直接使用环境变量
pipeline {agent {label "${28}"}stages {stage("git clone"){steps{script{sh """pwdls"""// 环境变量的使用// 输出所有环境变量 echo "All environment variables: ${env}" // 输出单个环境变量的值 echo "HOME directory: ${env.HOME}" echo "Jenkins user: ${env.USER}" echo "Jenkins WORKSPACE: ${env.WORKSPACE}"// 遍历输出所有的环境变量 env.each { key, value -> echo "Environment variable $key: $value" }// 如下为/home/jenkins/program/jenkins/workspace/middle_nMedia_testecho "${WORKSPACE}"// 构建号echo "${BUILD_NUMBER}"echo "${WORKSPACE}/${BUILD_NUMBER}"}}}}
}
Console Output:
Started by user 昌显瑞
[Pipeline] Start of Pipeline
[Pipeline] node
Running on 192.168.3.28 in /home/jenkins/program/jenkins/workspace/middle_nMedia_test
[Pipeline] {
[Pipeline] stage
[Pipeline] { (git clone)
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ pwd
/home/jenkins/program/jenkins/workspace/middle_nMedia_test
+ ls
[Pipeline] echo
All environment variables: org.jenkinsci.plugins.workflow.cps.EnvActionImpl@2f5a9fc9
[Pipeline] echo
HOME directory: /home/jenkins
[Pipeline] echo
Jenkins user: jenkins
[Pipeline] echo
Jenkins WORKSPACE: /home/jenkins/program/jenkins/workspace/middle_nMedia_test
[Pipeline] echo
Environment variable org.jenkinsci.plugins.workflow.cps.EnvActionImpl@2f5a9fc9: null
[Pipeline] echo
/home/jenkins/program/jenkins/workspace/middle_nMedia_test
[Pipeline] echo
28
[Pipeline] echo
/home/jenkins/program/jenkins/workspace/middle_nMedia_test/28
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
通过environment间接使用
在environment中定义新的全局的环境变量,在后文中使用。
亦可以将参数化构建的参数在environment中赋值给新的环境变量,然后后文中同样可以使用。
pipeline {agent {label "28"}environment {// 通过环境变量定义新的变量work_dir = "${BUILD_NUMBER}"server_main_workspace = "${WORKSPACE}/${BUILD_NUMBER}"}stages {stage("git clone"){steps{script{sh """pwdls"""echo "${work_dir}"echo "${server_main_workspace}"}}}}
}
Console Output:
Started by user 昌显瑞
[Pipeline] Start of Pipeline
[Pipeline] node
Running on xxx.xxx.xx.xx in /home/jenkins/program/jenkins/workspace/xxxxxxxxx_test
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (git clone)
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ pwd
/home/jenkins/program/jenkins/workspace/xxxxxxxxx_test
+ ls
[Pipeline] echo
29
[Pipeline] echo
/home/jenkins/program/jenkins/workspace/xxxxxxxxx_test/29
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
一个好的教程链接