How to pass secrets from GitHub Actions to python environ variables?

10.6k Views Asked by At

To run pytest within GitHub Actions, I have to pass some secrets for Python running environ. e.g.,

  - name: Test env vars for python
    run: python -c 'import os;print(os.environ)'
    env:
      TEST_ENV: 'hello world'
      TEST_SECRET: ${{ secrets.MY_TOKEN }}

However, the output is as follows,

environ({
'TEST_ENV': 'hello world',
'TEST_SECRET':'',
...})

It seems not working due to GitHub's redaction.

Based on @raspiduino 's answer, I did more explore on both options to import env vars.

name: python

on: push

jobs:
  test_env:
    runs-on: ubuntu-latest
    steps:
    - name: Set up Python
      uses: actions/setup-python@v2
      with:
        python-version: 3.8
        
    - name: Test env vars for python
      run: python -c 'import os;print(os.environ)'
      env:
        ENV_SECRET: ${{ secrets.ENV_SECRET }} 
        REPO_SECRET: ${{ secrets.REPO_SECRET }} 
    
    - name: Test inline env vars for python
      run: ENV_SECRET=${{ secrets.ENV_SECRET }} REPO_SECRET=${{ secrets.REPO_SECRET }} python -c 'import os;print(os.environ)'

Basically, both steps are in same outputs. The REPO_SECRET can be passed thru but not the ENV_SECRET.

enter image description here

Outputs enter image description here

3

There are 3 best solutions below

0
On BEST ANSWER

There are three types of secrets within GitHub Actions.

  1. Organization secrets
  2. Repository secrets
  3. Environment secrets

To access Environment secrets, you have to referencing an environment in your job. (Thanks to @riQQ)

Actions secrets

name: python

on: push

jobs:
  test_env:
    environment: TEST_SECRET
    runs-on: ubuntu-latest
    steps:
    - name: Set up Python
      uses: actions/setup-python@v2
      with:
        python-version: 3.8
        
    - name: Test env vars for python
      run: python -c 'import os;print(os.environ)'
      env:
        ENV_SECRET: ${{ secrets.ENV_SECRET }} 
        REPO_SECRET: ${{ secrets.REPO_SECRET }} 
2
On

You try the things below:

  - name: Test env vars for python
    run: TEST_SECRET=${{ secrets.MY_TOKEN }} python -c 'import os;print(os.environ['TEST_SECRET'])

This will pass ${{ secrets.MY_TOKEN }} directly as an environment variable to the python process and not share with other processes. Then you can use os.environ['TEST_SECRET'] to get it.

I have done this here and here

0
On

An other alternative I use is create a .env file with all the secrets, something like this:

      - name: Create .env arquive
        run: |
          echo "MY_TOKEN=${{ secrets.MY_TOKEN }}" >> ./.env