Eric J Ma's Website

Sync GitHub secrets with your .env and gh CLI

written by Eric J. Ma on 2024-09-15 | tags: github secrets environment-variables gh-cli automation devops productivity security til


So I learned something new today. We can set GitHub secrets using a .env file and the gh CLI.

This is how it's done.

Suppose you have a .env file with the following content:

export SECRET_KEY=my-secret-key
export DATABASE_URL=my-database-url

You can set these secrets using the following command:

gh secret set -f .env

This will set the SECRET_KEY and DATABASE_URL secrets in your GitHub repository automatically.

The pre-requisite is that you have the gh CLI installed and you have set up your local git config with your GitHub user.

gh auth login

Additionally, your git remote should be set to your GitHub repository.

git remote -v

If it's not set to your GitHub repository, you can set it with the following command:

git remote set-url origin git@github.com:YOUR_USERNAME/YOUR_REPOSITORY.git

(Remember to change YOUR_USERNAME and YOUR_REPOSITORY to the appropriate values!)

Now, instead of doing the tedious work of setting each secret manually using the GitHub web interface, you can use the gh CLI to set them. This streamlines the process and reduces the chance of human error.

gh secret set -f .env

This will set the SECRET_KEY and DATABASE_URL secrets in your GitHub repository automatically.


Cite this blog post:
@article{
    ericmjl-2024-sync-cli,
    author = {Eric J. Ma},
    title = {Sync GitHub secrets with your .env and gh CLI},
    year = {2024},
    month = {09},
    day = {15},
    howpublished = {\url{https://ericmjl.github.io}},
    journal = {Eric J. Ma's Blog},
    url = {https://ericmjl.github.io/blog/2024/9/15/sync-github-secrets-with-your-env-and-gh-cli},
}
  

I send out a newsletter with tips and tools for data scientists. Come check it out at Substack.

If you would like to sponsor the coffee that goes into making my posts, please consider GitHub Sponsors!

Finally, I do free 30-minute GenAI strategy calls for teams that are looking to leverage GenAI for maximum impact. Consider booking a call on Calendly if you're interested!