Kubernetes: Apply parts of a manifest by labels

kubernetes kubectl selector apply

2 min read | by Jordi Prats

Sometimes we might have a manifest file with a lot of objects in it but we don't really need them all. We can use it's labels to install just the objects that have a specific label.

Let's assume we have the following manifest:

kind: Service
apiVersion: v1
metadata:
  name: demo1
  labels:
    app: first
spec:
  type: ExternalName
  externalName: demo1.pet2cattle.com
---
kind: Service
apiVersion: v1
metadata:
  name: demo2
  labels:
    app: second
spec:
  type: ExternalName
  externalName: demo2.pet2cattle.com

If we apply it as usual it's going to create both objects:

$ kubectl apply -f test_en.yaml
service/demo1 created
service/demo2 created

But with the -l option we can specify the label that's going to be used to filter the objects. So for example if we set it to app=first it's going to apply just the object that has that label, in the example that would be demo1:

$ kubectl apply -f test_en.yaml -l app=first
service/demo1 created

We can do the same using app=second to install just the other object as well:

$ kubectl apply -f test_en.yaml -l app=second
service/demo2 created

Posted on 15/09/2022