![](/img/trans.png)
[英]SSH keys in build environment when using multibranch pipeline Jenkinsfile
[英]Reduce Stages in Jenkinsfile when using Multibranch Pipeline
在这个 Jenkinsfile 中,我试图为多分支管道中的不同分支执行相同的阶段。 我每次都需要配置每个分支名称的环境变量。 有没有更好的方法来做到这一点?
stage('Create New AMI for master branch') {
when { branch 'master' }
environment {
BRANCH_NAME = "${env.BRANCH_NAME}"
ENV_NAME = "prod"
}
steps {
sh "packer build jenkins/${PROJECT_NAME}/${PROJECT_NAME}-ami.json"
}
}
stage('Create New AMI for development branch') {
when { branch 'development' }
environment {
BRANCH_NAME = "${env.BRANCH_NAME}"
ENV_NAME = "dev"
}
steps {
sh "packer build jenkins/${PROJECT_NAME}/${PROJECT_NAME}-ami.json"
}
}
stage('Create New AMI for staging branch') {
when { branch 'staging' }
environment {
BRANCH_NAME = "${env.BRANCH_NAME}"
ENV_NAME = "staging"
}
steps {
sh "packer build jenkins/${PROJECT_NAME}/${PROJECT_NAME}-ami.json"
}
}
在这种情况下,请使用共享库,它将包含您所有的阶段实现。参考示例实现,如下所示。
创建一个名为:sharedlibraries(groovy 文件)的文件
#!groovy
// Write or add Functions(definations of stages) which will be called from your jenkins file
def Create_AMI(PROJECT_NAME, ENV_NAME)
{
echo ENV_NAME
sh "packer build jenkins/${PROJECT_NAME}/${PROJECT_NAME}-ami.json"
// You can also set the environment below example:
env.ENV_NAME ="dev"
}
return this
在您的 Jenkinsfile 中编写以下代码:
// Global variable is used to get data from groovy file(shared library)
def stagelibrary
stage('Create New AMI') {
steps {
script {
// Load Shared library Groovy file stagelibraries.Give your path of stagelibraries file whic is created
stagelibrary = load 'C:\\Jenkins\\stagelibraries'
// Execute Create_AMI function. You can add if else conditions over here, based on your branches. But am not sure of your conditions.
// You can also pass your environment variable
// in the Crete_AMI function using env.<YOURENVVARIABLE>
stagelibrary.Create_AMI(PROJECT_NAME,env.ENV_NAME)
}
}
}
上面的示例显示了共享库的概述,您不需要编写相同的函数/或冗余阶段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.