首页 > 解决方案 > 在 .gitlab-ci.yml 中设置一个从 pom 读取 artifactId 名称的变量

问题描述

在 .gitlab-ci.yml 我们定义了一个变量(它只是项目的 artifactId 名称)ARTIFACT_ID: myMicroservice-1

这个变量ARTIFACT_ID被发送到一个通用的微服务,该微服务具有发布/部署 docker 等的所有脚本。

如何直接从 POM 文件中读取此变量?

起居室:

<artifactId>myMicroservice-1</artifactId>

.gitlab-ci.yml:
variables:
  SKIP_UNIT_TESTS_FLAG: "true"
  ARTIFACT_ID: myMicroserverName
  IS_OSL: "true"
  KUBERNETES_NAMESPACE: test

标签: mavengitlab-ci

解决方案


这是我们如何做到的。

pom.xml值是根据其 XPath提取的。
我们使用xmllint来自 的工具libxml2-utils,但还有其他各种工具。
然后将值保存为文件中的环境变量,该文件作为工件传递给进一步的 GitLab 作业。

stages:
  - prepare
  - build

variables:
  VARIABLES_FILE: ./variables.txt  # "." is required for sh based images
  POM_FILE: pom.xml

get-version:
  stage: prepare
  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`
    - echo "export APP_VERSION=$APP_VERSION" > $VARIABLES_FILE
  artifacts:
    paths:
      - $VARIABLES_FILE

build:
  stage: build
  image: docker:latest
  script:
    - source $VARIABLES_FILE
    - echo "Here use $APP_VERSION as you like"

推荐阅读