Home > Software design >  How to access GitHub action secrets with python?
How to access GitHub action secrets with python?

Time:08-13

I have environment secrets set up in a Python GitHub actions project:

enter image description here

I can access the secrets from the actions file, because the following:

jobs:
  log-the-inputs:
    runs-on: ubuntu-latest
    steps:
      - run: |
          echo "Log level: $LEVEL"
          echo "Tags: $TAGS"
          echo "Environment: $ENVIRONMENT"
          echo ${{ secrets.EMAIL_USER }}

will output

Run echo "Log level: $LEVEL"
Log level: warning
Tags: false
Environment: novi
***

I expected the secrets to be available from the environment variables, but when I use os.environ EMAIL_USER and EMAIL_PASSWORD are not in there.

How to access the secrets from the python script?

CodePudding user response:

When you use an expression like ${{ secrets.EMAIL_USER }}, you're not referencing an environment variable. That value is substituted by the workflow engine before your script runs.

If you want the secrets to be available as environment variables, you need to set those environment variables explicitly using the env section of a step or workflow. For example:

name: Workflow with secrets

on:
  workflow_dispatch:

jobs:
  show-secrets:
    runs-on: ubuntu-latest
    env:
      EMAIL_USER: ${{ secrets.EMAIL_USER }}
      EMAIL_PASSWORD: ${{ secrets.EMAIL_PASSWORD }}
    steps:
      - name: Setup Python
        uses: actions/setup-python@v2
        with:
          python-version: '^3.9'

      - name: Show environment
        run: |
          env | grep EMAIL

      - name: Create python script
        run: |
          cat > showenv.py <<'EOF'
          import os

          print(f'Email username is {os.environ.get("EMAIL_USER", "<unknown")}')
          print(f'Email password is {os.environ.get("EMAIL_PASSWORD", "<unknown")}')
          EOF

      - name: Run python script
        run: |
          python showenv.py
  • Related