在GitLab-ci中动态设置全局变量 [英] set up global variables dynamically in gitlab-ci
本文介绍了在GitLab-ci中动态设置全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过从pom.xml文件获取值来设置一些变量。这些变量需要是全局变量,因为它们将在多个阶段和作业中使用。
根据GitLab-ci文档,我可以通过两种不同的方式设置全局变量:
使用变量语句:
variable: pom_artifactID: $(grep -m1 '<artifactId>' pom.xml | cut -d '<' -f2 |cut -d '>' -f2)
使用"之前"脚本:
before_script: - pom_artifactID=$(grep -m1 '<artifactId>' pom.xml | cut -d '<' -f2 |cut -d '>' -f2) - pom_artifactVersion=$(grep -m1 '<version>' pom.xml | cut -d '<' -f2 |cut -d '>' -f2) - pom_packaging=$(grep -m1 '<packaging>' pom.xml | cut -d '<' -f2 |cut -d '>' -f2) - pom_finalName=$({ grep -m1 '<finalName>' pom.xml | cut -d '<' -f2 | cut -d '>' -f2; [ ${PIPESTATUS[0]} -eq 0 ] && true || echo ${pom_artifactID}-${pom_artifactVersion}.$pom_packaging}; })
第一个不起作用,因为GitLab-ci不求值$(Command),所以pom_artifactID
变成文字"$(grep-m1‘’pom.xml|cut-d‘<;’-f2|cut-d‘>’-f2)"
第二个也不起作用,因为"BEFORE_SCRIPT"依赖于"grep"命令,而我的管道中使用的某些停靠器映像使用的是旧版本的grep。
是否还有其他方法可以设置全局变量以在阶段和作业之间传递变量?
推荐答案
在作业和阶段之间传递值
GitLab中当前无法在阶段或作业之间传递环境变量。
但是有这样的请求:https://gitlab.com/gitlab-org/gitlab/-/issues/22638
当前解决方法是使用项目-基本上传递文件。
我们有一个类似的用例-从pom.xml
获取Java应用程序版本,并稍后将其传递给管道中的各个作业。
我们在.gitlab-ci.yml
中是如何做到的:
stages:
- prepare
- package
variables:
VARIABLES_FILE: ./variables.txt # "." is required for image that have sh not bash
get-version:
stage: build
script:
- APP_VERSION=...
- echo "export APP_VERSION=$APP_VERSION" > $VARIABLES_FILE
artifacts:
paths:
- $VARIABLES_FILE
package:
stage: package
script:
- source $VARIABLES_FILE
- echo "Use env var APP_VERSION here as you like ..."
 ;
 ;
正在从pom.xml
提取值
顺便说一句,最好将xml.pom
视为从pom.xml
提取值的XML,而不是普通的grep
,因为XML元素可能跨越多行。
至少有几个选项,例如:
- 在
libxml2-utils
中的xmllint
工具中使用XPath
get-version:
image: ubuntu
script:
- apt-get update
- apt-get install -y libxml2-utils
- APP_VERSION=`xmllint --xpath '/*[local-name()="project"]/*[local-name()="version"]/text()' $POM_FILE`
- 使用
python
XML处理
get-version:
image: python3
script:
- APP_VERSION=$(python3 -c "import xml.etree.ElementTree as ET; print(ET.parse(open('pom.xml')).getroot().find('{http://maven.apache.org/POM/4.0.0}version').text)")
这篇关于在GitLab-ci中动态设置全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文