Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set environment variables in GitHub actions using python

I want to execute a python script to set some environment variables in GitHub actions. I want to use those environment variables later in my GitHub actions steps. My python script looks like:

new_ver = get_version_from_commit(commit_msg)
if new_ver:
    if new_ver == "false":
        os.environ["SHOULD_PUSH"] = "0"
        print("Not pushing the image to k8s")
        exit(0)
    else:
        new_tag = app_name + ":" + str(new_ver)
        os.environ["DOCKER_IMAGE_TAG"] = new_tag
        os.environ["SHOULD_PUSH"] = "1"
        print("New tag: " + new_tag)
        exit(0)

Part of my GitHub actions file, after the execution of the above python script looks like:

- name: Print env var
  run: echo ${{ env.DOCKER_IMAGE_TAG }}
- name: Build and push
  id: docker_build
  uses: docker/build-push-action@v2
  with:
     push: true
     tags: ${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE_TAG }}

But using os.environ won't expose the environment variable outside of the python process. How can I fix this ?

like image 547
Rumesh Madhusanka Avatar asked Dec 03 '25 09:12

Rumesh Madhusanka


1 Answers

You cannot set environment variables directly. Instead, you need to write your environment variables into a file, whose name you can get via $GITHUB_ENV.

In a simple workflow step, you can append it to the file like so (from the docs):

echo "{name}={value}" >> $GITHUB_ENV

In python, you can do it like so:

import os

env_file = os.getenv('GITHUB_ENV')

with open(env_file, "a") as myfile:
    myfile.write("MY_VAR=MY_VALUE")

Given this python script, you can set and use your new environment variable like the following:

- run: python write-env.py
- run: echo ${{ env.MY_VAR }}
like image 92
rethab Avatar answered Dec 04 '25 21:12

rethab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!