Way to change Jenkins' project variable value with script

柔情痞子 提交于 2019-12-12 01:43:58

问题


Is there a way to change project variable values in Jenkins automatically when build is done? In my case i got a variable VERSION, default value is 1. And i need to increment this default value every build done. Assuming build stars by cron in this case. Any plugins can help me?

Now i have something like this: My build steps. It is a single working way to get project variable in my groovy script that i found. Now how can i set new value for variable? I read some similar question on SO, but didn't found a working way for me.

P.S. I can't use $BUILD_NUMBER var, because i need a possibility to set VERSION manually when i start build.


回答1:


First, of all, install the plugins Global Variable String Parameter Plugin and Groovy Postbuild Plugin. Under Manage Jenkins -> Configure System you should now have a part, called Global Properties. There you add a new variable. In my tests, I called it SOME_VER.

At your job, you now add a Groovy postbuild part with this code adjusted to your variable:

import jenkins.*;
import jenkins.model.*;
import hudson.*;
import hudson.model.*;
import java.lang.*;

instance = Jenkins.getInstance();
globalNodeProperties = instance.getGlobalNodeProperties();
envVarsNodePropertyList = globalNodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class);

envVars = null

if (envVarsNodePropertyList != null && envVarsNodePropertyList.size() > 0) 
{
    envVars = envVarsNodePropertyList.get(0).getEnvVars()

    String value = envVars.get("SOME_VER", "0")
    int NEW_VER = Integer.parseInt(value)
    NEW_VER = NEW_VER + 1

    envVars.override("SOME_VER", NEW_VER.toString());
}

instance.save()

Parts of this code are taken from here. This code does nothing else than retrieving the value of the global variable, change it and save the new value of the variable.



来源:https://stackoverflow.com/questions/42164225/way-to-change-jenkins-project-variable-value-with-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!