Issue
Is it possible to re-assign the variable value a few times inside IF in one script block? I have a script block where I need to pass variable values to different environments:
script {
if (env.DEPLOY_ENV == 'staging') {
echo 'Run LUX-staging build'
def ENV_SERVER = ['192.168.141.230']
def UML_SUFFIX = ['stage-or']
sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'
echo 'Run STAGE ADN deploy'
def ENV_SERVER = ['192.168.111.30']
def UML_SUFFIX = ['stage-sg']
sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'
echo 'Run STAGE SG deploy'
def ENV_SERVER = ['stage-sg-pbo-api.example.com']
def UML_SUFFIX = ['stage-ba']
sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'
}
}
But I receive an error in Jenkins job on second variable assignment:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 80: The current scope already contains a variable of the name ENV_SERVER
@ line 80, column 11.
def ENV_SERVER = ['192.168.111.30']
^
WorkflowScript: 81: The current scope already contains a variable of the name UML_SUFFIX
@ line 81, column 11.
def UML_SUFFIX = ['stage-sg']
^
Or perhaps any other ways to multiple assignment inside one IF part of script block.
Solution
Using def
defines the variable. This is only needed on the first call.
so removing the def on the other calls should work
script {
if (env.DEPLOY_ENV == 'staging') {
echo 'Run LUX-staging build'
def ENV_SERVER = ['192.168.141.230']
def UML_SUFFIX = ['stage-or']
sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'
echo 'Run STAGE ADN deploy'
ENV_SERVER = ['192.168.111.30']
UML_SUFFIX = ['stage-sg']
sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'
echo 'Run STAGE SG deploy'
ENV_SERVER = ['stage-sg-pbo-api.example.com']
UML_SUFFIX = ['stage-ba']
sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'
}
}
The variables will only be scoped to the if block, so you wont have access to them outside that block.
Answered By - apr_1985
Answer Checked By - Cary Denson (JavaFixing Admin)