Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
k8s: Updating a Secret

Hopefully helped another k8s newbie with the following. The question was, how do you update a single key in a secret in k8s? I don't know anything about secrets but I will probably want to know this in the future, so here we go.

First, to create a dummy secret:

apiVersion: v1
kind: Secret
metadata:
  name: test-secret
data:
  foo: YmFy
  ding: ZG9uZw==
  wing: d2FuZw==
type: Clear

The type value above is probably invalid. I tried creating the secret with cleartext values but this didn't work; the parser complained that the values are not base64-encoded. There may be a way around this but then it wouldn't really be secrets, it would be a configmap.

I created this using kubectl apply -f secrets.yml. I can then verify:

$ kubectl get secret test-secret -o yaml
apiVersion: v1
data:
  ding: ZG9uZw==
  foo: YmFy
  wing: d2FuZw==
kind: Secret
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","data":{"ding":"ZG9uZw==","foo":"YmFy","wing":"d2FuZw=="},"kind":"Secret","metadata":{"annotations":{},"name":"test-secret","namespace":"default"},"type":"Clear"}
  creationTimestamp: 2018-02-16T17:56:50Z
  name: test-secret
  namespace: default
  resourceVersion: "306952"
  selfLink: /api/v1/namespaces/default/secrets/test-secret
  uid: c39e5c65-1342-11e8-87db-fa163e320b73
type: Clear

So here's the patching:

$ kubectl patch secret test-secret -p='{"data":{"wing": "d29uZw=="}}' -v=1
secret "test-secret" patched

And now to verify:

$ kubectl get secret test-secret -o yaml
apiVersion: v1
data:
  ding: ZG9uZw==
  foo: YmFy
  wing: d29uZw==
kind: Secret
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","data":{"ding":"ZG9uZw==","foo":"YmFy","wing":"d2FuZw=="},"kind":"Secret","metadata":{"annotations":{},"name":"test-secret","namespace":"default"},"type":"Clear"}
  creationTimestamp: 2018-02-16T17:56:50Z
  name: test-secret
  namespace: default
  resourceVersion: "307409"
  selfLink: /api/v1/namespaces/default/secrets/test-secret
  uid: c39e5c65-1342-11e8-87db-fa163e320b73
type: Clear
@chudyandrej
Copy link

chudyandrej commented Oct 2, 2020

This command worked for me:

kubectl patch secret  test-secret -p="{\"data\":{\"foo\": \"`echo -n 'value' | base64`\"}}"

@XDanny322
Copy link

Yes, you helped another someone =)

@magf
Copy link

magf commented Nov 16, 2022

Which implies that we don't need base64 for a quick update:

kubectl patch secret test-secret -p='{"stringData":{"wing": "wing-value"}}' -v=1

best solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment