本文介绍如何在pipeline中使用变量

使用jenkins预定义的环境变量

jenkins预先定义了一些环境变量,在pipeline中使用${env.key}来调用
另外安装了第三方插件,会有新的环境变量,可以使用插件Environment Inject来查看

在pipeline中使用预定义的环境变量,来调用BUILD_ID等环境变量
pipeline{
    agent any
    stages{
        stage("Build Test"){
            steps{
                echo "The build id is ${env.BUILD_ID}"
            }
        }
        stage("UT Test"){
            steps{
                echo "The build number is ${env.BUILD_NUMBER}"
            }
        }
    }
}

build之后的console output:

在这里插入图片描述

在pipeline中使用自定义的环境变量

使用environment指令来定义环境变量,可以定义pipeline块的环境变量,适用于所有stage,也可以只在stage中定义环境变量,只适用于改stage,调用时使用$key来调用

在pipeline中定义使用自定义的环境变量
pipeline{
    agent any
    environment{
        UseAll="Testone"
    }
    stages{
        stage("Build Test"){
            steps{
                echo "print UseAll ${UseAll}"
            }
        }
        stage("Test"){
            environment{
                UseOnly="useronley"
            }
            steps{
                echo "print UseAll ${UseAll}"
                echo "print UseOnly ${UseOnly}"
            }
        }
    }
}

build的结果

在这里插入图片描述

参数化构建pipeline

可以使用parameters来参数化构建pipeline,也就是构建的时候选择或者输入参数
在pipeline中使用${params.key}来调用参数

创建一个pipeline job,参数化构建pipeline
pipeline{
    agent any
    parameters{
        string(name:"deploy_env",defaultValue:"test",description:"deploy env")
        choice(name:"mychoice",choices:["One","Two","Thress"],description:"")
    }
    stages{
        stage("Build Test"){
            steps{
                echo "deploy env is ${params.deploy_env}"
                echo "choices is ${params.mychoice}"
            }
        }
    }
}

build结果:
在这里插入图片描述

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐