2

Okay, here is a common example how to set ENVs if we have a bash shell:

...

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Set environment variable
        shell: bash
        run: echo "ENV_NAME=ENV_VALUE" >> "${GITHUB_ENV}"

      - name: Get environment variable
        shell: bash
        run: echo "A value of ENV_NAME is ${{ env.ENV_NAME }}"      

But what if our shell is a python?:

...

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Set environment variable with python
        shell: python
        # How to set ENV with python?
        run: ???

How to set ENV with python?

2
  • 1
    What happens in that shell script line is that a piece of text is appended to the filename stored in the GITHUB_ENV variable. Using the standard Python file.WriteLines function should work just fine. Commented Jan 10, 2023 at 10:27
  • @jessehouwing stupid me... it was obvious. Working like a charm Commented Jan 10, 2023 at 11:13

1 Answer 1

2

Thanks to @jessehouwing comment: GITHUB_ENV is just a file name. And we able to insert variable by editing this file:

...

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Set environment variable with python
        shell: python
        run: |
          from os import environ as env

          file_path = env.get('GITHUB_ENV', None)
          if file_path is None:
            raise OSError('Environment file not found')

          with open(file_path, 'a') as gh_envs:
            gh_envs.write('ENV_NAME=ENV_VALUE\n')

GITHUB_ENV is not a part of env context, so open('${{ env.GITHUB_ENV }}', 'a') can not be used

Sign up to request clarification or add additional context in comments.

3 Comments

That does not fully work as is read by python as "***" if you want a secret. The problem is that github obfuscates the secret. I am still trying to figure out a solution.
@user18140022 All secrets already accessible via secrets.SECRET_NAME context. Also it may be set inside env: key like ENV_NAME: ${{secrets.SECRET_NAME}. I can't imagine why you need to assign secret environment variable via python
I need different envs for dev, qa, prod. In each environment there are credentials for different databases. That's why I need to assign secret environment variables. I could obvs set them all as repo secret but not ideal

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.