Jenkins声明式流水线里怎么设置环境变量?
我在写Jenkins的Declarative Pipeline,想在pipeline里定义一个全局的环境变量,比如API_URL,但不知道该放哪儿。试过放在agent外面,结果报错说语法不对。
看到文档说可以用environment块,但不确定是不是要放在stage里面还是整个pipeline顶层。我现在的写法像这样:
pipeline {
agent any
environment {
API_URL = 'https://api.example.com'
}
stages {
stage('Build') {
steps {
sh 'echo $API_URL'
}
}
}
}
这样写对吗?为啥有时候变量没生效?是不是位置放错了?
变量没生效大概率是因为sh步骤里的单引号问题。shell里单引号不会解析变量,所以改成这样:
pipeline {
agent any
environment {
API_URL = 'https://api.example.com'
}
stages {
stage('Build') {
steps {
sh "echo $API_URL"
sh 'echo ${API_URL}'
}
}
}
}
要么用双引号让变量展开,要么用${API_URL}明确指定。
另外在Jenkins里environment定义的变量在代码里访问要用
${env.API_URL},比如在脚本式步骤里或者when条件中。顺带提一句,如果是全局需要用的凭证啥的,用credentials()方法绑定到environment里更安全,别硬编码写在代码中。