Andy
Andy

Reputation: 2946

How to re-label multiple pods in k8s with kubectl label?

Trying to figure out, how to apply new label "app=green" to the pods that are currently marked with "color=green"...

Looks like I could not use "--field-selector" and I do not want to specify name of each pod in "kubectl label" command.

Upvotes: 2

Views: 2127

Answers (2)

Sanket
Sanket

Reputation: 149

To apply a new label to Pods that are currently labeled with "color=green" without specifying the names of each Pod individually, you can use the kubectl command in combination with label selectors. Here's how you can do it:

  1. Use a label selector to identify the Pods with the "color=green" label. You can use the kubectl get pods command with the --selector option to list the Pods that match this label selector:
kubectl get pods --selector=color=green

This command will list all Pods with the "color=green" label.

  1. Once you have identified the Pods, you can use the kubectl label command to add the "app=green" label to them. You can pipe the list of Pods from the previous step to the kubectl label command like this:
kubectl get pods --selector=color=green --no-headers | awk '{print $1}' | xargs -I {} kubectl label pod {} app=green

Here's what this command does:

  • kubectl get pods --selector=color=green --no-headers lists the Pods with the "color=green" label without headers.
  • awk '{print $1}' extracts the Pod names from the list.
  • xargs -I {} kubectl label pod {} app=green applies the "app=green" label to each Pod. This command will apply the new label "app=green" to all Pods that match the label selector "color=green."

Please be cautious when applying labels to Pods, especially in a production environment, to avoid unintended consequences.

Upvotes: 0

Burak Serdar
Burak Serdar

Reputation: 51652

This should work:

kubectl label pods --selector=color=green app=green

Upvotes: 7

Related Questions