Just a summary about how to create k8s secret object, which is used to store a piece of sensitive information.
String data and Base64 encoding
An secret is saved as base64 encoded string, to generate a based64 string from your password in bash
1 | $ echo -n "mypassword123" | base64 -w0 |
To decode a base64 string
1 | $ echo 'MWYyZDFlMmU2N2Rm' | base64 --decode |
Note: The serialized JSON and YAML values of Secret data are encoded as base64 strings. Newlines are not valid within these strings and must be omitted. When using the base64 utility on Darwin/macOS, users should avoid using the -b option to split long lines. Conversely, Linux users should add the option -w 0 to base64 commands or the pipeline base64 | tr -d ‘\n’ if the -w option is not available.
3 ways to manage secrets
There are 3 ways to use kubectl cli, the 3 corresponding ways to create secrets are as following.
3.1 Imperative commands to edit
3.1.1 Create from file
- Generate base64 string to file
1
2$ echo -n 'admin' > ./username.txt
$ echo -n '1f2d1e2e67df' > ./password.txt - Create secrets from file, the key of the secrets will be the filenamesTo specify another names
1
2
3$ kubectl create secret generic db-user-pass \
--from-file=./username.txt \
--from-file=./password.txt1
2
3$ kubectl create secret generic db-user-pass \
--from-file=username=./username.txt \
--from-file=password=./password.txt
3.1.2 Create from literal
Literal escape with single quote (‘)
1 | kubectl create secret generic dev-db-secret \ |
Note: To edit secret, command to use: kubectl edit secrets dev-db-secret
3.2 Imperative object files
3.2.1 Using here doc
1 | cat <<EOF | kubectl apply -f - |
3.2.2 yaml File
which is the same as the following 2 commands and a yaml file
1 | $echo -n 'admin' | base64 |
3.2.3 string data
The above is the same as following string data example, the string data will be encoded when k8s creates secret
1 | apiVersion: v1 |
Note: you can specify both data and stringdata in the same secret, the stringData will be used. I found this is useful if I want to encode a few lines of information
1 | apiVersion: v1 |
The values from stringData will be used.
3.3 Using kustomization.yml file, Declarative object configuration
To use kustomization feature, we need to create a folder first and add our file there
1 | $ mkdir myconfigs |
3.3.1 Generate from file
- Create base64 stirng
1
2$ echo -n 'admin' > ./username.txt
$ echo -n '1f2d1e2e67df' > ./password.txt - Add following generator to kustomization.yaml file
1
2
3
4
5secretGenerator:
- name: db-user-pass
files:
- username.txt
- password.txt
3.3.2 Generate from literal
1 | secretGenerator: |
The next post will be the 3 practical ways to use k8s secret
References:
https://kubernetes.io/docs/concepts/configuration/secret/
https://kubernetes.io/docs/tasks/configmap-secret/managing-secret-using-kustomize/