Kubernetes: creating TLS secrets with kustomize using embedded or external content

There are multiple options for creating a TLS secret using kustomize.  One is to embed the certificate content as a base64 string directly in the data, the other is to use an external file.

Below is an example kustomization.yaml file that serves as an entry point for both methods.

---
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  # load secret from embedded content
  - my-tls-secret-embedded.yaml 

generators:
  # load secret from file
  - my-tls-secret-extfile.yaml

The my-tls-secret-embedded.yaml contains the embedded content of my-tls.crt and my-tls.key directly in the file itself.  I replaced the base64 content with ellipsis to keep the output simple.

---
apiVersion: v1
kind: Secret
type: kubernetes.io/tls
metadata:
  name: my-tls-secret-embedded
data:
  # cat my-tls.crt | base64 -w0
  tls.crt: ...
  # cat my-tls.key | base64 -w0
  tls.key: ...

The my-tls-secret-extfile.yaml only contains the filenames of the certificate and key, and allows kustomize to resolve the content.

---
apiVersion: builtin
kind: SecretGenerator
metadata:
  name: my-tls-secret-extfile
behavior: create
files:
  - tls.crt=my-tls.crt
  - tls.key=my-tls.key
type: kubernetes.io/tls
options:
  disableNameSuffixHash: true

Testing

You can test the kustomize output and apply to a cluster using the commands below.

# test output from kustomize, does not apply to cluster
kustomize build .

# apply to cluster
kubectl apply -k .

 

Here is a github link to all the files referenced in this article.

 

REFERENCES

kubernetes.io, using kustomize

github project code for this kustomize example

shocksolution.com, creating Kubernetes secrets using tls

NOTES

How the certificate and key were generated for this article

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout my-tls.key -out my-tls.crt -subj "/CN=my-tls.com"