PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

[FIXED] How to access GitHub action secrets with python?

 August 18, 2022     environment-variables, github-actions, python     No comments   

Issue

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?


Solution

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


Answered By - larsks
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing