Search code examples
environment-variablesgithub-actions

How to set GitHub Actions ENV with python shell


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?


Solution

  • 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