If I run the command using echo, it seems to be a valid JSON
In fact, it does not. Look carefully at the first character of the output:
'{"data": {"FOOBAR": "value that I want"}}'
Your "JSON" string starts with a single quote, which is an invalid character. To get valid JSON, you would need to rewrite your command to look like this:
echo "{\"data\": {\"FOOBAR\": \"$FOOBAR\"}}"
And we can confirm that's valid JSON using something like the jq
command:
$ echo "{\"data\": {\"FOOBAR\": \"$FOOBAR\"}}" | jq .
{
"data": {
"FOOBAR": "value that i want"
}
}
Making your patch command look like:
kubectl patch secret operator-secrets \
--namespace kube-system \
--context=cluster1 \
--patch "{\"data\": {\"FOOBAR\": \"$FOOBAR\"}}"
But while that patch is now valid JSON, it's still going to fail with
a new error:
The request is invalid: patch: Invalid value: "map[data:map[FOOBAR:value that i want]]": error decoding from json: illegal base64 data at input byte 5
The value of items in the data map must be base64 encoded values.
You can either base64 encode the value yourself:
kubectl patch secret operator-secrets \
--namespace kube-system \
--context=cluster1 \
--patch "{\"data\": {\"FOOBAR\": \"$(base64 <<<"$FOOBAR")\"}}"
Or use stringData instead:
kubectl patch secret operator-secrets \
--namespace kube-system \
--context=cluster1 \
--patch "{\"stringData\": {\"FOOBAR\": \"$FOOBAR\"}}"