是否可以在一个脚本块中的 IF 内多次重新分配变量值? 我有一个脚本块,我需要将变量值传递给不同的环境:
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'
}
}
但是我在 Jenkins 作业中在第二个变量赋值中收到一个错误:
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']
^
或者在脚本块的一个 IF 部分内进行多重赋值的任何其他方法。
答案 0 :(得分:1)
使用 def
定义变量。这仅在第一次调用时需要。
所以删除其他调用的 def 应该可以工作
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'
}
}
变量的作用域只限于 if 块,因此您无法在该块之外访问它们。