bakadevops
bakadevops

Reputation: 149

How to replace JSON value in kubectl output using go-template?

I have a configMap and I want to create a backup configMap by using the last applied configuration from that.

I use the following command to get the last applied configuration:

    kubectl get cm app-map -n app-space \
    -o go-template \
    --template='{{index .metadata "annotations" "kubectl.kubernetes.io/last-applied-configuration"}}' > backup.json

It returns something like this [the content of backup.json]:

{"kind":"ConfigMap","apiVersion":"v1","metadata":{"name":"app-map","creationTimestamp":null},"data":{"app.yml":"xxxxxxxxx","config.yml":"yyyyyyyyy"}}

Now, I want my backup configMap to have a different name. So, I want to change the .metadata.name from app-map to app-map-backup.

Is there a way I can achieve that with kubectl and -o go-template? I want to have the name changed before I write it to the backup.json file.

I know I can do that using jq but I do not have permission to install jq on the server where I am using kubectl.

Upvotes: 2

Views: 1148

Answers (2)

Emre Odabaş
Emre Odabaş

Reputation: 499

you could use kubectl bulk plugin. The below command will replicate your config map

# get resource(s) and create with field(name) change 
kubectl bulk configmap app-map -n app-space create name app-mapp-backup

Kubectl bulk is very powerful to use, I suggest to check samples.

Upvotes: 2

Matt
Matt

Reputation: 8152

You cannot do this just using kubectl. But there are other ways.

You can download statically linked jq binary from official jq website:

wget https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
chmod +x jq-linux64

and then you can use this binary like following:

kubectl -o go-template [...] | ./jq-linux64 ...

or you can use sed:

kubectl -o go-template [...] | sed 's/"name":"app-map"/"name":"app-map-backup"/'

Upvotes: 1

Related Questions