kuberneteskubernetes-secrets

Add contents of a file to an existing Kubernetes secret


I have an existing generic Kubernetes secret that exported as YAML (using kubectl get secret -o yaml > secret.yaml), looks like this:

kind: Secret
apiVersion: v1
type: Opaque
metadata:
  name: some-secret-key-files
data:
  host1.example.com.key: c2VjcmV0IG51bWJlciBvbmUK
  host2.example.com.key: c2VjcmV0IG51bWJlciB0d28K

Now I have a new key file named host3.example.com.key, with these contents:

secret number three

What is easiest way to add the contents of this file base64-encoded to secret.yaml, so that in the end it looks like this:

kind: Secret
apiVersion: v1
type: Opaque
metadata:
  name: some-secret-key-files
data:
  host1.example.com.key: c2VjcmV0IG51bWJlciBvbmUK
  host2.example.com.key: c2VjcmV0IG51bWJlciB0d28K
  host3.example.com.key: c2VjcmV0IG51bWJlciB0aHJlZQo=

Solution

  • In the end, exporting the secret to a YAML file was not needed at all. With kubectl patch secret this can be done 'online' like this:

    kubectl patch secret some-secret-key-files --patch="{\"data\": {\"host3.example.com.key\": \"$(base64 -w0 host3.example.com.key)\"}}"
    

    This will add a new file entry to the existing secret some-secret-key-files, and use base64(1) to base64 encode the contents of the local host3.example.com.key file.