5

How I can get the gitlab-ci environment variable VERSION value from the python script - get_version.py for a gitlab-runners which will work on both OS windows and linux? I need some universal solution so that it works on both OS.

Here is my .gitlab-ci.yml :

stages:
  - versioning

variables:
  VERSION: ""

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

Here is my ./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

Denis Mozhaev
  • 59
  • 1
  • 1
  • 6

3 Answers3

5

what I found that works is to save it to a temp file.

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

and then in the pipeline you just export the variable using the .env file

script:
  - ./ci-cd_scripts/get_version.py
  - source .env
  - echo $VERSION
paul
  • 51
  • 1
  • 2
1

It is not normally possible

You can set and modify environment variables using os.environ inside Python scripts but as the scripts is finished, everything goes back to the previous value.

It would be helpful to read these posts on 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

Amir Dadkhah
  • 1,074
  • 2
  • 11
  • 17
1

Modify your get_version.py python script to have :

#!/usr/bin/python3

print("export VERSION='{}'".format(value))

and then in your pipeline :

script:
  - eval `python ./ci-cd_scripts/get_version.py`
  - echo $VERSION
Nicolas Pepinster
  • 5,413
  • 2
  • 30
  • 48
  • 1
    But this solution will not work on Windows runner, because "eval" command not supported in CMD or Powershell. I need a universal solution so that it works for runners on both OS Windows and Linux – Denis Mozhaev Apr 29 '20 at 09:39