A common reason to use a Kubernetes Secrets is to add a SSL/TLS certificate to a cluster secure traffic through Ingress Controllers. Kubernetes provides two ways to add a secret:
- Directly using the
kubctl
command line, and - From a YAML source file
- Create a quick self-signed cert for
www.example.com
, valid for one year. This command produces two files:www.example.com.key
andwww.example.com.cert
. In production, you would a more secure key and use it to obtain a certificate from a certificate authority.
openssl req -x509 -nodes \
-days 365 \
-newkey rsa:2048 \
-keyout www.example.com.key \
-out www.example.com.crt \
-subj "/CN=www.example.com"
- Create a TLS secret in Kubernetes with the
kubectl
command:
kubectl create secret tls test-tls --key="www.example.com.key" --cert="www.example.com.crt"
- Verify that it was added:
kubectl get secrets
- To view the YAML source of the secret:
kubectl get secret test-tls -o yaml
- Optional: To delete the secret, run:
kubectl delete secrets test-tls
Create a YAML source file manually to create the secret. Ths provides better documentation and reproduction it is prefered to create files that specify the state of the system, which can be committed to a source repo (i.e. git
).
- The basic template of the YAML file is:
apiVersion: v1
data:
tls.crt:
tls.key:
kind: Secret
metadata:
name: test-tls
namespace: default
type: kubernetes.io/tls
- We need to base64 encode the key and certificate data (to Copy and paste into file)
cat www.example.com.crt | base64
cat www.example.com.key | base64
- Paste the base64 encoded cert and key into the appropriate sections of the YAML file as one line. Important: Make sure your text editor doesn’t add any carriage returns to wrap the lines.
apiVersion: v1
data:
tls.crt: LS0tLS1CRUdJTiBDRVJUSUZKKJQ0F...etc
tls.key: LS0tLS1CRUdJTiBdJTiBSU0EgUFJJ...etc
kind: Secret
metadata:
name: test-tls
namespace: default
type: kubernetes.io/tls
- Finally, use the YAML file to create the secret:
# Specify namespace with `-n` if required
kubectl create -f tls.yaml