【问题标题】:Gitlab-CI environment variable from Python script to pipeline从 Python 脚本到管道的 Gitlab-CI 环境变量
【发布时间】:2020-04-29 07:41:14
【问题描述】:

如何从 python 脚本中获取 gitlab-ci 环境变量 VERSION 值 - get_version.py 用于 gitlab-runners,它可以在 OS windows 和 linux 上运行? 我需要一些通用解决方案,以便它可以在两个操作系统上运行。

这是我的.gitlab-ci.yml

stages:
  - versioning

variables:
  VERSION: ""

versioning:
  stage: versioning
  script:
  - echo "[versioning] ..."
  - python ./ci-cd_scripts/get_version.py
  - echo $VERSION

这是我的./ci-cd_scripts/get_version.py

import os

refName = os.environ.get("CI_COMMIT_REF_NAME")
piplineID = os.environ.get("CI_PIPELINE_ID")
relVersion = refName + ".0." + piplineID

version = relVersion.replace("rel.", "")
print("current version is", version)

python output in pipeline log

【问题讨论】:

  • 请粘贴您的代码并登录您的答案,而不是使用图像。

标签: python gitlab environment-variables gitlab-ci


【解决方案1】:

我发现可行的方法是将其保存到临时文件中。

import os

refName = os.environ.get("CI_COMMIT_REF_NAME")
piplineID = os.environ.get("CI_PIPELINE_ID")
relVersion = refName + ".0." + piplineID

version = relVersion.replace("rel.", "")
print("current version is", version)
with open('.env', 'w') as writer:
     writer.write(f'export VERSION="{version}"')

然后在管道中,您只需使用 .env 文件导出变量

script:
  - ./ci-cd_scripts/get_version.py
  - source .env
  - echo $VERSION

【讨论】:

    【解决方案2】:

    修改您的get_version.py python 脚本以具有:

    #!/usr/bin/python3
    
    print("export VERSION='{}'".format(value))
    

    然后在您的管道中:

    script:
      - eval `python ./ci-cd_scripts/get_version.py`
      - echo $VERSION
    

    【讨论】:

    • 但此解决方案不适用于 Windows 运行器,因为 CMD 或 Powershell 不支持“eval”命令。我需要一个通用的解决方案,以便它适用于操作系统 Windows 和 Linux 上的跑步者
    【解决方案3】:

    一般情况下是不可能的

    您可以在 Python 脚本中使用 os.environ 设置和修改环境变量,但随着脚本完成,一切都会恢复到之前的值。

    阅读 StackOverflow 上的这些帖子会很有帮助:

    Why can't environmental variables set in python persist?
    How do I make environment variable changes stick in Python?
    Environment Variables in Python on Linux

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-20
      • 2022-01-19
      • 2021-04-17
      • 2020-11-09
      • 2021-03-20
      • 2018-07-25
      • 2021-12-14
      • 2020-11-13
      相关资源
      最近更新 更多