Managing Secrets using kubectl

    You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:

    Create a Secret

    A can contain user credentials required by pods to access a database. For example, a database connection string consists of a username and password. You can store the username in a file ./username.txt and the password in a file ./password.txt on your local machine.

    In these commands, the -n flag ensures that the generated files do not have an extra newline character at the end of the text. This is important because when kubectl reads a file and encodes the content into a base64 string, the extra newline character gets encoded too.

    The kubectl create secret command packages these files into a Secret and creates the object on the API server.

    1. --from-file=./username.txt \
    2. --from-file=./password.txt

    The output is similar to:

    1. secret/db-user-pass created
    1. kubectl create secret generic db-user-pass \
    2. --from-file=password=./password.txt

    You do not need to escape special characters in password strings that you include in a file.

    You can also provide Secret data using the --from-literal=<key>=<value> tag. This tag can be specified more than once to provide multiple key-value pairs. Note that special characters such as $, \, *, =, and ! will be interpreted by your shell) and require escaping.

    In most shells, the easiest way to escape the password is to surround it with single quotes ('). For example, if your password is S!B\*d$zDsb=, run the following command:

    Check that the Secret was created:

    1. kubectl get secrets

    The output is similar to:

    1. NAME TYPE DATA AGE
    1. kubectl describe secrets/db-user-pass

    The output is similar to:

    The commands kubectl get and kubectl describe avoid showing the contents of a Secret by default. This is to protect the Secret from being exposed accidentally, or from being stored in a terminal log.

    Decoding the Secret

    To view the contents of the Secret you created, run the following command:

    1. kubectl get secret db-user-pass -o jsonpath='{.data}'

    The output is similar to:

    1. {"password":"MWYyZDFlMmU2N2Rm","username":"YWRtaW4="}

    Now you can decode the password data:

    1. echo 'MWYyZDFlMmU2N2Rm' | base64 --decode

    Delete the Secret you created:

    1. kubectl delete secret db-user-pass

    What’s next