CodeBlanks Logo Icon CodeBlanks

kubectl get -l

Learn to filter by label with the -l flag.

kubectl get -l

-l (--selector) filters objects by label in kubectl commands. A comma means AND; != means not equal, and !key means the key is absent:

kubectl get pods -l app=web
kubectl get pods -l app=web,ortam=prod
kubectl get pods -l 'ortam!=prod'
kubectl get pods -l '!katman'
kubectl get pods -L app,ortam        # show labels as columns

Bulk operations with selectors

Selectors aren't only for listing; they also do bulk operations such as deleting, reading logs, scaling and labelling:

kubectl delete pods -l app=web,ortam=test
kubectl logs -l app=web --tail=5 --prefix   # logs of all replicas
kubectl rollout restart deploy -l takim=odeme

Before a bulk delete, running get with the same selector to see what will be deleted is a good habit.

Practice Operations by label

Write three commands: list the pods labelled app=web and ortam=prod with app and ortam columns; show the last 5 log lines of all pods labelled app=web with prefixes; delete the pods labelled ortam=test.

Starter code

terminal
# buraya yaz

Sample solution

terminal
kubectl get pods -l app=web,ortam=prod -L app,ortam
kubectl logs -l app=web --tail=5 --prefix
kubectl delete pods -l ortam=test

Expected output

NAME                  READY   STATUS    APP   ORTAM
web-7c5b9f6d8-abcde   1/1     Running   web   prod
[pod/web-7c5b9f6d8-abcde/nginx] 10.244.1.1 - - "GET / HTTP/1.1" 200 615
pod "web-test-1" deleted

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which pods does kubectl get pods -l app=web,ortam=prod list?

  • Only those with app=web
  • None
  • Those with both app=web and ortam=prod Correct answer
  • Those with app=web or ortam=prod

Explanation: A comma is AND.

2 Show labels as columns.

Question
kubectl get pods ____ app,ortam
Answer
kubectl get pods -L app,ortam

Explanation: Uppercase L (--label-columns) adds columns.

3 Match.

Term Meaning
-l a=b,c=d AND
-l 'a!=b' Not equal
-l '!a' Key absent
-L a Show as a column

All lessons in Intermediate