Kubernetes - Why does selector field fail to validate for Deployment?

Selector directives in Deployments require you to use a sub-field of either matchLabels or matchExpressions, so in my case I need to make use of matchLabels:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: redis
spec:
  replicas: 3
  selector:
    matchLabels:
      name: redis
  template:
    metadata:
      labels:
        name: redis
    spec:
      containers:
      - name: redis
        image: kubernetes/redis:v1
        ports:
        - containerPort: 6379
        resources:
          limits:
            cpu: "0.1"
        volumeMounts:
        - mountPath: /redis-master-data
          name: data
      volumes:
        - name: data
          emptyDir: {}

The selector field of a v1beta1.DeploymentSpec object is of type v1beta1.LabelSelector rather than just a plain map. So, you can either add the label under the matchLabels field of the selector:

redis-with-matchLabels.yaml

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: redis
spec:
  replicas: 3
  selector:
    matchLabels:
      name: redis
  template:
    metadata:
      labels:
        name: redis
    spec:
      containers:
      - name: redis
        image: kubernetes/redis:v1
        ports:
        - containerPort: 6379
        resources:
          limits:
            cpu: "0.1"
        volumeMounts:
        - mountPath: /redis-master-data
          name: data
      volumes:
        - name: data
          emptyDir: {}

Or leave the LabelSelector out of the DeploymentSpec, in which case it will match the labels from the PodSpec:

redis-podSpec-labels.yaml

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: redis
  template:
    metadata:
      labels:
        name: redis
    spec:
      containers:
      - name: redis
        image: kubernetes/redis:v1
        ports:
        - containerPort: 6379
        resources:
          limits:
            cpu: "0.1"
        volumeMounts:
        - mountPath: /redis-master-data
          name: data
      volumes:
        - name: data
          emptyDir: {}

See the Selector section of the Deployment docs.

Tags:

Kubernetes