ReplicaSet fails with invalid: spec.template.metadata.labels

2/12/2020

I am trying to do some research on replicaSet for my learning purpose. I was able to create a replicaSet successfully with matchLabels. To test the matchExpression selector, I created a pod first then a new replica set to test if the replica set will be able to check the labels from the running pods. But this failed with error. Here is what I did so far.

  1. Created a pod first with a specific label. Pod runs successfully.
  2. Create a replicaSet with matchExpressions matching the value with the label specified in the pod.

After the second step I get error. Below are the YAML files and the error. Can you help me understand the issue here ?

Here is the pod-definition.yaml

apiVersion: v1
kind: Pod
metadata:
  name: nginx-app
  labels:
    tier: frontend1

spec:
  containers:
  - name: nginx-c
    image: nginx

Here is the replicaset-definition.yaml

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: replicaset-2
spec:
  replicas: 2
  selector:
    matchExpressions:
      - {key: tier, operator: In, values: [frontend1]}
  template:
    metadata:
      labels:
        tier: nginx
    spec:
      containers:
      - name: nginx
        image: nginx

Error while creating replica set:

master $ kubectl create -f /root/replicaset-definition.yaml

The ReplicaSet "replicaset-2" is invalid: spec.template.metadata.labels: Invalid value: map[string]string{"tier":"nginx"}: selector does not match template labels

-- srinu259
kubernetes

2 Answers

2/13/2020

To make pod fall into newly created ReplicaSet's scope using matchExpressions you have to either use the same labels in RS as defined in already created pod or you have to add additional label in the expression so it looks like following:

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: replicaset-2
spec:
  replicas: 2
  selector:
    matchExpressions:
    - key: tier
      operator: In
      values:
      - frontend1
      - nginx
  template:
    metadata:
      labels:
        tier: nginx
    spec:
      containers:
      - name: nginx
        image: nginx

This way RS will recognize already existing pod as its own and create only one more pod to meet the requirements defined in replicas field.

-- KFC_
Source: StackOverflow

2/12/2020

Can you try with the following by changing the label in template section.

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: replicaset-2
spec:
  replicas: 2
  selector:
    matchExpressions:
      - {key: tier, operator: In, values: [frontend1]}
  template:
    metadata:
      labels:
        tier: frontend1
    spec:
      containers:
      - name: nginx
        image: nginx
-- Dinesh
Source: StackOverflow