我找不到在sh脚本中使用jenkins提供的BUILD_NUMBER的方法。我读了一些类似问题的答案,但似乎无济于事。
node {
echo "Build number 1 $BUILD_NUMBER"
// output ok
stage('stage1') {
echo "Build number 2 $BUILD_NUMBER"
// output ok
def BUILD_NUMBER = "$BUILD_NUMBER"
withCredentials([sshUserPrivateKey(credentialsId: 'github-rsa-key', variable: 'RSAKEY')]) {
echo "Build number 3 " + BUILD_NUMBER
// output ok
echo "Build number 4 $BUILD_NUMBER"
// output ok
// -----------------
sh 'echo $BUILD_NUMBER' // NullPointer
sh "echo $BUILD_NUMBER" // NullPointer
sh "echo \$BUILD_NUMBER" // NullPointer
sh "echo BUILD_NUMBER" // NullPointer
withEnv(["BUILD_NUMBER=BUILD_NUMBER"]) {
sh "echo $BUILD_NUMBER" // NullPointer!!
}
env.BUILD_NUMER = "$BUILD_NUMBER"
sh "echo $BUILD_NUMBER" // NullPointer
sh "echo ${env.BUILD_NUMBER}" // NullPointer
}
}
}
答案 0 :(得分:2)
这是一个对我有用的简单示例。詹金斯2.164.2
编辑以添加物理脚本:/tmp/script.sh包含..
#!/bin/bash
echo "Script: - Build number: $BUILD_NUMBER"
还有詹金斯的工作
node {
echo "Node: Build number: $BUILD_NUMBER"
stage('stage1') {
echo "Stage: Build number: $BUILD_NUMBER"
sh ("echo Shell: Build number: $BUILD_NUMBER")
sh ("/tmp/script.sh")
}
}
此示例使用“ withCredentials”块。注意这里引用的单引号-https://jenkins.io/doc/pipeline/steps/credentials-binding/
node {
echo "Build number 1 $BUILD_NUMBER"
// output ok
stage('stage1') {
withCredentials([string(credentialsId: 'my_password', variable: 'TOKEN')]) {
sh '''
echo "Shell: Build number: $BUILD_NUMBER"
'''
sh ('/tmp/script.sh')
}
}
}
答案 1 :(得分:0)
可能有一种更惯用的方法(请分享,如果您知道的话),但是如果您首先在environment
块中定义它,则它会起作用。像这样:
stage('Show Build Number') {
environment {
BUILD_NUMBER = "${env.BUILD_NUMBER}"
}
steps {
sh '''
echo "This is build $BUILD_NUMBER"
'''
}
}
在code maven上有一篇很好的文章,其中包含有用的示例。
答案 2 :(得分:0)
基本解决方案:将外壳程序脚本包装在"""
块中
node {
echo "Build number 1: $BUILD_NUMBER"
// output ok
stage('stage1') {
echo "Build number 2: $BUILD_NUMBER"
// output ok
def BUILD_NUMBER = "$BUILD_NUMBER"
echo "Build number 3: " + BUILD_NUMBER
// output ok
echo "Build number 4: $BUILD_NUMBER"
// output ok
// -----------------
sh 'printenv'
sh """
echo "Build number in sh script: ${env.BUILD_NUMBER}"
echo "Job base name: ${env.JOB_BASE_NAME}"
"""
// output ok
}
}
控制台输出:
Running on Jenkins in /var/lib/jenkins/workspace/test-infra-env
[Pipeline] {
[Pipeline] echo
Build number 1: 5
[Pipeline] stage
[Pipeline] { (stage1)
[Pipeline] echo
Build number 2: 5
[Pipeline] echo
Build number 3: 5
[Pipeline] echo
Build number 4: 5
[Pipeline] sh
+ printenv
JENKINS_HOME=/var/lib/jenkins
MAIL=/var/mail/jenkins
USER=jenkins
...
...
JOB_BASE_NAME=test-infra-env
BUILD_NUMBER=5
...
...
[Pipeline] sh
+ echo Build number in sh script: 5
Build number in sh script: 5
+ echo Job base name: test-infra-env
Job base name: test-infra-env
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS