Accessing GitHub secrets in Python

How to securely push your passwords to GitHub

Dipam Vasani
DataDrivenInvestor

--

Reason for writing this article

This is not a full tutorial article like the ones I usually write. Maybe it should just be a top-rated answer on Stackoverflow.

Anyway, I was creating a Python package using nbdev and I needed to use an api_key and a secret_key to access some data. Locally, I just embedded them in a Python file config.py , added the config file to my .gitignore so I don’t accidentally push it to GitHub and started using my credentials.

However, I realized that I will have to somehow push them to GitHub at some point because GitHub actions will need access to them to run all my tests.

There are many ways you can do this but I found Github Secrets to be the easiest. You can use it to store tokens, account details, passwords, anything you would want to encrypt.

To add a new secret, go to your GitHub repository > Settings > Secrets > New Repository Secret.

I am adding secrets for this repository only, but you can also share them across repositories in your organization.

Once added, you can then map them as environment variables in your GitHub actions workflow.

Finally, you can use them in Python as follows:

That’s it. Now you can securely store all your secrets on GitHub and use them in your code.

~happy learning

--

--