7

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

1
  • Please paste your code and log in your answer instead of having images. Commented Apr 29, 2020 at 9:25

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.