简体   繁体   中英

Dynamic variable in Jenkins pipeline with groovy method variable

I have a Jenkinsfile in Groovy for a declarative pipeline and two created Jenkins variables with names OCP_TOKEN_VALUE_ONE and OCP_TOKEN_VALUE_TWO and the corresponding values. The problem comes when I try to pass a method variable and use it in an sh command.

I have the next code:

private def deployToOpenShift(projectProps, environment, openshiftNamespaceGroupToken) {  
  sh """/opt/ose/oc login ${OCP_URL} --token=${openshiftNamespaceGroupToken} --namespace=${projectProps.namespace}-${environment}"""
}

The problem is, the method deployToOpenShift has in the openshiftNamespaceGroupToken variable, a value that is the name of variable that has been set in Jenkins. It needs to be dynamic and the problem is that Jenkins don't resolve the Jenkins variable value, just the one passed as String, I mean, the result is:

--token=OCP_TOKEN_VALUE_ONE

If I put in the code

private def deployToOpenShift(projectProps, environment, openshiftNamespaceGroupToken) {  
  sh """/opt/ose/oc login ${OCP_URL} --token=${OCP_TOKEN_VALUE_ONE} --namespace=${projectProps.namespace}-${environment}"""
}

works perfect but is not dynamic that is the point of the method variable. I have tried with the """ stuff as you can see, but not working.

Any extra idea?

Edited with the code that calls the method:

...
projectProps = readProperties file: './gradle.properties'
openShiftTokenByGroup = 'OCP_TOKEN_' + projectProps.namespace.toUpperCase()

...

stage ('Deploy-Dev') {
  agent any
  steps {
    milestone ordinal : 10, label: "Deploy-Dev Milestone"
    deployToOpenShift(projectProps, 'dev', openShiftTokenByGroup)
  }
}

I have got two different ways to do that. One is using evaluate from groovy like this:

def openShiftTokenByGroup = 'OCP_TOKEN_' + projectProps.namespace.toUpperCase()

evaluate("${openShiftTokenByGroup}") //This will resolve the configured value in Jenkins

The second one is the same approach but in the sh command with eval escaping the $ character:

sh """ 
eval \$$openShiftTokenByGroup
echo "Token: $openShiftTokenByGroup
 """

This will do the magic too and you'll get the Jenkins configured value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM