I am writing a Jenkins declarative pipeline script with a powershell script inside it. When I try to get the value of an environment variable inside powershell, I get its "original" value, as defined on the environment
block, and not the value set in a previuous stage. The withEnv
block doesn't work either. Example:
pipeline {
agent any
environment { TEST_ENV_VAR = "0" }
stages {
stage('stage1') {
failFast true
parallel {
stage('stage1.1') {
steps {
script {
TEST_ENV_VAR = "1"
}
}
}
}
}
stage('stage2') {
failFast true
parallel {
stage('stage2.1') {
steps {
echo "$TEST_ENV_VAR" // prints "1"
withEnv(["inv_var = $TEST_ENV_VAR"]) {
withCredentials([usernamePassword(credentialsId: "$CredentialsID", passwordVariable: 'password', usernameVariable: 'srvUser')]) {
echo "$TEST_ENV_VAR" // prints "1"
echo "$env.inv_var" // prints "null"
powershell label: 'pshell', returnStatus: true, script: '''
echo "$env:TEST_ENV_VAR" # prints "0"
echo "$env:inv_var" # prints nothing
'''
}
}
}
}
}
}
}
}
It's a very simple answer, and very sad that groovy doesn't help more. Inside withEnv, you must not have a space between the variable and the equals sign. Here's your code with the credentials removed (because i don't have them), and the only other change is removing two spaces
pipeline {
agent any
environment { TEST_ENV_VAR = "0" }
stages {
stage('stage1') {
failFast true
parallel {
stage('stage1.1') {
steps {
script {
TEST_ENV_VAR = "1"
}
}
}
}
}
stage('stage2') {
failFast true
parallel {
stage('stage2.1') {
steps {
echo "$TEST_ENV_VAR" // prints "1"
withEnv(["inv_var=$TEST_ENV_VAR"]) {
echo "$TEST_ENV_VAR" // prints "1"
echo "$env.inv_var" // now prints "1"
powershell label: 'pshell', returnStatus: true, script: '''
echo "$env:TEST_ENV_VAR" # prints "0"
echo "$env:inv_var" # now prints "1"
'''
}
}
}
}
}
}
}
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.