A question commonly asked on StackOverflow and the Kubernetes Slack is how to update a Secret or whether it is possible to use kubectl apply on a ConfigMap. The answer may be simpler than you thought.

If you have created a Kubernetes Secret or ConfigMap with kubectl create secret|configmap, you may have expected there to be a similar Secret/ConfigMap helper command under kubectl apply. If so, you would have been wrong. Fortunately, there is a workaround. The trick is to use the dry-run feature of kubectl and then pipe the output of that to kubectl apply. Using this trick to create and/or update a Secret looks like this:

$ kubectl create secret generic my-secret --from-literal=foo=bar --dry-run -o yaml \
    | kubectl apply -f -
If you are running kubectl version 1.18.0 or newer, replace --dry-run with --dry-run=client. Starting in version 1.18, both client- and service-side dry runs are supported.

Similarly, to update a ConfigMap:

$ kubectl create configmap my-config --from-literal=foo=bar --dry-run -o yaml \
    | kubectl apply -f -

It is best to create your Secrets and ConfigMaps using the above approach so kubectl can record its annotation for tracking changes to the resource in the spec. You can also achieve this using the --save-config command-line option when running kubectl create secret|configmap.

When updating Secrets and ConfigMaps, note that since kubectl apply keeps track of deletions, you will need to specify all key/value pairs you want in the Secret or ConfigMap each time you run the command.

Atomist is an event-based automation platform that makes it simple to automate the complex software tasks that previously required a ton of work. We offer a community approach to automation through our curated catalog of Skills. Quickly discover and apply solutions to common needs around development tools, DevEx, DevOps, and other software tasks. View the catalog >>