> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Lab Solution Labels and Selectors

> Guide demonstrating Kubernetes labels and selectors to query resources, count objects, and fix a ReplicaSet selector mismatch causing validation errors

In this walkthrough we'll complete practice tasks that demonstrate using Kubernetes labels and selectors to find and count resources and to troubleshoot a ReplicaSet manifest that fails validation.

Labels and selectors are essential when operating clusters: they let you group and query resources (pods, services, ReplicaSets, etc.) using key/value pairs. Note that label keys and values are case-sensitive — you must use the exact key/value pair present on the resources.

<Callout icon="lightbulb" color="#1CB2FE">
  Label selectors are passed to `kubectl` with `--selector` (or `-l`). Combine multiple selectors with commas, for example `--selector env=prod,bu=finance`. You can apply selectors to most `kubectl get` commands (e.g., `pods`, `services`, `replicasets`, or `all`).
</Callout>

***

## Quick reference: common selector commands

| Question | Selector used | Command example | Result |
| -: | - | - | - |
| Count pods in `dev` | `env=dev` | `kubectl get pods --selector env=dev --no-headers \| wc -l` | `7` |
| Count pods in `finance` BU | `bu=finance` | `kubectl get pods --selector bu=finance --no-headers \| wc -l` | `6` |
| Count all objects in `prod` | `env=prod` | `kubectl get all --selector env=prod --no-headers \| wc -l` | `7` |
| Find pod in `prod`, `finance`, `frontend` | `env=prod,bu=finance,tier=frontend` | `kubectl get all --selector env=prod,bu=finance,tier=frontend` | `pod/app-1-zzxdf` |

***

## 1) How many pods exist in the `dev` environment?

Assuming the environment label key is `env` and development is labeled `dev`, use the selector and count the returned lines. The `--no-headers` flag prevents the header row from being counted.

```bash theme={null}
kubectl get pods --selector env=dev --no-headers | wc -l
# 7
```

There are 7 pods with `env=dev`.

***

## 2) How many pods are in the `finance` business unit?

Use the `bu` label with value `finance` and the same counting technique:

```bash theme={null}
kubectl get pods --selector bu=finance --no-headers | wc -l
# 6
```

There are 6 pods labeled `bu=finance`.

***

## 3) How many objects are in the `prod` environment (pods, ReplicaSets, services, etc.)?

To list every resource type in a namespace use `kubectl get all`. Add `--selector` to filter by label and `--no-headers` to make counting straightforward.

```bash theme={null}
kubectl get all --selector env=prod --no-headers
pod/db-2-prm79                  1/1 Running 0 3m13s
pod/auth                        1/1 Running 0 3m13s
pod/app-2-z5fgv                 1/1 Running 0 3m13s
pod/app-1-zzxdf                 1/1 Running 0 3m13s
service/app-1                   ClusterIP 10.43.108.231 <none> 3306/TCP 3m12s
replicaset.apps/db-2            1 1 1 3m13s
replicaset.apps/app-2           1 1 1 3m13s
```

Count the lines to get the total number of objects:

```bash theme={null}
kubectl get all --selector env=prod --no-headers | wc -l
# 7
```

There are 7 objects matching `env=prod`.

***

## 4) Identify the pod that is in `prod`, BU `finance`, and `frontend` tier

Combine the three selectors (comma-separated) so the command returns only objects matching all three labels:

```bash theme={null}
kubectl get all --selector env=prod,bu=finance,tier=frontend
NAME               READY STATUS RESTARTS AGE
pod/app-1-zzxdf    1/1   Running 0        4m7s
```

The pod `app-1-zzxdf` matches `env=prod`, `bu=finance`, and `tier=frontend`.

***

## 5) Fixing a ReplicaSet definition: selector does not match template labels

Kubernetes controllers (like ReplicaSet) require `spec.selector.matchLabels` to match the labels on the pod template (`spec.template.metadata.labels`). If they differ, the API server will reject the manifest with a validation error because the controller cannot determine which Pods it should manage.

Problematic manifest (selector and template labels do not match):

```yaml theme={null}
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: replicaset-1
spec:
  replicas: 2
  selector:
    matchLabels:
      tier: front-end
  template:
    metadata:
      labels:
        tier: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
```

If you attempt to create this ReplicaSet you'll see an admission/validation error:

```bash theme={null}
kubectl create -f replicaset-definition-1.yaml
# The ReplicaSet "replicaset-1" is invalid: spec.template.metadata.labels: Invalid value: map[string]string{"tier":"nginx"}: `selector` does not match template `labels`
```

Explanation: The `selector.matchLabels` is `tier: front-end` while the pod template labels are `tier: nginx`. They must be identical (or the selector must be a subset of the template labels).

Corrected manifest — make `selector.matchLabels` and `template.metadata.labels` identical (here we choose `tier: nginx`):

```yaml theme={null}
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: replicaset-1
spec:
  replicas: 2
  selector:
    matchLabels:
      tier: nginx
  template:
    metadata:
      labels:
        tier: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
```

Create the corrected ReplicaSet:

```bash theme={null}
kubectl create -f replicaset-definition-1.yaml
# replicaset.apps/replicaset-1 created
```

Verify the ReplicaSet and its pods:

```bash theme={null}
kubectl get rs
# NAME            DESIRED  CURRENT  READY  AGE
kubectl get pods --selector tier=nginx
# pod/nginx-xxxxx 1/1 Running 0 ...
# pod/nginx-yyyyy 1/1 Running 0 ...
```

The ReplicaSet is now valid and manages the pods as expected.

<Callout icon="lightbulb" color="#1CB2FE">
  Pro tip: Always ensure `spec.selector.matchLabels` is a subset of (or exactly equals) `spec.template.metadata.labels`. The pod template must include the selector labels so the controller can identify and adopt the pods. A mismatch results in a validation error and prevents creation.
</Callout>

***

## Additional resources

* Kubernetes labels and selectors: [https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/)
* ReplicaSet concept and fields: [https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/](https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/)
* kubectl reference: [https://kubernetes.io/docs/reference/kubectl/overview/](https://kubernetes.io/docs/reference/kubectl/overview/)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/cka-certification-course-certified-kubernetes-administrator/module/cd124bdf-9911-4cc1-8177-f2d8b6dfd2a0/lesson/973feb09-9555-4376-9c4b-01b913fc3388" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.