Expand ENV vars from String

Viewed 25

How can I expand ${ENV} variables in Jenkins Pipeline if they are in a string I do not control?

For example I have configured my Pipeline Job to load the Pipeline from a parameterized SCM:

parameterized scm

If I now access that branch via scm.branches[0].name inside the Pipeline I am currently getting ${REF}, too.

(The checkout scm part of the pipeline works fine, thats not the problem.)

I have tried the tm() step, but that throws org.jenkinsci.plugins.tokenmacro.MacroEvaluationException: Unrecognized macro 'REF' in '${REF}'


I for example cannot use to update the build name:

currentBuild.displayName = "${scm.branches[0].name} (#$BUILD_NUMBER)"
1 Answers

If REF is an Environment variable you can use String interpolation. Just put the variable into double quotes within the pipeline.

echo "${REF}"

Update

Not sure if there is better groovy way to do this. But following is an option you can use.

steps {
    script {
        script {
             echo "${scm.branches[0].name}"
             String branchName = "${scm.branches[0].name}"
             String envNameOnly = branchName.substring(2, branchName.length()-1)
             def env = System.getenv()[envNameOnly]
             echo "$env"
        } 
    }
}
Related