[英]Using git branch in environment variable in Jenkinsfile
I would like to customize one of environment variable depending on branch that is being build. 我想根据正在构建的分支来自定义环境变量之一。
environment {
CUSTOM_ENV='xyz_${GIT_BRANCH}'
}
I'd like to get CUSTOM_ENV=xyz_dev
for origin/dev
and CUSTOM_ENV=xyz_master
for origin/master
. 我想获得
CUSTOM_ENV=xyz_dev
为origin/dev
和CUSTOM_ENV=xyz_master
为origin/master
。 Not sure if its important, but its multibranch project in Jenkins. 不确定它是否重要,但是不确定它在詹金斯的多分支项目。
I tried things like xyz_${GIT_BRANCH}
or xyz_env.GIT_BRANCH
, but none of this worked out. 我尝试了诸如
xyz_${GIT_BRANCH}
或xyz_env.GIT_BRANCH
,但是都没有解决。
If your shell happens to be compatible with ksh
or bash
then you can use the variable-expansion modifier ##
to discard everything up to and including the final /
character, leaving get just the part of ${GIT_BRANCH}
that comes after that /
. 如果您的外壳碰巧与
ksh
或bash
兼容,则可以使用变量扩展修饰符##
舍弃所有字符,直到最后一个/
字符为止,只保留${GIT_BRANCH}
后面/
。 That would look like: 看起来像:
CUSTOM_ENV="xyz_${GIT_BRANCH##*/}"
Note the double-quotes "
rather than the single-quotes '
you used in your question. Single-quotes prevent the evaluation of variables inside the quoted string, and that's definitely not what you want in this case. 请注意问题中使用的双引号
"
而不是单引号'
。单引号阻止对带引号的字符串内的变量求值,在这种情况下,这绝对不是您想要的。
If your shell does not understand the ##
modifier then you'll have to use something like sed
to get just the last part of ${GIT_BRANCH}
. 如果您的外壳不理解
##
修饰符,则必须使用sed
东西来获取${GIT_BRANCH}
的最后一部分。 That would look like this: 看起来像这样:
CUSTOM_ENV="xyz_$(echo ${GIT_BRANCH} | sed -e 's@.*/@@')"
When you are doing a substitution in jenkinsfile for a variable. 当您在jenkinsfile中进行变量替换时。 It should always be in
""
. 它应该始终在
""
。 From environment directive , I guess you are using pipelines. 根据环境指令,我猜您正在使用管道。 So, you can leverage the groovy syntax to achieve string manipulation.
因此,您可以利用常规语法来实现字符串操作。 Something like,
就像是,
environment {
GIT_BRANCH = 'orgin/master'.split('/')[1]
CUSTOM_ENV="xyz_${GIT_BRANCH}"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.