pythonenvironment-variablesgithub-actionsgithub-secret

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


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


Solution

  • 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 }}