Kubernetes - deep dive questions - Series 02 - Solution

Question Area : Node Affinity:
- Describe what node affinity is and provide a scenario where you'd need to use it. Show a YAML configuration snippet demonstrating how to set a pod's affinity to nodes labeled with
zone=west.
- Describe what node affinity is and provide a scenario where you'd need to use it. Show a YAML configuration snippet demonstrating how to set a pod's affinity to nodes labeled with
Solutions : Node affinity is conceptually similar to nodeSelector, allowing you to constrain which nodes your Pod can be scheduled on based on node labels. There are two types of node affinity:
requiredDuringSchedulingIgnoredDuringExecution: The scheduler can't schedule the Pod unless the rule is met. This functions like nodeSelector, but with a more expressive syntax.
preferredDuringSchedulingIgnoredDuringExecution: The scheduler tries to find a node that meets the rule. If a matching node is not available, the scheduler still schedules the Pod.
apiVersion: v1
kind: Pod
metadata:
name: with-node-affinity
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: zone
operator: In
values:
- west
preferredDuringSchedulingIgnoredDuringExecution: #Another Option
- weight: 1
preference:
matchExpressions:
- key: another-node-label-key
operator: In
values:
- another-node-label-value
containers:
- name: with-node-affinity
image: registry.k8s.io/pause:2.0
Explanation :
Spec (Specification):
Affinity:
Node Affinity:
Required During Scheduling Ignored During Execution:
This section contains rules that must be met for a pod to be scheduled on a node.
nodeSelectorTerms: A list of node selector terms, where each term specifies a set of conditions that a node must meet.Match Expressions:
A key-value pair used for selecting nodes.
operator:In(this means the key's value must be in the set of values provided)values: Specifies the values for the key. In this case, the values areantarctica-east1andantarctica-west1. The pod can only be scheduled on nodes with these zone labels.
Preferred During Scheduling Ignored During Execution:
This section contains preferences that the scheduler will try to enforce but will not guarantee.
weight: Assigned as 1 (weights can be between 0 and 100).preference: Defines a node preference.Match Expressions:
key:another-node-label-keyoperator:Invalues: Contains a single valueanother-node-label-value. The scheduler will prefer nodes with this label.
![Terraform Function - Part 1 [Collection functions] - with examples](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1703964504127%2F858bcdce-10ce-484e-ba7c-2c80be482edc.png&w=3840&q=75)
![Terraform Function - Part 1 [lookup] - with examples](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1703963612987%2Fdb6dbc27-56ed-4ce5-8aec-49e6002c26a6.png&w=3840&q=75)

