---
# System prepended metadata

title: 'Script for Class 13 - EKS Fundamentals: Basics'
tags: [aws, eks]

---

#  EKS Fundamentals: Basics

# **Agenda of the Day**

* Introduction to Amazon EKS (Elastic Kubernetes Service)
* Key Components of EKS
* Introduction to YAML in Kubernetes
* Essential EKS Commands
* Managing Deployments and Pods
* Pod Restart Mechanisms in Kubernetes

---

# **Introduction to Amazon EKS (Elastic Kubernetes Service)**  

## **What is Amazon EKS?**  
Amazon Elastic Kubernetes Service (EKS) is a **fully managed Kubernetes service** provided by AWS. It simplifies the deployment, scaling, and management of Kubernetes applications on AWS infrastructure.  
## Container Orchestration Before Amazon EKS

#### **The Rise of Docker (2013 Onward)**
- Docker revolutionized software delivery by introducing lightweight, portable **containers**.
- Developers could package applications and dependencies into a single image and run them consistently across environments.
- However, as usage grew, managing **multiple containers** became complex:
  - How to scale them?
  - How to restart failed containers?
  - How to distribute containers across hosts?

---

### **Docker Swarm: Docker’s Native Orchestration Tool**

#### **What is Docker Swarm?**
- **Docker Swarm** was Docker’s first attempt at native orchestration (built directly into Docker Engine).
- It allowed users to group multiple Docker hosts into a single **“swarm” cluster**.
- Docker CLI could then deploy containers across this cluster.

#### **Core Features of Docker Swarm:**
- **Cluster Management**: Group of Docker nodes (managers & workers)
- **Service Deployment**: Define services (like replicated NGINX containers)
- **Load Balancing**: Built-in routing mesh to distribute traffic
- **Scaling**: Simple `docker service scale` to increase instances
- **Rolling Updates**: Support for updating services without downtime
- **Built-in Security**: TLS encryption between nodes

#### **Limitations of Docker Swarm:**
- Limited flexibility and customizability compared to Kubernetes
- Smaller community and ecosystem
- Not ideal for large, complex microservice systems

---

### **Before EKS: Kubernetes Without AWS Integration**

Before Amazon EKS (Elastic Kubernetes Service) launched in 2018:
- DevOps teams manually installed and managed **Kubernetes** clusters on **EC2 instances**.
- This required:
  - Provisioning nodes
  - Configuring etcd, kube-apiserver, kubelet, kube-proxy manually
  - Setting up networking and security groups
  - Maintaining high availability and fault tolerance

This was time-consuming, error-prone, and required deep Kubernetes knowledge.

---

### **Then Came Amazon EKS (2018)**
- Amazon introduced **EKS** as a **fully managed Kubernetes control plane**.
- Simplified the process of running production-grade Kubernetes clusters:
  - AWS handles availability, upgrades, patching
  - Integrated with IAM, VPC, CloudWatch, ALB, etc.
- Allowed DevOps to focus on apps, not cluster maintenance

---

## **Why Use EKS?**  
- **Simplifies Kubernetes Management:** AWS handles the control plane, making it easier to manage clusters.  
- **Highly Scalable:** Easily scales applications using Kubernetes-native tools like **Horizontal Pod Autoscaler (HPA)**.  
- **Secure and Compliant:** Integrated with AWS services like **IAM, VPC, and AWS Fargate** for security and networking.  
- **Multi-Availability Zone (AZ) Deployment:** Ensures high availability by distributing workloads across different AZs.  

## **Key Features of Amazon EKS**  
1. **Managed Kubernetes Control Plane** – AWS manages the Kubernetes API servers and etcd database.  
2. **Worker Node Management** – Supports EC2 instances and AWS Fargate for running containers.  
3. **Integrated with AWS Services** – Works with services like **IAM, VPC, CloudWatch, ALB, Route 53, and Auto Scaling**.  
4. **Supports Hybrid and On-Prem Deployments** – Works with **EKS Anywhere** for running Kubernetes clusters on-premises.  
5. **Automated Updates and Patching** – AWS handles Kubernetes version upgrades.  

## **Use Cases of EKS**  
 **Microservices Architecture** – Run containerized applications efficiently.  
 **Machine Learning (ML) Workloads** – Deploy ML models using Kubernetes.  
 **Hybrid Cloud Deployments** – Use EKS Anywhere for multi-cloud or on-prem environments.  
 **Continuous Integration & Deployment (CI/CD)** – Integrate with Jenkins, GitHub Actions, or AWS CodePipeline.  

Amazon EKS is widely used for **scalable, secure, and efficient** Kubernetes cluster management, making it a preferred choice for modern cloud-native applications.  

---

# **Key Components of Amazon EKS (Elastic Kubernetes Service)**  

Amazon EKS is built on Kubernetes and consists of several core components that work together to deploy and manage containerized applications. Below are the key components:  

## **1. EKS Cluster**  
An **EKS Cluster** is the main container orchestration unit that manages Kubernetes workloads.  
- It consists of a **control plane** (managed by AWS) and **worker nodes** (managed by users).  
- The control plane runs Kubernetes API servers and manages cluster state.  

## **2. Nodes (Worker Nodes)**  
Nodes are **EC2 instances or AWS Fargate** containers where application workloads run.  
- Managed using **Node Groups** (collections of EC2 instances).  
- Can be scaled up or down based on workload demands.  

## **3. Namespaces**  
Namespaces are **logical partitions** within an EKS cluster that help organize Kubernetes resources.  
- Used to isolate workloads, such as **dev, test, and production environments**.  
- Enables fine-grained access control using **RBAC (Role-Based Access Control)**.  

## **4. Services**  
A **Service** is used to expose applications running on Pods and ensure connectivity between them.  
- **ClusterIP:** Internal communication within the cluster.  
- **NodePort:** Exposes service on a static port on each node.  
- **LoadBalancer:** Integrates with AWS **Elastic Load Balancer (ELB)** for external access.  

## **5. Pods**  
Pods are the **smallest deployable units** in Kubernetes, consisting of one or more containers.  
- Each Pod shares **networking and storage** but runs separate applications.  
- Can be replicated for **high availability** using **Deployments**.  

## **6. Deployments**  
Deployments manage application lifecycle, enabling rolling updates, scaling, and rollback.  
- Ensures Pods are running in the desired state.  
- Supports **Rolling Updates** and **Blue-Green Deployments** for minimal downtime.  

## **7. Jobs & CronJobs**  
Used for running **batch processes** or scheduled tasks.  
- **Job:** Runs a one-time task and ensures it completes successfully.  
- **CronJob:** Schedules jobs at specific time intervals (e.g., nightly backups).  

## **8. ConfigMaps & Secrets**  
- **ConfigMaps:** Store non-sensitive configuration data (e.g., database connection strings).  
- **Secrets:** Securely store sensitive information like passwords, API keys, and certificates.  

## **9. Ingress**  
Ingress **manages external access** to services within the cluster using HTTP/HTTPS routing.  
- Uses AWS **Application Load Balancer (ALB)** or **Nginx Ingress Controller**.  

## **10. Persistent Volumes (PVs) & Persistent Volume Claims (PVCs)**  
Storage components in Kubernetes that enable **data persistence** across Pods.  
- PVs: Provisioned storage from AWS EBS, EFS, or S3.  
- PVCs: Requests for storage resources within a cluster.  

## **11. Horizontal Pod Autoscaler (HPA)**  
Automatically **scales Pods** based on CPU or memory usage.  
- Helps maintain application performance under varying loads.  

## **12. Cluster Autoscaler**  
Automatically adjusts the **number of nodes** in an EKS cluster based on demand.  
- Works with EC2 Auto Scaling groups.  

#  Introduction to YAML in Kubernetes  

##  What is YAML?  

YAML (**Yet Another Markup Language** or **YAML Ain’t Markup Language**) is a **human-readable** format used to define configurations in Kubernetes. It is widely used because of its **simplicity** and **ease of use** compared to other formats like JSON or XML.

---

##  Why is YAML Used in Kubernetes?  

Kubernetes uses YAML to **define, configure, and manage** resources like Pods, Deployments, Services, and ConfigMaps. Instead of using long command-line instructions, YAML allows users to specify **desired states** in a structured file.

###  Key Benefits of YAML in Kubernetes:  
**Human-Readable** – Uses indentation for structure, making it easy to read.  
**Declarative** – Describes what the system should do, not how to do it.  
 **Scalable** – Allows defining multiple resources in a single file.  
 **Flexible** – Supports variables, comments, and multi-line values.  

---

##  Basic Structure of a Kubernetes YAML File  

Every YAML file in Kubernetes follows a similar structure with these key components:

 **API Version (`apiVersion`)** – Specifies which Kubernetes API version to use.  
 **Kind (`kind`)** – Defines the type of resource (e.g., Pod, Deployment, Service).  
 **Metadata (`metadata`)** – Contains unique information like name, labels, and namespace.  
 **Specification (`spec`)** – Describes the desired state of the resource.  

 _Think of it as filling out a form: You declare what you want, and Kubernetes makes it happen._  

---

## How Kubernetes Uses YAML  

*  **Creating Resources** - YAML files help create Kubernetes objects like **Pods, Deployments, Services, and ConfigMaps**.
* **Updating Resources** - Existing configurations can be updated using YAML by modifying the file and applying changes.
* **Scaling Applications** - YAML allows defining how many replicas (instances) an application should have, making scaling **simple and automated**.
* **Managing Networking & Security** - YAML is used to configure network rules, permissions, and access control.


## How to Apply a YAML File in Kubernetes  

Once a YAML file is created, it can be applied using:  
```bash
kubectl apply -f filename.yaml
```

## Kubernetes YAML Examples

### 1. Deployment YAML Example
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        - name: my-container
          image: nginx
```
Runs 2 copies of the application for reliability.

### 2. Service YAML Example
```yaml
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: my-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
```
Exposes the application inside the Kubernetes cluster over Port 80.

#  Essential AWS EKS Commands  

## What is EKS?  
**Amazon Elastic Kubernetes Service (EKS)** is a **managed Kubernetes service** that allows you to run containerized applications on AWS **without** needing to set up and maintain Kubernetes manually.  

### Let's first understand how to Create an Amazon EKS Cluster

Amazon EKS (Elastic Kubernetes Service) allows you to run Kubernetes without managing the control plane. Below is a step-by-step overview of **how to create an EKS cluster**, the **modes available**, and **how to configure `kubectl`** to interact with it.

---

## **Different Modes to Create an EKS Cluster**

| Mode                    | Description                                                                 |
|-------------------------|-----------------------------------------------------------------------------|
| **AWS Management Console** | UI-based creation for beginners and visual tracking                        |
| **AWS CLI**                | Command-line based, great for scripting and automation                     |
| **eksctl**                 | Open-source tool built by AWS for quick setup of EKS and node groups       |
| **CloudFormation/Terraform** | Infrastructure as Code (IaC) to automate and version control the setup |

---

## **Using `eksctl` (Recommended for Simplicity)**

### **Step 1: Install `eksctl`**
```bash
curl --silent --location "https://github.com/eksctl-io/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz" | tar xz -C /tmp
sudo mv /tmp/eksctl /usr/local/bin
```

### **Step 2: Create an EKS Cluster with `eksctl`**
```bash
eksctl create cluster \
  --name demo-cluster \
  --region us-west-2 \
  --nodes 2 \
  --node-type t3.medium \
  --with-oidc \
  --ssh-access \
  --ssh-public-key my-key \
  --managed
```

- `--with-oidc`: enables IAM roles for service accounts
- `--managed`: creates a managed node group (recommended)

---

## **Using AWS Management Console**

1. Go to **EKS** → **Clusters** → **Create cluster**
2. Provide:
   - Cluster name
   - Kubernetes version
   - IAM role (EKS cluster role)
   - VPC and Subnets
3. Create a **Node Group**:
   - Choose EC2 instance types
   - Set scaling config (min/max nodes)
   - Attach IAM role for worker nodes
4. Review and **Create**

---

## **Configure `kubectl` for EKS**

### **Step 1: Install `kubectl`**
```bash
curl -o kubectl https://amazon-eks.s3.us-west-2.amazonaws.com/<k8s-version>/bin/linux/amd64/kubectl
chmod +x ./kubectl
sudo mv ./kubectl /usr/local/bin
```

> Replace `<k8s-version>` with your EKS version (e.g., `1.27`)

### **Step 2: Update `kubeconfig` to use EKS**
```bash
aws eks update-kubeconfig --region us-west-2 --name demo-cluster
```

This command updates `~/.kube/config` with credentials and cluster info.

### **Step 3: Test the Connection**
```bash
kubectl get svc
kubectl get nodes
```

You should see your EKS worker nodes and default services.

---

## **Summary Table: Tools & Commands**

| Tool        | Purpose                         | Command Example                         |
|-------------|----------------------------------|------------------------------------------|
| `eksctl`    | Create/manage EKS cluster        | `eksctl create cluster`                 |
| `aws cli`   | Configure kubeconfig             | `aws eks update-kubeconfig`             |
| `kubectl`   | Interact with Kubernetes cluster | `kubectl get pods`, `kubectl get nodes` |

---

##  **1. Checking EKS Cluster Details**  

* **List Available EKS Clusters**

```bash
aws eks list-clusters --region <your-region>
```

This command shows all the EKS clusters in your AWS region.

* **Describe an EKS Cluster**
```bash
aws eks describe-cluster --name <cluster-name> --region <your-region>
```

Displays details like status, endpoint, version, and IAM roles.
    
## 2. Connecting to an EKS Cluster
```bash
aws eks update-kubeconfig --name <cluster-name> --region <your-region>

### Update kubeconfig for Cluster Access
aws eks update-kubeconfig --name <cluster-name> --region <your-region>
```

This allows you to use kubectl commands to interact with your EKS cluster.

```bash
### Verify Connection to the Cluster
kubectl get nodes
```

If the output shows worker nodes, you’re successfully connected to the cluster.
    
## 3. Managing Worker Nodes

* **List Worker Nodes**
```bash
kubectl get nodes
```

Shows the nodes available in your cluster.

* **Check Node Status**
```bash
kubectl describe node <node-name>
```

Displays detailed node information, including labels, taints, and resource usage.
    
## 4. Deploying Applications on EKS
###  Deploy an Application Using a YAML File
kubectl apply -f <your-file>.yaml

**Used to create or update Kubernetes resources like Pods, Deployments, and Services.**

### Check Running Pods
kubectl get pods
    
**Lists all the running pods inside the cluster.**
### Check Logs of a Pod
kubectl logs <pod-name>

**Useful for debugging applications.**

## 5. Managing Kubernetes Resources
 ### Check Deployments
kubectl get deployments
    
**Lists all deployment resources in the cluster.**
### Check Services
kubectl get services

**Lists all the services running in the cluster.**

### Delete a Deployment or Service
kubectl delete deployment <deployment-name>
kubectl delete service <service-name>

**Removes the specified deployment or service from the cluster.**

## 6. Scaling Applications
### Scale a Deployment (Increase/Decrease Pods)
kubectl scale deployment <deployment-name> --replicas=<number>

**Adjusts the number of running instances of an application.**

### Check Horizontal Pod Autoscaler (HPA)
kubectl get hpa

**Displays the status of auto-scaling policies in your cluster.**

##  7. Deleting an EKS Cluster

aws eks delete-cluster --name <cluster-name> --region <your-region>

**Completely removes the EKS cluster from AWS.**
    
---    
     
 #  Managing Deployments and Pods in Kubernetes  

## Background Around Kubernetes Concepts (Short Overview)

### **What is a Pod?**
- A **Pod** is the **smallest deployable unit** in Kubernetes.
- It wraps one or more containers that:
  - Share the same **network** (IP, port space)
  - Share **storage** volumes (if defined)
- Typically, **1 pod = 1 container**, but can contain helper containers (sidecars).

**Example:** A pod might run a Node.js app and a sidecar container for logging.

---

### **What is a NodePort?**
- **NodePort** is a type of Kubernetes service that **exposes a pod to external traffic** via a static port on each worker node.
- External users can access the service using:
  ```
  <NodeIP>:<NodePort>
  ```
- Valid range: **30000–32767**

**Use Case:** Quick testing or exposing a pod without a load balancer.

---

### **What is ClusterIP?**
- **ClusterIP** is the **default Kubernetes service type**.
- It exposes the service **only within the cluster** using a virtual IP (internal DNS).
- Cannot be accessed directly from outside the cluster.

**Use Case:** For internal communication between services like `frontend` talking to `backend`.

---

##  Creating a Deployment  

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        - name: my-container
          image: nginx
          ports:
            - containerPort: 80
```   
### Explanation
-  replicas: 3 – Runs 3 instances of the Pod.
-  selector – Ensures Pods match this label (app: my-app).
-  template – Defines the Pod specification.
-  image: nginx – Uses the nginx container image.
    
## Managing Deployments
### 1. Apply the Deployment
```bash
    kubectl apply -f deployment.yaml
```

**Creates or updates the Deployment.**

### 2. Check Deployment Status

```bash
    kubectl get deployments
```

**Lists all Deployments running in the cluster..**

### 3. Check Pods Created by Deployment

`kubectl get pods`

**Displays the Pods managed by the Deployment.**

### 4. View Detailed Deployment Info
    
`kubectl describe deployment my-deployment`

**Shows details like events, replicas, and conditions.**
    
## Scaling Deployments
###  Increase or Decrease Replicas

`kubectl scale deployment my-deployment --replicas=5`

**Changes the number of Pods to 5.**

### Check Updated Replica Count

`kubectl get deployments`

**Confirms the new number of replicas.**
    
## Updating Deployments
### Update the Container Image

`kubectl set image deployment my-deployment my-container=nginx:latest`

**Changes the running image to nginx:latest.**
    
### Check Rollout Status 

kubectl rollout status deployment my-deployment

**Ensures the update is successfully applied.**
    
### View Deployment History

`kubectl rollout history deployment my-deployment`

**Displays previous versions of the Deployment.**
    
### Rollback to Previous Version

`kubectl rollout undo deployment my-deployment`

**Reverts to the last stable version.**
    
## Deleting Deployments and Pods

### Delete a Deployment
    
`kubectl delete deployment my-deployment`

**Removes the Deployment and all associated Pods.**

### Delete a Specific Pod

`kubectl delete pod <pod-name>`

**Deletes a single Pod without affecting the Deployment.**
    
    
#  Pod Restart Mechanisms in Kubernetes  

##  Why Do Pods Restart?  
Kubernetes automatically restarts Pods under certain conditions to ensure applications remain **available and resilient**.  

###  **Pod Restart Triggers**  
 Container crashes due to errors.  
 Node failure where the Pod was running.  
 Manual Pod deletion (if managed by a Deployment).  
 Kubernetes scheduling a Pod on a different node.  

---

##  How Pods Restart in Kubernetes  

##  **1. Restart Policy (Pod-Level Control)**  
Each Pod has a **restart policy** that defines **how containers restart** when they fail.  

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: restart-example
spec:
  containers:
    - name: my-container
      image: busybox
      command: ["sh", "-c", "exit 1"]  # Simulates a failure
  restartPolicy: Always
```
    
   `restartPolicy` options:

Restart Policy 	Behavior
Always -	Restart container every time it fails (default for Deployments).
OnFailure -	Restart container only if it exits with an error.
Never - Never restart the container, even if it fails.
    
**Only applies to standalone Pods**. Deployments always use `Always`.    
 ## 2. Deployment Controller (Self-Healing Mechanism)  

If a Pod in a **Deployment, ReplicaSet, or StatefulSet** crashes or is deleted, Kubernetes **automatically creates a new Pod.**
    
### Example Deployment:
```
apiVersion: apps/v1
kind: Deployment
metadata:
  name: self-healing-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        - name: my-container
          image: nginx
```
**If a Pod fails, Kubernetes creates a replacement Pod to maintain 3 replicas.**

## 3. Liveness Probes (Detecting Crashes)

Liveness probes check if a container is still **healthy**. If it fails, Kubernetes **automatically restarts the container.**
    
 ### Example Liveness Probe:

```
apiVersion: v1
kind: Pod
metadata:
  name: liveness-probe-example
spec:
  containers:
    - name: my-container
      image: nginx
      livenessProbe:
        httpGet:
          path: /
          port: 80
        initialDelaySeconds: 5
        periodSeconds: 10
```
    
 **If the `/` endpoint stops responding, Kubernetes restarts the container.**    
    
## Node Failure & Pod Eviction in Kubernetes

### **1. Node Failure**

- A **node** is a virtual or physical machine in the Kubernetes cluster that runs pods.
- If a node becomes **unreachable** (e.g., due to network failure, system crash, or hardware issue), the Kubernetes control plane starts monitoring its health.

#### **How Node Failures Are Detected:**
- The **Kubelet** on each node sends regular heartbeats to the control plane.
- If no response is received for a default duration (usually **5 minutes**), the node is marked as **NotReady**.

---

### **2. Pod Eviction**

Once a node is marked **unhealthy**, Kubernetes initiates **pod eviction** to maintain workload availability.

#### **Eviction Process:**
- Pods scheduled on the failed node are **terminated** and marked as **Unknown**.
- The **scheduler** then attempts to create **new pods** on other healthy nodes in the cluster.
- The ability to reschedule depends on:
  - Resource availability on other nodes
  - Pod **affinity/anti-affinity** rules
  - Taints and tolerations

---

### **Key Configurations:**
- **`node-monitor-grace-period`**: Time before a node is considered unhealthy (default: 40s)
- **`pod-eviction-timeout`**: Time before eviction begins after node failure (default: 5m)

---

### **Important Notes:**
- Kubernetes does **not auto-reboot** a failed node; recovery of infrastructure is your responsibility or the cloud provider’s.
- To improve resilience:
  - Use **Pod Disruption Budgets**
  - Enable **pod anti-affinity rules** to spread workloads across nodes
  - Configure **autoscaling** (Cluster Autoscaler, HPA)

---

## 5. Manual Pod Deletion & Restarting
If you manually delete a Pod that is managed by a Deployment, Kubernetes will automatically create a new one.

kubectl delete pod <pod-name>

**The Deployment recreates the Pod to match the desired replicas.**

However, if the Pod is not part of a Deployment, it will not restart!
    
## How to Prevent Unwanted Pod Restarts
 
### 1. Use `restartPolicy: Never` for One-Time Jobs
For batch jobs, set the restart policy to Never:
```
spec:
  restartPolicy: Never
```
 ### 2. Use Readiness Probes to Prevent Bad Deployments

If an application isn't ready, prevent Kubernetes from routing traffic to it:
```
readinessProbe:
  httpGet:
    path: /
    port: 80
  initialDelaySeconds: 10
  periodSeconds: 5
```
### 3. Debugging Frequent Pod Restarts
```
kubectl get pods
kubectl describe pod <pod-name>
kubectl logs <pod-name>
```
**Check the Events, Logs, and Status to diagnose the issue.**

 ---
# Wrap-up and Q&A: 

### **Amazon EKS Overview**
- Amazon EKS is a **fully managed Kubernetes service** by AWS that simplifies running containerized applications at scale.
- It offloads the complexity of managing Kubernetes control plane, offering built-in integrations with IAM, VPC, ECR, CloudWatch, and more.

### **Key EKS Components**
- **EKS Cluster**: Hosts and manages workloads
- **Node Groups**: EC2 or Fargate resources running pods
- **Pods & Services**: Basic units of deployment and networking
- **IAM Roles & Policies**: For secure access control
- **Kubeconfig & `kubectl`**: CLI tools for interacting with your EKS cluster

### **Understanding YAML in Kubernetes**
- YAML is used to define Kubernetes resources declaratively.
- It includes **kind**, **metadata**, **spec**, and other attributes to define deployments, services, etc.
- Writing clean, properly indented YAML is crucial for successful deployment.

### **Essential EKS Commands**
- `eksctl create cluster`: Create a cluster quickly
- `aws eks update-kubeconfig`: Configure local `kubectl` to talk to EKS
- `kubectl get pods`, `kubectl apply -f`: Inspect and manage Kubernetes objects

### **Managing Deployments and Pods**
- Deployments manage the desired state of applications (e.g., replicas, updates).
- You can scale, roll out, and roll back using simple commands like:
  ```bash
  kubectl scale deployment <name> --replicas=3
  kubectl rollout status deployment <name>
  ```

### **Pod Restart Mechanisms**
- Kubernetes uses controllers to **automatically restart failed pods**.
- **Liveness probes** and **readiness probes** can help manage health checks and restarts.
- Crash loops and evictions are handled based on pod status and node conditions.

---

# Multiple Choice Questions (MCQs)

## **1. Introduction to Amazon EKS (Elastic Kubernetes Service)**  
### **Q1. What is the primary purpose of Amazon EKS?**  
A) To manage EC2 instances  
B) To run and manage Kubernetes workloads on AWS  
C) To store and retrieve files in AWS  
D) To automate database backups  

**Answer:** B) To run and manage Kubernetes workloads on AWS  

### **Q2. What does Amazon EKS manage on behalf of the user?**  
A) Worker nodes  
B) Kubernetes control plane  
C) Application code  
D) IAM roles  

**Answer:** B) Kubernetes control plane  

### **Q3. Which AWS service provides serverless compute for EKS pods?**  
A) EC2  
B) Lambda  
C) Fargate  
D) CloudFormation  

**Answer:** C) Fargate  

---

## **2. Key Components of EKS**  
### **Q4. What is a Kubernetes Pod?**  
A) A group of AWS Lambda functions  
B) The smallest deployable unit in Kubernetes  
C) A virtual machine in AWS  
D) An IAM security role  

**Answer:** B) The smallest deployable unit in Kubernetes  

### **Q5. Which component helps expose Kubernetes services externally?**  
A) Deployment  
B) Ingress  
C) Namespace  
D) ConfigMap  

**Answer:** B) Ingress  

### **Q6. What is the function of a Kubernetes Deployment?**  
A) It runs a one-time task  
B) It stores application logs  
C) It manages and scales Pods  
D) It provides storage for databases  

**Answer:** C) It manages and scales Pods  

---

## **3. Introduction to YAML in Kubernetes**  
### **Q7. What is YAML used for in Kubernetes?**  
A) Storing container logs  
B) Configuring Kubernetes objects  
C) Running shell scripts  
D) Creating IAM roles  

**Answer:** B) Configuring Kubernetes objects  

### **Q8. Which of the following is NOT a valid section in a Kubernetes YAML file?**  
A) `apiVersion`  
B) `kind`  
C) `metadata`  
D) `script`  

**Answer:** D) `script`  

### **Q9. What does the `spec` section in a YAML file define?**  
A) The metadata of the object  
B) The desired state of the object  
C) The security settings of the object  
D) The namespace of the object  

**Answer:** B) The desired state of the object  

---

## **4. Essential EKS Commands**  
### **Q10. What command is used to list all running Pods in an EKS cluster?**  
A) `eksctl get pods`  
B) `kubectl get pods`  
C) `aws eks list-pods`  
D) `kubectl describe nodes`  

**Answer:** B) `kubectl get pods`  

### **Q11. How do you apply a Kubernetes manifest file?**  
A) `kubectl apply -f <file>.yaml`  
B) `kubectl deploy -f <file>.yaml`  
C) `eksctl apply -f <file>.yaml`  
D) `aws eks apply -f <file>.yaml`  

**Answer:** A) `kubectl apply -f <file>.yaml`  

### **Q12. What command is used to check logs of a specific Pod?**  
A) `kubectl describe logs <pod-name>`  
B) `kubectl get logs <pod-name>`  
C) `kubectl logs <pod-name>`  
D) `aws eks logs <pod-name>`  

**Answer:** C) `kubectl logs <pod-name>`  

---

## **5. Understanding Kubernetes Jobs**  
### **Q13. What is the main purpose of a Kubernetes Job?**  
A) Running short-lived, one-time workloads  
B) Managing long-running applications  
C) Controlling IAM permissions  
D) Providing storage for Pods  

**Answer:** A) Running short-lived, one-time workloads  

### **Q14. What happens to a Kubernetes Job after it completes execution?**  
A) It restarts indefinitely  
B) It terminates and does not restart  
C) It automatically scales up  
D) It deletes itself immediately  

**Answer:** B) It terminates and does not restart  

### **Q15. How do you define a Kubernetes Job in YAML?**  
A) By setting `kind: Deployment`  
B) By setting `kind: Job`  
C) By setting `kind: Pod`  
D) By setting `kind: Namespace`  

**Answer:** B) By setting `kind: Job`  

---

## **6. Managing Deployments and Pods**  
### **Q16. What is the purpose of a Kubernetes Deployment?**  
A) It creates and manages sets of replicated Pods  
B) It stores container logs  
C) It provides storage volumes  
D) It manages IAM roles  

**Answer:** A) It creates and manages sets of replicated Pods  

### **Q17. How do you scale a Deployment in Kubernetes?**  
A) `kubectl set scale deployment <deployment-name> --replicas=3`  
B) `kubectl increase deployment <deployment-name> --replicas=3`  
C) `eksctl scale deployment <deployment-name> --replicas=3`  
D) `aws eks update deployment <deployment-name> --replicas=3`  

**Answer:** A) `kubectl set scale deployment <deployment-name> --replicas=3`  

### **Q18. What command deletes a Deployment in Kubernetes?**  
A) `kubectl remove deployment <deployment-name>`  
B) `kubectl delete deployment <deployment-name>`  
C) `eksctl delete deployment <deployment-name>`  
D) `aws eks delete deployment <deployment-name>`  

**Answer:** B) `kubectl delete deployment <deployment-name>`  

---

## **7. Pod Restart Mechanisms in Kubernetes**  
### **Q19. Which of the following can be used to restart a Pod in Kubernetes?**  
A) `kubectl delete pod <pod-name>`  
B) `kubectl restart pod <pod-name>`  
C) `kubectl refresh pod <pod-name>`  
D) `aws eks restart pod <pod-name>`  

**Answer:** A) `kubectl delete pod <pod-name>` (Kubernetes will recreate it automatically if part of a Deployment)  

### **Q20. What is a Rolling Restart in Kubernetes?**  
A) A method to restart all Pods at the same time  
B) A process that sequentially restarts Pods with zero downtime  
C) A mechanism to delete all resources in a cluster  
D) A way to add new worker nodes dynamically  

**Answer:** B) A process that sequentially restarts Pods with zero downtime  

### **Q21. Which command triggers a rolling restart in Kubernetes?**  
A) `kubectl rollout restart deployment <deployment-name>`  
B) `kubectl restart deployment <deployment-name>`  
C) `eksctl restart deployment <deployment-name>`  
D) `aws eks restart deployment <deployment-name>`  

**Answer:** A) `kubectl rollout restart deployment <deployment-name>`  

---

# Scenario Based Questions



##  1. Introduction to Amazon EKS (Elastic Kubernetes Service)  

### **Q1: What problem does Amazon EKS solve?**  
#### **Scenario:**  
You work at a company that wants to deploy containerized applications on Kubernetes, but managing a self-hosted Kubernetes cluster is complex.  

#### **Answer:**  
Amazon EKS provides a **managed Kubernetes service**, handling **control plane management, security, and scalability**. It removes the overhead of **manual cluster setup, upgrades, and maintenance**.  

---

### **Q2: How does Amazon EKS integrate with AWS services?**  
#### **Scenario:**  
Your team wants to use AWS-native services like IAM, VPC, and ALB with Kubernetes workloads.  

#### **Answer:**  
EKS **seamlessly integrates** with:  
- **IAM** for authentication & authorization.  
- **VPC** for networking.  
- **ALB/NLB** for load balancing.  
- **CloudWatch** for logging & monitoring.  

---

##  2. Key Components of EKS  

### **Q3: What are the key components of an EKS cluster?**  
#### **Scenario:**  
Your manager asks you to explain the architecture of an EKS cluster.  

#### **Answer:**  
An EKS cluster consists of:  
- **Control Plane** (Managed by AWS) – Handles API requests & scheduling.  
- **Worker Nodes** (EC2 or Fargate) – Run the actual workloads.  
- **VPC & Networking** – Ensures secure communication.  
- **IAM Roles** – Control permissions for Kubernetes services.  

---

### **Q4: How do worker nodes communicate with the control plane?**  
#### **Scenario:**  
Your team is troubleshooting why worker nodes are not connecting to the control plane.  

#### **Answer:**  
Worker nodes communicate using **AWS IAM-authenticated API calls** over **private networking (VPC, ENI)**. Ensure:  
- The **IAM role** for nodes allows communication.  
- The **VPC security group** allows inbound/outbound traffic.  

---
   ## Introduction to YAML in Kubernetes  

### Scenario  Basic YAML Structure  

###  **Question:**  
You are given the following YAML file but it has **errors**. Can you **fix the mistakes**?  

```yaml
apiVersion: v1
kind Pod
metadata:
  name: mypod
spec:
  container:
    - name: my-container
      image: nginx
```
Step-by-Step Solution:
🔹 Step 1: Identify syntax errors.
🔹 Step 2: Correct kind Pod → kind: Pod (missing colon).
🔹 Step 3: Fix container → containers (should be plural).
🔹 Step 4: Add proper indentation and formatting.

###  **Answer**

```
  apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
    - name: my-container
      image: nginx

  ```

##  3. Essential EKS Commands  

### **Q5: How do you create an EKS cluster?**  
#### **Scenario:**  
Your company wants to deploy a new EKS cluster and asks you for the steps.  

#### **Answer:**  
1️⃣ **Create an EKS cluster** using AWS Console or Terraform.  
2️⃣ **Create worker nodes** (EC2 or Fargate).  
3️⃣ **Update kubeconfig** to connect the cluster.  
4️⃣ **Deploy applications** using `kubectl`.  

---

### **Q6: How do you check if your EKS cluster is running?**  
#### **Scenario:**  
You need to verify if the EKS cluster is active.  

#### **Answer:**  
- Use AWS Console → EKS → Check Cluster Status.  
- Use `kubectl get nodes` to list worker nodes.  

---

##  4. Understanding Kubernetes Jobs  

### **Q7: When would you use a Kubernetes Job instead of a Deployment?**  
#### **Scenario:**  
Your application requires **one-time data processing** instead of continuous running.  

#### **Answer:**  
Use a **Job** when:  
✅ Running **batch jobs** (e.g., file processing, database migration).  
✅ A task **needs to complete** and **not restart** like a Deployment.  

---

### **Q8: How does Kubernetes retry failed Jobs?**  
#### **Scenario:**  
A Kubernetes Job failed due to a **temporary database outage**, and you want to know if it will retry.  

#### **Answer:**  
Kubernetes **retries Jobs** based on the `backoffLimit` (default: **6 retries**). If exceeded, the Job enters **Failed state**.  

---

##  5. Managing Deployments and Pods  

### **Q9: How do Deployments ensure high availability?**  
#### **Scenario:**  
Your company wants to ensure **zero downtime** when updating a web application.  

#### **Answer:**  
Deployments use:  
- **Rolling Updates** – Updates Pods gradually.  
- **ReplicaSets** – Keep multiple Pods running.  
- **Health Probes** – Ensure new Pods are ready before removing old ones.  

---

### **Q10: What happens when a Pod is manually deleted?**  
#### **Scenario:**  
You deleted a Pod from a Deployment, and another Pod automatically appeared.  

#### **Answer:**  
The **Deployment controller detects** the missing Pod and **creates a new one** to maintain the desired replica count.  

---

##  6. Pod Restart Mechanisms in Kubernetes  

### **Q11: How does Kubernetes restart a failed Pod?**  
#### **Scenario:**  
A container inside a Pod **crashes** due to an application bug.  

#### **Answer:**  
- **Standalone Pod** → Restart depends on `restartPolicy`.  
- **Deployment Pod** → Automatically recreated by the Deployment.  

---

### **Q12: What is the role of Liveness Probes in Pod restarts?**  
#### **Scenario:**  
Your API server **stops responding**, but the container remains running.  

#### **Answer:**  
- A **Liveness Probe** detects unresponsive containers and **triggers a restart**.  
- Prevents containers from staying in a **"hung" state**.  

---
