Skip to content

API keys and environment variables in GitHub Actions

If you're running code that accesses APIs or uses passwords on your own computer, you might use dotenv or something similar to hide them from GitHub when you make your repository.

But what happens when you want to run a GitHub Action workflow that accesses the same variables?

Saving the variables

Open up settings, scroll down until you see Secrets and variables on the left. Open it up and click Actions.

Settings, scroll

Even though API keys seem secret, we want variables. Secrets are never displayed ever again, while variables show up as normal text. I personally like variables because that means we can debug what we were using by looking at it later.

Variables, not secrets

Click new repository variable. Environment variables (in this instance) are when you're sharing things across an organization or need to have multiple setups - maybe you're using a different database URL if you're doing automated testing vs. if you're doing something for real.

New repo var

Type it in!

Type it in

Save it and you're done!

Done

Using the variables

To use the environment variable in your Python script, you just ask for it from os.

import os

API_KEY = os.getenv('MY_API_KEY')

With python-dotenv

If you're using python-dotenv you don't have to change your code at all! When a .env file, dotenv just uses the environment variable you set through GitHub.

import os
from dotenv import load_dotenv
load_dotenv()

API_KEY = os.getenv('MY_API_KEY')