13

I created a secret like this:

kubectl create secret generic test --from-literal=username=testuser --from-literal=password=12345

I want to update the username to testuser2 but I want to do it only with kubectl patch --type='json'.

This is how I tried to do it:

kubectl patch secret test --type='json' -p='[{"data":{"username": "testuser 2"}}]' -v=1  

But I received:

The "" is invalid

Remember, I want to do it with the option of --type='json', no other workarounds.

E235
  • 11,560
  • 24
  • 91
  • 141
  • the data object should not be inside square brackets, so instead of using '[{"data": ... }]' you can use '{ "data": ... } ' – Maoz Zadok Jun 16 '22 at 13:51

3 Answers3

19

I found how to do it after I read here that referred me to this great article.
This is the JSON secret:

{
    "apiVersion": "v1",
    "data": {
        "password": "aWx1dnRlc3Rz",
        "username": "dGVzdHVzZXI="
    },
    "kind": "Secret",
    "metadata": {
        "creationTimestamp": "2019-04-18T11:37:09Z",
        "name": "test",
        "namespace": "default",
        "resourceVersion": "3017",
        "selfLink": "/api/v1/namespaces/default/secrets/test",
        "uid": "4d0a763e-61ce-11e9-92b6-0242ac110015"
    },
    "type": "Opaque"
}

Therefore, to update the user's field I needed to create the JSON Patch format:

[
    {
        "op" : "replace" ,
        "path" : "/data/username" ,
        "value" : "dGVzdHVzZXIy" # testuser2 in base64
    }
]

Notice that the value should be in base64.

The result is:

kubectl patch secret test --type='json' -p='[{"op" : "replace" ,"path" : "/data/username" ,"value" : "dGVzdHVzZXIy"}]'
E235
  • 11,560
  • 24
  • 91
  • 141
  • 1
    Thank you it works. Note: if you PATCH secret with direct http request, Content-Type: application/json-patch+json have to be set. – Sergey M. Dec 16 '19 at 11:32
3

This is what I do in order to replace the secret:

kubectl patch secret my-secret  --patch="{\"data\": { \"password\": \"$(echo -n mypassword |base64 -w0)\" }}"

You can either use stringData as a clear text, as follow

kubectl patch secret my-secret  --patch='{"stringData": { "password": "mypassword" }}'

Maoz Zadok
  • 4,871
  • 3
  • 33
  • 43
0

This command solved my issue on version 1.24.x:

kubectl patch secret app-sec  --patch="{\"data\": { \"license-id\": \"TEST\" }}" -oyaml
Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
Omar
  • 11
  • 4