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.
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.
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.
Type it in!
Save it and you're done!
Using the variables¶
To use the environment variable in your Python script, you just ask for it from os
.
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.