Manage kubernetes Secrets with python

ahmed.mahmoud
2 min readSep 24, 2020

--

kubernetes secrets is a great place to inject your environment variables in.From the name many people think it’s the right place to inject services secrets like tokens and passwords. This approach is not really secured. The best way to inject your high sensitive data is from somewhere outside your cluster, but we will come to this point later.

This article is about managing your low sensitivity variables from inside the cluster.

kubernetes provides and amazing cli and python-sdk for such matter. so let’s get started. we will create a microservice that creates a jwt token for user authentication. I will not go into detail on the logic of the jwt service itself wen will just discuss how to manage our database variables to connect safely with database without any exposer of the connection variables to the outside world.

By default database connection needs 4 variables:
- HOST (low sensitivity)
- DATABASE (low sensitivity)
- USER (low sensitivity)
- PASSWORD (high sensitivity)

I will inject host, database and user into the cluster and the password will be injected from Github secrets or Gitlab secrets.

kubectl create secret generic database-vars --from-literal=host="$VALUE" --from-literal=database="$VALUE" --from-literal=user="$VALUE"

See you variables after injection with:

kubectl get secret database-vars -o yaml## ResultapiVersion: v1
data:
database: ""
host: ""
user: ""
kind: Secret
metadata:
creationTimestamp: "2020-09-24T15:14:51Z"
name: database-vars
namespace: default
resourceVersion: "5261615"
selfLink: /api/v1/namespaces/default/secrets/database-vars
uid: 5b83d99d-19b3-4129-8e3e-024f1113abb0
type: Opaque

Now, let’s get these variables in our code so we can have a good CI/CD and higher security.

Let’s get the decoded variables from k8s. first make sure to know in which namespace are your variables injected and install K8s python-sdk

pip install kubernetes

For the password:
Pass the password as a docker ARG from Github or Gitlab secrets registry to your code for high security.

--

--

ahmed.mahmoud
0 Followers

DevOps | SRE | Kubernetes | Multi-Cloud | Pipeline