Env Variables in K8s — Part 2: Secrets

note: This article describes how to deploy GitHub secrets in Azure Kubernetes clusters using GitHub actions. It should be more or less applicable regardless of which code repository and CI/CD platform you use.

In part 1, I described the issues of managing environmental variables between software developers and traditional operations groups. You can read it here:

In this article, I am going to talk about secrets, specifically creating K8s secrets from GitHub secrets. Credentials like database credentials and api keys should not be stored in the repo itself, but rather in a Github secret. You can read about GitHub secrets here: https://docs.github.com/en/actions/reference/encrypted-secrets

Once you create a secret, you can’t see what the value of the secret is, you can only replace it with a new value. Thus it is a good idea to store those secrets in a password manager as well. This also makes it easy to share them when needed with other members of your team.

Once you create a secret at either the repo or organization level in GitHub, you need to be able to create a K8s secret from your GitHub secret so that the app will have the secret, such as a DB connection string, exposed to it’s pods in K8s as an env variable. To do so, we use the Azure/k8s-create-secret@v1 action.

For example, if your app has a DB connection string stored as a GitHub secret and the secret is named “DB_CONNECTION_STRING”, to create a K8s secret from that GitHub secret in the staging namespace, you would use the following code as a step in your staging deployment GitHub workflow:

- name: Add GitHub secrets to k8s        
uses: Azure/k8s-create-secret@v1
namespace: 'staging'
secret-type: 'generic'
arguments: --from-literal=DB_CONNECTION_STRING=${{ secrets.DB_CONNECTION_STRING }}
secret-name: myapp-config-secret

In the above example, we are creating a secret named: myapp-config-secret in the staging namespace in K8s.

To verify the secret was created, just issue the following kubectl command:

kubectl get secrets -n staging

You can create more than one value in your secret by just adding more --from-literal=arguments.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store