I am using kubernetes and its resources like secrets. During deployment one secret has been created (say test-secret) with some values inside it. Now I need to renamed this secretes (dev-secret) within the same namespace. How can I rename the secret or how can I copy test-secret value to dev-secret.
Please let me know the correct approach for this.
I needed to do something similar: rename K8s secrets. <br>I searched everywhere, but could not find a good way to do it. <br>So I wrote a bash script for copying secrets into new secrets with a new name. <br>In my case, I also wanted to do this in batch, as I had many secrets with the same prefix that I needed to change. <br>I don't work with bash all the time, so there might be better ways... but it did the trick for me. <br>I hope it helps!
#!/bin/bash
# Copies K8s secrets with names containing the NAME_PART into new
# secrets where the NAME_PART was replaced with NEW_NAME_PART.
# i.e. if NAME_PART is "test-abc" and NEW_NAME_PART is "test-xyz", a secret names test-abc-123
# will be copied into a new secret named test-xyz-123
#
# Pre-requisites:
# - have kubectl installed and pointing to the cluster you want to alter
#
# NOTE: tested with kubectl v1.18.0 and K8s v1.21.5-eks-bc4871b
# configure the NAME_PARTs here
NAME_PART=test-abc
NEW_NAME_PART=test-xyz
WORK_DIR=work_secret_copy
mkdir -p $WORK_DIR
echo "Getting secrets from K8s..."
allSecrets=`kubectl get secrets | tail -n +2 | cut -d " " -f1`
matchingSecrets=`echo $allSecrets | tr ' ' '\n' | grep $NAME_PART`
#printf "All secrets:\n $allSecrets \n"
#printf "Secrets:\n $secrets \n"
for secret in $matchingSecrets; do
newSecret=${secret/$NAME_PART/$NEW_NAME_PART}
echo "Copying secret $secret to $newSecret"
# skip this secret if one with the new name already exists
if [[ $(echo $allSecrets | tr ' ' '\n' | grep -e "^$newSecret\quot;) ]]; then
echo "Secret $newSecret already exists, skipping..."
continue
fi
kubectl get secret $secret -o yaml \
| grep -v uid: \
| grep -v time: \
| grep -v creationTimestamp: \
| sed "s/$secret/$newSecret/g" \
> $WORK_DIR/$newSecret.yml
kubectl apply -f $WORK_DIR/$newSecret.yml
done
There is no specific way to do this. The Kubernetes API does not have "rename" as an operation. In this particular case you would kubectl get server test-secret -o yaml
, clean up the metadata:
sections that don't apply anymore, edit the name, and kubectl apply
it again.
Extending @coderanger answer: If you still have secret config yaml file you can do
kubectl delete -f </path/to/secret-config-yaml>
change metadata.name
object and issue
kubectl apply -f </path/to/secret-config-yaml>