I have a requirement where I want to create an Service Now Incident only when a previous similar incident is closed. I am using Jenkins freestyle Job. The approach I have taken is as below:-
- Create a Global environment variable to store Incident Number and set a default value.
- Check the state of the incident in an upstream job and pass the state to the downstream job.
- In the downstream job, if the incident is still open, do nothing. If it is Closed/Resolved, create
another Incident with some defined descriptions.
- Update the global environment variable with the current Incident no. and store it permanently.
- Check the state of the updated Incident Number(by accessing the global Environment Variable) and then
follow the same process during subsequent builds.
Till now I have achieved till step 3 by using various plugins. To achieve step 4, I am using groovy post-build plugin, so that I can update the global environment variable permanently, so that it is available in my next build, so that I can check the status of the incident before creating a new one.
I have come-up with a code, but it does not seem to update the variable permanently(Verified by printing the variable in a subsequent build). The script also has other parts as per my requirement but SNOW_INC is the global variable that I want to update permanently, till the next build.
import groovy.json.JsonSlurper
import hudson.model.*
def workspace = manager.build.getEnvVars()["WORKSPACE"]
def console = manager.listener.logger.&println
build = Thread.currentThread().executable
String jobName = build.project.getName()
job = Hudson.instance.getJob(jobName)
my_env_var = job.getLastBuild().getEnvironment()["SNOW_INC"]
console(my_env_var)
try{
def inputFile = new File(workspace, 'response.json')
if (inputFile != null){
JsonSlurper slurper = new JsonSlurper()
parsedJson = slurper.parse(inputFile)
String number= parsedJson.result.number
console("${number}")
System.setProperty("hudson.model.ParametersAction.safeParameters", "INC_NUMBER")
manager.build.addAction(
new ParametersAction(
new StringParameterValue("INC_NUMBER", "${number}")
)
)
manager.build.addAction(
new ParametersAction(
new StringParameterValue("SNOW_INC", "${number}")
)
)
console("Environment Variable set")
}
} catch (Exception e){
println("response.json file was not ")
}
Any help would be appreciated!
question from:
https://stackoverflow.com/questions/65932817/how-can-i-update-a-global-environment-variable-using-groovy-postbuild-in-jenkins 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…