kubernetes-hands-on/10-secrets/README.md

107 lines
2.4 KiB
Markdown
Raw Normal View History

2019-05-09 19:41:07 +06:00
# Secrets
Objects of type `Secret` are intended to hold sensitive information, such as passwords, OAuth tokens, and ssh keys. Putting this information in a secret is safer and more flexible than putting it verbatim in a pod definition or in a docker image.
```yml
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
username: YWRtaW4= # admin
password: cGFzc3dvcmQ= # password
```
* `data`: is a list of key/values. The values must be in base64.
You can apply the file:
2019-05-21 15:10:59 +06:00
```sh
2019-05-09 19:53:01 +06:00
$ kubectl apply -f 10-secrets/01-secrets.yml
2019-05-09 19:41:07 +06:00
secret "mysecret" created
```
You can reference a secret from a pod, either per env variable or mounting a volume containing a secret.
## Reference the secret by mounting it as a volume
2019-05-09 19:41:07 +06:00
Here we mount the secret `mysecret` to the path `/etc/foo` inside the pod:
2019-05-21 15:09:13 +06:00
```yml
2019-05-09 19:41:07 +06:00
apiVersion: v1
kind: Pod
metadata:
name: redis-with-volume-secrets
spec:
containers:
- name: redis
image: redis
volumeMounts:
- name: foo
mountPath: "/etc/foo"
readOnly: true
volumes:
- name: foo
secret:
secretName: mysecret
```
You can look up the secrets in the pod by connecting to the pod:
```sh
$ kubectl exec -ti redis-with-volume-secrets /bin/bash
root@redis-with-volume-secrets:/data# cd /etc/foo/
root@redis-with-volume-secrets:/etc/foo# ls
password username
```
## Reference the secret by using environment variables
2019-05-09 19:41:07 +06:00
Here we bind the value `username` from the secret `mysecret` to the env variable `SECRET_USERNAME`,
`password` from the secret `mysecret` to the env variable `SECRET_PASSWORD`:
2019-05-21 15:09:13 +06:00
```yml
2019-05-09 19:41:07 +06:00
apiVersion: v1
kind: Pod
metadata:
name: redis-with-env-secrets
spec:
containers:
- name: redis
image: redis
env:
- name: SECRET_USERNAME
valueFrom:
secretKeyRef:
name: mysecret
key: username
- name: SECRET_PASSWORD
valueFrom:
secretKeyRef:
name: mysecret
key: password
```
You can look up the secrets in the pod by connecting to the pod:
```sh
$ kubectl exec -ti redis-with-env-secrets /bin/bash
root@redis-with-env-secrets:/data# echo $SECRET_USERNAME
admin
root@redis-with-env-secrets:/data# echo $SECRET_PASSWORD
1f2d1e2e67df
```
2019-05-09 19:41:07 +06:00
Careful, if you change a secret after starting the pods, it won't update the pods. So you need to restart them.
2019-05-14 19:36:19 +06:00
## Clean up
2019-05-21 15:10:59 +06:00
```sh
2019-05-14 19:36:19 +06:00
kubectl delete service,deployment,pod,secrets --all
```
## Links
* https://kubernetes.io/docs/concepts/configuration/secret/