Hugo
Hugo

Reputation: 1304

Update Gitlab environment variables from a python script in a pipeline

I am trying to update a Gitlab environment variable from a python scripts :

In the gitlab-ci.yml

gitlab_job:
  stage: gitlab_stage
  script:
    - python set_myvar.py
    - echo $MYVAR

In the set_myvar.py

import os
os.environ["MYVAR"] = my_value

I don't need the variable to persist. I just need it to be programmaticaly updated (from python).

So far, it doesnt do anything.

Upvotes: 0

Views: 2114

Answers (1)

Kurtis Rader
Kurtis Rader

Reputation: 7459

That won't work. The UNIX process model requires certain attributes to be private to a process. This includes such things as the current working directory of the process and its environment variables. Each of these private attributes is inherited; either implicitly or explicitly depending on how the child process is spawned by its parent process. A child process cannot modify those private attributes of its parent.

There are ways to workaround the aforementioned limitation. For example, the child process could write the new var=value pairs to stdout. The parent process that runs your python program can then read those strings and add them to its environment. In your case your python program would do print("MYVAR=my_value") and you would run it from your gitlab script as eval $(python set_myvar.py).

Upvotes: 1

Related Questions