【问题标题】:set up global variables dynamically in gitlab-ci在 gitlab-ci 中动态设置全局变量
【发布时间】:2020-06-25 13:39:33
【问题描述】:

我想通过从 pom.xml 文件中获取值来设置一些变量。这些变量需要是全局变量,因为它们将在多个阶段和作业中使用。

根据 gitlab-ci 文档,我可以通过两种不同的方式设置全局变量:

  1. 使用变量语句:

    variable:  
     pom_artifactID: $(grep -m1 '<artifactId>' pom.xml | cut -d '<' -f2  |cut -d '>' -f2)
    
  2. 使用“之前”脚本:

     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)"

第二个也不起作用,因为“before_script”依赖于“grep”命令,并且我的管道中使用的一些 docker 映像具有旧版本的 grep。

还有另一种方法来设置全局变量或在阶段和作业之间传递变量吗?

【问题讨论】:

    标签: global-variables gitlab-ci


    【解决方案1】:

    在作业和阶段之间传递值

    GitLab 目前无法在阶段或作业之间传递环境变量。
    但是有一个要求:https://gitlab.com/gitlab-org/gitlab/-/issues/22638

    当前的解决方法是使用 artifacts - 基本上是传递文件。
    我们有一个类似的用例 - 从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 视为XML 以从pom.xml 中提取值而不是普通的grep,因为XML 元素可能跨越多行。

    至少有几个选项,例如:

    1. xmllint 工具中使用来自libxml2-utils 的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`
    
    1. 使用pythonxml处理
    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)")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-07
      • 1970-01-01
      • 2023-03-15
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      • 1970-01-01
      相关资源
      最近更新 更多