Skip to main content

Python Variables Quiz

Β· 5 min read

Progress

Score: 0/20

🎩 Python Naming Conventions

Prove your DevSecOps expertise! Answer 20 questions to earn your rank. Green = Correct, Red = Incorrect.

BeginnerVariables

  • **A) CamelCase**
  • **B) PascalCase**
  • **C) snake_case**
  • **D) UPPER_CASE**

πŸ’‘ Explanation​

Snake Case (snake_case) is the Python standard.

According to PEP 8, variables and function names should be lowercase with underscores to separate words.

IntermediateClass Naming

When should you strictly use PascalCase?​

  • **A) For Function Names**
  • **B) For Class Names**
  • **C) For Constants**
  • **D) For Private Variables**

πŸ’‘ Explanation​

For Class Names (e.g., BankAccount).

This helps developers instantly recognize that BankAccount is a blueprint (Class), whereas bank_account is an instance.

BeginnerStandards

What is PEP 8?​

  • **A) A Python Compiler**
  • **B) A Testing Tool**
  • **C) The Official Style Guide**
  • **D) A Database Driver**

πŸ’‘ Explanation​

The "Bible" of Python Styling.

PEP 8 (Python Enhancement Proposal 8) defines the standard rules for formatting Python code.

IntermediateConstants

How should you name a constant value like PI?​

  • **A) pi**
  • **B) Pi**
  • **C) PI**
  • **D) _pi**

πŸ’‘ Explanation​

UPPER_CASE (e.g., PI, MAX_RETRIES).

Capitalizing every letter signals: "This value is fixed. Do not change it."

ArchitectAutomation

Which tool automatically checks your code for style violations?​

  • **A) Python Tutor**
  • **B) A Linter (e.g., pylint)**
  • **C) The Compiler**
  • **D) Git**

πŸ’‘ Explanation​

A Linter (like pylint or flake8).

In DevSecOps pipelines, linters reject code that doesn't follow PEP 8 before it reaches production.

AdvancedAnti-Patterns

Why avoid Hungarian Notation (e.g., strName)?​

  • **A) Python is dynamically typed**
  • **B) It uses too much memory**
  • **C) It is illegal syntax**
  • **D) Python doesn't support strings**

πŸ’‘ Explanation​

Because types can change.

Since Python is dynamic, strName could technically be assigned a number later, making the name misleading.

BeginnerDescriptive Naming

Which variable name is preferred?​

  • **A) d = 10``**
  • **B) days = 10``**
  • **C) days_since_login = 10``**
  • **D) i = 10``**

πŸ’‘ Explanation​

days_since_login

Style is important, but meaning is critical. d is vague. The full name explains exactly what the data represents.

AdvancedExceptions

When is it acceptable to use CamelCase (e.g., setUp)?​

  • **A) Always**
  • **B) Never**
  • **C) In legacy libs (unittest)**
  • **D) For private variables**

πŸ’‘ Explanation​

When using legacy libraries.

Libraries like unittest were ported from Java, so they use CamelCase. You must match their style when using them.

BeginnerRefactoring

Refactor calculate_Salary to Python style:​

  • **A) CalculateSalary``**
  • **B) calculate_salary``**
  • **C) calculateSalary``**
  • **D) CALCULATE_SALARY``**

πŸ’‘ Explanation​

calculate_salary (Snake Case).

Functions should always use lowercase letters with underscores.

IntermediateSingle Letter Vars

When are single-letter vars (i, x) okay?​

  • **A) For database keys**
  • **B) In short loops/math formulas**
  • **C) For global variables**
  • **D) Never**

πŸ’‘ Explanation​

In short loops or math.

Using i for loop counters or x, y for coordinates is standard. For anything else, be descriptive.

AdvancedPrivate Variables

What does a single underscore prefix mean (e.g., _data)?​

  • **A) It is a System Variable**
  • **B) It is for "Internal Use" (Hint)**
  • **C) It cannot be accessed at all**
  • **D) It makes the variable constant**

πŸ’‘ Explanation​

"Internal Use Only" (Convention).

Python doesn't have true private variables. A single underscore is a polite note to other developers: "Please don't touch this from outside the class."

ArchitectName Mangling

What happens with double underscores (e.g., __password)?​

  • **A) It becomes public**
  • **B) It deletes the variable**
  • **C) Python changes its name (Mangling)**
  • **D) It throws an error**

πŸ’‘ Explanation​

Name Mangling triggers.

Python internally renames __password to _ClassName__password to prevent subclasses from accidentally overwriting it. It is the closest thing to "Private" in Python.

IntermediateShadowing

Why is list = [1, 2, 3] a bad variable name?​

  • **A) Lists must be empty**
  • **B) It shadows the built-in list()``**
  • **C) Variable names must be 5 chars**
  • **D) It causes a Memory Leak**

πŸ’‘ Explanation​

It shadows a built-in function.

If you name your variable list, you overwrite Python's actual list() function. Later, if you try to convert a tuple to a list using list((1,2)), your code will crash.

IntermediateModules

What is the convention for Module names (file names)?​

  • **A) short_lowercase.py**
  • **B) PascalCase.py**
  • **C) camelCase.py**
  • **D) UPPERCASE.py**

πŸ’‘ Explanation​

Short, all-lowercase names.

Modules should have short, all-lowercase names (e.g., numpy, requests). Underscores can be used if it improves readability, but short is better.

BeginnerReadability

Which single letter variable should be avoided due to font issues?​

  • **A) x**
  • **B) z**
  • **C) l (lowercase L)**
  • **D) a**

πŸ’‘ Explanation​

Lowercase L (l), Uppercase O (O).

In many fonts, l looks exactly like the number 1, and O looks like 0. Using them as variable names confuses other developers.

AdvancedWhitespace

Which assignment follows PEP 8 whitespace rules?​

  • **A) x=1``**
  • **B) x = 1``**
  • **C) x = 1``**
  • **D) x= 1``**

πŸ’‘ Explanation​

x = 1 (One space on each side).

PEP 8 recommends surrounding assignment operators with a single space to let the code "breathe."

ArchitectError Naming

How should you name a custom Exception class?​

  • **A) DatabaseCrash``**
  • **B) database_error``**
  • **C) DatabaseError``**
  • **D) ErrorDatabase``**

πŸ’‘ Explanation​

Suffix with 'Error' (PascalCase).

Exceptions are Classes, so they use PascalCase. The convention is to end the name with "Error" (e.g., ValueError, KeyError, MyCustomError).

IntermediateArguments

What is the correct style for Function Arguments?​

  • **A) def func(my_arg):``**
  • **B) def func(MyArg):``**
  • **C) def func(myArg):``**
  • **D) def func(ARG):``**

πŸ’‘ Explanation​

Snake Case (my_arg).

Function arguments follow the same rule as variables: lowercase with underscores.

AdvancedLine Length

According to strict PEP 8, what is the max line length?​

  • **A) 120 chars**
  • **B) 79 chars**
  • **C) 100 chars**
  • **D) Unlimited**

πŸ’‘ Explanation​

79 Characters.

While modern teams often use 100 or 120, the strict PEP 8 standard is 79 characters. This dates back to when terminals were only 80 columns wide.

ArchitectImports

Which import style is preferred?​

  • **A) import my_lib``**
  • **B) from my_lib import *``**
  • **C) import MyLib``**
  • **D) import numpy as np (Standard Alias)**

πŸ’‘ Explanation​

Explicit Aliases (e.g., np for numpy).

Avoid import * because it pollutes the namespace (variables might clash). Using standard aliases like pd for pandas or np for numpy is best practice.

πŸŽ‰ Quiz Complete!​

Your Final Score:

0/20 Novice

Keep practicing to reach Architect level!

  • **β†Ί Retake Quiz**

Amazon EKS Pod Identity Lab

Β· 6 min read

EKS Pod Identity is the newer, streamlined alternative to IRSA. Unlike IRSA, it does not require configuring an OIDC provider for the cluster, and it does not require annotating Kubernetes Service Accounts with IAM Role ARNs.

Install the EKS Pod Identity Agent, create an IAM role with the correct trust policy, map it to a Kubernetes Service Account using Pod Identity Associations, and verify S3 access from a test Pod.

Prerequisites​

  • An active Amazon EKS cluster (Kubernetes version 1.24 or later).

  • kubectl, eksctl, and aws CLI tools configured and authenticated.

Step 1: Install the EKS Pod Identity Agent Add-on​

EKS Pod Identity requires a specific add-on running on your worker nodes to intercept the AWS credential requests from pods.

Bash

export CLUSTER_NAME="my-eks-cluster"
export AWS_REGION="us-east-1"

eksctl create addon \
--cluster $CLUSTER_NAME \
--name eks-pod-identity-agent \
--region $AWS_REGION \
--approve

``

export CLUSTER_NAME="my-eks-cluster"
export AWS_REGION="us-east-1"

eksctl create addon \
--cluster $CLUSTER_NAME \
--name eks-pod-identity-agent \
--region $AWS_REGION \
--approve

Step 2: Create the IAM Role and Trust Policy​

EKS Pod Identity uses a different trust policy than IRSA. Instead of trusting an OIDC provider, it trusts the pods.eks.amazonaws.com service principal.

1: Create the Trust Policy document:

Bash

cat < trust-policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "pods.eks.amazonaws.com"
},
"Action": &#91;
"sts:AssumeRole",
"sts:TagSession"
&#93;
}
]
}
EOF

``

cat < trust-policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "pods.eks.amazonaws.com"
},
"Action": &#91;
"sts:AssumeRole",
"sts:TagSession"
&#93;
}
]
}
EOF

2: Create the IAM Role:

Bash

ROLE_ARN=$(aws iam create-role \
--role-name EKSPodIdentityS3Role \
--assume-role-policy-document file://trust-policy.json \
--query 'Role.Arn' \
--output text)

echo $ROLE_ARN

``

ROLE_ARN=$(aws iam create-role \
--role-name EKSPodIdentityS3Role \
--assume-role-policy-document file://trust-policy.json \
--query &#39;Role.Arn&#39; \
--output text)

echo $ROLE_ARN

3: Attach a Permissions Policy: For this lab, we will attach the AWS-managed ReadOnly S3 policy.

Bash

aws iam attach-role-policy \
--role-name EKSPodIdentityS3Role \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

``

aws iam attach-role-policy \
--role-name EKSPodIdentityS3Role \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

Step 3: Create the Pod Identity Association​

This step links your IAM Role to a specific Kubernetes Namespace and Service Account directly within the AWS API.

Bash

aws eks create-pod-identity-association \
--cluster-name $CLUSTER_NAME \
--role-arn $ROLE_ARN \
--namespace default \
--service-account pod-id-sa

``

aws eks create-pod-identity-association \
--cluster-name $CLUSTER_NAME \
--role-arn $ROLE_ARN \
--namespace default \
--service-account pod-id-sa

Step 4: Deploy the Kubernetes Resources​

Notice that unlike IRSA, the Kubernetes Service Account does not need an eks.amazonaws.com/role-arn annotation. The EKS Pod Identity Agent handles the mapping automatically based on the association created in Step 3.

Bash

cat < test-pod-identity.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: pod-id-sa
namespace: default
---
apiVersion: v1
kind: Pod
metadata:
name: aws-cli-pod-identity
namespace: default
spec:
serviceAccountName: pod-id-sa
containers:
- name: aws-cli
image: amazon/aws-cli:latest
command: &#91;"sleep", "3600"&#93;
restartPolicy: Never
EOF

kubectl apply -f test-pod-identity.yaml

``

cat < test-pod-identity.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: pod-id-sa
namespace: default
---
apiVersion: v1
kind: Pod
metadata:
name: aws-cli-pod-identity
namespace: default
spec:
serviceAccountName: pod-id-sa
containers:
- name: aws-cli
image: amazon/aws-cli:latest
command: &#91;"sleep", "3600"&#93;
restartPolicy: Never
EOF

kubectl apply -f test-pod-identity.yaml

Wait for the Pod to be in the Running state:

Bash

kubectl get pods aws-cli-pod-identity -w

``

kubectl get pods aws-cli-pod-identity -w

Step 5: Verify EKS Pod Identity Configuration​

Exec into the Pod to verify that credentials are being successfully intercepted and vended by the Pod Identity Agent.

1: Verify Identity: Check which IAM role the Pod is assuming.

Bash

kubectl exec -it aws-cli-pod-identity -- aws sts get-caller-identity

``

kubectl exec -it aws-cli-pod-identity -- aws sts get-caller-identity

Expected Output: The Arn should reflect an assumed role based on EKSPodIdentityS3Role, formatted like arn:aws:sts:::assumed-role/EKSPodIdentityS3Role/eks-....

2: Test S3 Access:

Bash

kubectl exec -it aws-cli-pod-identity -- aws s3 ls

``

kubectl exec -it aws-cli-pod-identity -- aws s3 ls

Expected Output: A list of S3 buckets in your account.

3: Check the Environment (Optional Validation): With EKS Pod Identity, you will notice that AWS SDKs use a different credential provider chain variable.

Bash

kubectl exec -it aws-cli-pod-identity -- env | grep AWS_CONTAINER_AUTHORIZATION_TOKEN

``

kubectl exec -it aws-cli-pod-identity -- env | grep AWS_CONTAINER_AUTHORIZATION_TOKEN

Expected Output: You should see an environment variable pointing to the token file managed by the Pod Identity agent, rather than the AWS_WEB_IDENTITY_TOKEN_FILE used by IRSA.

Step 6: Teardown​

Remove the resources to clean up your environment.

Bash

# Delete Kubernetes resources
kubectl delete -f test-pod-identity.yaml

# Delete the Pod Identity Association
ASSOCIATION_ID=$(aws eks list-pod-identity-associations --cluster-name $CLUSTER_NAME --namespace default --service-account pod-id-sa --query 'associations&#91;0&#93;.associationId' --output text)

aws eks delete-pod-identity-association \
--cluster-name $CLUSTER_NAME \
--association-id $ASSOCIATION_ID

# Detach policy and delete IAM role
aws iam detach-role-policy \
--role-name EKSPodIdentityS3Role \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

aws iam delete-role --role-name EKSPodIdentityS3Role

# Clean up local files
rm trust-policy.json test-pod-identity.yaml

# (Optional) Delete the add-on if you no longer need it
eksctl delete addon --cluster $CLUSTER_NAME --name eks-pod-identity-agent

``

# Delete Kubernetes resources
kubectl delete -f test-pod-identity.yaml

# Delete the Pod Identity Association
ASSOCIATION_ID=$(aws eks list-pod-identity-associations --cluster-name $CLUSTER_NAME --namespace default --service-account pod-id-sa --query &#39;associations&#91;0&#93;.associationId&#39; --output text)

aws eks delete-pod-identity-association \
--cluster-name $CLUSTER_NAME \
--association-id $ASSOCIATION_ID

# Detach policy and delete IAM role
aws iam detach-role-policy \
--role-name EKSPodIdentityS3Role \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

aws iam delete-role --role-name EKSPodIdentityS3Role

# Clean up local files
rm trust-policy.json test-pod-identity.yaml

# (Optional) Delete the add-on if you no longer need it
eksctl delete addon --cluster $CLUSTER_NAME --name eks-pod-identity-agent

IAM Roles for Service Accounts IRSA across multi-cloud environments Lab

Β· 6 min read

Implementing IAM Roles for Service Accounts (IRSA) across multi-cloud environments (e.g., authenticating GKE, AKS, or on-premises Kubernetes workloads to AWS) requires decoupling the AWS IAM OIDC federation mechanism from the Amazon EKS mutating admission webhook.

In a native EKS environment, the EKS control plane automatically configures the cluster's OIDC discovery endpoint and runs a webhook that intercepts Pod creation to inject AWS environment variables and the Kubelet-projected OIDC token volume.

For multi-cloud workloads, you must manually architect these three components:

  • Expose the external Kubernetes cluster's Service Account Issuer discovery endpoint publicly.

  • Register the external cluster's OIDC issuer URL as an Identity Provider in AWS IAM.

  • Manually construct the Pod specification with a projected Service Account token volume and explicit AWS SDK environment variables.

Step 1: Retrieve the External Cluster's OIDC Issuer URL​

Your external Kubernetes cluster must have Service Account Token Volume Projection and OIDC discovery enabled, and the JSON Web Key Set (JWKS) endpoint must be publicly accessible to AWS STS.

For Google Kubernetes Engine (GKE), you can retrieve the active OIDC issuer URL using the Google Cloud CLI:

Bash

# Retrieve K8s OIDC Issuer for a GKE cluster
export ISSUER_URL=$(gcloud container clusters describe gke-cluster \
--region us-central1 \
--format="value(workloadIdentityConfig.workloadPool)")

# For AKS or custom clusters, this is typically a public HTTPS URL
# ending in /.well-known/openid-configuration
echo $ISSUER_URL

``

# Retrieve K8s OIDC Issuer for a GKE cluster
export ISSUER_URL=$(gcloud container clusters describe gke-cluster \
--region us-central1 \
--format="value(workloadIdentityConfig.workloadPool)")

# For AKS or custom clusters, this is typically a public HTTPS URL
# ending in /.well-known/openid-configuration
echo $ISSUER_URL

Step 2: Register the OIDC Provider in AWS​

AWS IAM must trust the external K8s cluster's identity provider. You must fetch the TLS certificate thumbprint of the external K8s API server's domain and register it.

Bash

export AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export ISSUER_HOST=$(echo $ISSUER_URL | awk -F/ '{print $3}')

# Fetch the top-level CA thumbprint for the OIDC endpoint
export THUMBPRINT=$(echo | openssl s_client -servername $ISSUER_HOST -showcerts -connect $ISSUER_HOST:443 2>/dev/null | openssl x509 -in /dev/stdin -fingerprint -noout | awk -F= '{print tolower($2)}' | tr -d ':')

# Create the OIDC Identity Provider in AWS IAM
aws iam create-open-id-connect-provider \
--url "https://$ISSUER_URL" \
--client-id-list "sts.amazonaws.com" \
--thumbprint-list $THUMBPRINT

``

export AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export ISSUER_HOST=$(echo $ISSUER_URL | awk -F/ &#39;{print $3}&#39;)

# Fetch the top-level CA thumbprint for the OIDC endpoint
export THUMBPRINT=$(echo | openssl s_client -servername $ISSUER_HOST -showcerts -connect $ISSUER_HOST:443 2>/dev/null | openssl x509 -in /dev/stdin -fingerprint -noout | awk -F= &#39;{print tolower($2)}&#39; | tr -d &#39;:&#39;)

# Create the OIDC Identity Provider in AWS IAM
aws iam create-open-id-connect-provider \
--url "https://$ISSUER_URL" \
--client-id-list "sts.amazonaws.com" \
--thumbprint-list $THUMBPRINT

Step 3: Create the AWS IAM Role and Trust Policy​

Create an IAM role that explicitly trusts the external OIDC provider and restricts assumption to a specific K8s namespace and service account name (e.g., default namespace, multicloud-sa service account).

Bash

export OIDC_PROVIDER_ARN="arn:aws:iam::$AWS_ACCOUNT_ID:oidc-provider/$ISSUER_URL"

cat < multicloud-trust-policy.json
{
"Version": "2012-10-17",
"Statement": &#91;
{
"Effect": "Allow",
"Principal": {
"Federated": "$OIDC_PROVIDER_ARN"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"$ISSUER_URL:aud": "sts.amazonaws.com",
"$ISSUER_URL:sub": "system:serviceaccount:default:multicloud-sa"
}
}
}
&#93;
}
EOF

# Create Role
ROLE_ARN=$(aws iam create-role \
--role-name MultiCloudIRSARole \
--assume-role-policy-document file://multicloud-trust-policy.json \
--query 'Role.Arn' \
--output text)

# Attach a testing policy (e.g., S3 ReadOnly)
aws iam attach-role-policy \
--role-name MultiCloudIRSARole \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

``

export OIDC_PROVIDER_ARN="arn:aws:iam::$AWS_ACCOUNT_ID:oidc-provider/$ISSUER_URL"

cat < multicloud-trust-policy.json
{
"Version": "2012-10-17",
"Statement": &#91;
{
"Effect": "Allow",
"Principal": {
"Federated": "$OIDC_PROVIDER_ARN"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"$ISSUER_URL:aud": "sts.amazonaws.com",
"$ISSUER_URL:sub": "system:serviceaccount:default:multicloud-sa"
}
}
}
&#93;
}
EOF

# Create Role
ROLE_ARN=$(aws iam create-role \
--role-name MultiCloudIRSARole \
--assume-role-policy-document file://multicloud-trust-policy.json \
--query &#39;Role.Arn&#39; \
--output text)

# Attach a testing policy (e.g., S3 ReadOnly)
aws iam attach-role-policy \
--role-name MultiCloudIRSARole \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

Step 4: Configure the Kubernetes Workload (The Manual Injection)​

Because the external cluster lacks the EKS pod identity mutating webhook, you must manually recreate what the webhook does. This involves defining a ServiceAccount and explicitly configuring the Pod to project an OIDC token and set the exact environment variables expected by the AWS SDKs (AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE).

Bash

cat < multicloud-pod.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: multicloud-sa
namespace: default
---
apiVersion: v1
kind: Pod
metadata:
name: aws-cli-multicloud
namespace: default
spec:
serviceAccountName: multicloud-sa
containers:
- name: aws-cli
image: amazon/aws-cli:latest
command: &#91;"sleep", "3600"&#93;
env:
# 1. Provide the IAM Role ARN
- name: AWS_ROLE_ARN
value: "$ROLE_ARN"
# 2. Point the SDK to the projected token path
- name: AWS_WEB_IDENTITY_TOKEN_FILE
value: "/var/run/secrets/aws-iam-token/token"
volumeMounts:
- name: aws-iam-token
mountPath: /var/run/secrets/aws-iam-token
readOnly: true
volumes:
# 3. Request a projected service account token tailored for AWS STS
- name: aws-iam-token
projected:
sources:
- serviceAccountToken:
audience: sts.amazonaws.com
expirationSeconds: 86400
path: token
EOF

# Deploy to the external K8s cluster
kubectl apply -f multicloud-pod.yaml

``

cat < multicloud-pod.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: multicloud-sa
namespace: default
---
apiVersion: v1
kind: Pod
metadata:
name: aws-cli-multicloud
namespace: default
spec:
serviceAccountName: multicloud-sa
containers:
- name: aws-cli
image: amazon/aws-cli:latest
command: &#91;"sleep", "3600"&#93;
env:
# 1. Provide the IAM Role ARN
- name: AWS_ROLE_ARN
value: "$ROLE_ARN"
# 2. Point the SDK to the projected token path
- name: AWS_WEB_IDENTITY_TOKEN_FILE
value: "/var/run/secrets/aws-iam-token/token"
volumeMounts:
- name: aws-iam-token
mountPath: /var/run/secrets/aws-iam-token
readOnly: true
volumes:
# 3. Request a projected service account token tailored for AWS STS
- name: aws-iam-token
projected:
sources:
- serviceAccountToken:
audience: sts.amazonaws.com
expirationSeconds: 86400
path: token
EOF

# Deploy to the external K8s cluster
kubectl apply -f multicloud-pod.yaml

Step 5: Verify Federation Architecture​

Once the Kubelet creates the Pod, it requests a JWT from the external K8s API server with the audience sts.amazonaws.com. It mounts this JWT into the container. When the aws CLI executes, the underlying AWS SDK reads the token and calls sts:AssumeRoleWithWebIdentity against AWS, exchanging the K8s JWT for temporary AWS credentials.

Verify this credential exchange within the external pod:

Bash

# Verify the injected K8s JWT exists
kubectl exec -it aws-cli-multicloud -- cat /var/run/secrets/aws-iam-token/token

# Verify AWS identity resolution via the exchanged token
kubectl exec -it aws-cli-multicloud -- aws sts get-caller-identity

# Execute an authorized AWS API call from K8s
kubectl exec -it aws-cli-multicloud -- aws s3 ls

``

# Verify the injected K8s JWT exists
kubectl exec -it aws-cli-multicloud -- cat /var/run/secrets/aws-iam-token/token

# Verify AWS identity resolution via the exchanged token
kubectl exec -it aws-cli-multicloud -- aws sts get-caller-identity

# Execute an authorized AWS API call from K8s
kubectl exec -it aws-cli-multicloud -- aws s3 ls

IAM Roles for Service Accounts IRSA Lab

Β· 4 min read

Provision an OpenID Connect (OIDC) identity provider, map an AWS IAM Role to a Kubernetes Service Account, and verify access using a test Pod.

Prerequisites​

  • An active Amazon EKS cluster.

  • kubectl, eksctl, and aws CLI tools configured and authenticated.


Step 1: Associate an OIDC Provider​

EKS clusters have an OIDC issuer URL. You must associate an IAM OIDC provider with this cluster so IAM can validate the tokens generated by Kubernetes.

Bash

# Replace and with your cluster details
export CLUSTER_NAME="eks-cluster"
export AWS_REGION="us-east-1"

eksctl utils associate-iam-oidc-provider \
--cluster $CLUSTER_NAME \
--region $AWS_REGION \
--approve

``

# Replace and with your cluster details
export CLUSTER_NAME="eks-cluster"
export AWS_REGION="us-east-1"

eksctl utils associate-iam-oidc-provider \
--cluster $CLUSTER_NAME \
--region $AWS_REGION \
--approve

Step 2: Create an AWS IAM Policy​

Create a policy that defines the exact AWS permissions the Pod requires. In this lab, we will grant read-only access to Amazon S3.

Bash

cat < s3-readonly-policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": &#91;
"s3:ListAllMyBuckets",
"s3:GetBucketLocation"
&#93;,
"Resource": "*"
}
]
}
EOF

# Create the policy and capture the ARN
POLICY_ARN=$(aws iam create-policy \
--policy-name EKSS3ReadOnlyPolicy \
--policy-document file://s3-readonly-policy.json \
--query 'Policy.Arn' \
--output text)

echo $POLICY_ARN

``

cat < s3-readonly-policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": &#91;
"s3:ListAllMyBuckets",
"s3:GetBucketLocation"
&#93;,
"Resource": "*"
}
]
}
EOF

# Create the policy and capture the ARN
POLICY_ARN=$(aws iam create-policy \
--policy-name EKSS3ReadOnlyPolicy \
--policy-document file://s3-readonly-policy.json \
--query &#39;Policy.Arn&#39; \
--output text)

echo $POLICY_ARN

Step 3: Create the IAM Role and Kubernetes Service Account​

This step creates an IAM role, attaches the policy from Step 2, and creates a Kubernetes Service Account annotated with the IAM Role ARN. It establishes the trust relationship.

Bash

eksctl create iamserviceaccount \
--name s3-reader-sa \
--namespace default \
--cluster $CLUSTER_NAME \
--region $AWS_REGION \
--attach-policy-arn $POLICY_ARN \
--approve \
--override-existing-serviceaccounts

``

eksctl create iamserviceaccount \
--name s3-reader-sa \
--namespace default \
--cluster $CLUSTER_NAME \
--region $AWS_REGION \
--attach-policy-arn $POLICY_ARN \
--approve \
--override-existing-serviceaccounts

Step 4: Deploy a Test Pod​

Deploy an AWS CLI Pod configured to use the newly created Service Account (s3-reader-sa).

Bash

cat < test-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: aws-cli-tester
namespace: default
spec:
serviceAccountName: s3-reader-sa
containers:
- name: aws-cli
image: amazon/aws-cli:latest
command: &#91;"sleep", "3600"&#93;
restartPolicy: Never
EOF

kubectl apply -f test-pod.yaml

``

cat < test-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: aws-cli-tester
namespace: default
spec:
serviceAccountName: s3-reader-sa
containers:
- name: aws-cli
image: amazon/aws-cli:latest
command: &#91;"sleep", "3600"&#93;
restartPolicy: Never
EOF

kubectl apply -f test-pod.yaml

Wait for the Pod to be in the Running state:

Bash

kubectl get pods aws-cli-tester -w

``

kubectl get pods aws-cli-tester -w

Step 5: Verify IRSA Configuration​

Exec into the Pod and verify that the AWS CLI is automatically picking up the injected web identity token.

1: Check the environment variables: Kubernetes automatically injects AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE when the Service Account is annotated.

Bash

kubectl exec -it aws-cli-tester -- env | grep AWS

``

kubectl exec -it aws-cli-tester -- env | grep AWS

2: Verify Identity: Check which IAM role the Pod is assuming.

Bash

kubectl exec -it aws-cli-tester -- aws sts get-caller-identity

``

kubectl exec -it aws-cli-tester -- aws sts get-caller-identity

Expected Output: The Arn should reflect the IAM role created in Step 3, not the worker node's IAM role.

3: Test S3 Access:

Bash

kubectl exec -it aws-cli-tester -- aws s3 ls

``

kubectl exec -it aws-cli-tester -- aws s3 ls

Expected Output: A list of S3 buckets in your account.

4: Test Unauthorized Access (Validation): Attempt to create an S3 bucket to ensure the least privilege policy is enforced.

Bash

kubectl exec -it aws-cli-tester -- aws s3 mb s3://my-irsa-test-bucket-12345

``

kubectl exec -it aws-cli-tester -- aws s3 mb s3://my-irsa-test-bucket-12345

Expected Output: AccessDenied error.

Step 6: Teardown​

Remove the resources to avoid any ongoing configuration drift or clutter.

Bash

kubectl delete -f test-pod.yaml

eksctl delete iamserviceaccount \
--name s3-reader-sa \
--namespace default \
--cluster $CLUSTER_NAME \
--region $AWS_REGION

aws iam delete-policy --policy-arn $POLICY_ARN
rm s3-readonly-policy.json test-pod.yaml

``

kubectl delete -f test-pod.yaml

eksctl delete iamserviceaccount \
--name s3-reader-sa \
--namespace default \
--cluster $CLUSTER_NAME \
--region $AWS_REGION

aws iam delete-policy --policy-arn $POLICY_ARN
rm s3-readonly-policy.json test-pod.yaml

AWS EKS Cluster Creating Lab

Β· 5 min read

Hands-on Lab: Provisioning Your First EKS Cluster with eksctl​

Objective: Spin up a fully functional Amazon Elastic Kubernetes Service (EKS) cluster using eksctl, deploy a test workload to verify functionality, and tear it down to optimize costs.

Cost Warning: This lab requires an AWS account and will incur small charges. The EKS Control Plane costs ~$0.10 per hour, plus the cost of the EC2 instances (t3.medium instances are ~$0.04/hr each). Total lab cost should be well under $1.00 if torn down immediately after completion.

Step 1: The Prerequisites​

Before building the cluster, you need the right tools installed on your local machine. These tools act as the bridge between your terminal and the AWS Cloud infrastructure.

  • AWS CLI (Command Line Interface): Used to authenticate your terminal with your AWS account.

  • Install: choco install awscli -y

  • kubectl: The standard Kubernetes command-line tool. It allows you to run commands against Kubernetes clusters to deploy applications, inspect resources, and view logs.

  • Install: choco install kubernetes-cli -y

  • eksctl: The official CLI for Amazon EKS, originally created by Weaveworks and officially endorsed by AWS. It automates the heavy lifting of writing complex CloudFormation templates.

  • Install: choco install eksctl -y

Step 2: Authenticate with AWS​

Your terminal needs to know who you are and what permissions you have before it can build infrastructure on your behalf.

  • Generate an Access Key ID and Secret Access Key from the IAM (Identity and Access Management) console in your AWS account. Ensure this IAM user has Administrator access (or sufficient privileges to create VPCs, EC2 instances, IAM roles, and EKS clusters).

  • Open your terminal and run: aws configure

  • Input your credentials when prompted:

  • AWS Access Key ID: Paste your key here.

  • AWS Secret Access Key: Paste your secret here.

  • Default region name: us-east-1 (or your preferred region).

  • Default output format: json

Step 3: Create the Cluster Config File​

While you can use a massive single-line command to build a cluster, Infrastructure as Code (IaC) is the industry standard. It makes your deployments repeatable, readable, and version-controllable.

Create a new directory for your project, navigate into it, and create a file named cluster.yaml:

YAML

apiVersion: eksctl.io/v1alpha5
kind: ClusterConfig

metadata:
name: devsecops-guru-cluster
region: us-east-1
version: "1.34" # Using a modern, supported Kubernetes version

managedNodeGroups:
- name: standard-nodes
instanceType: t3.medium
minSize: 1
maxSize: 2
desiredCapacity: 1
volumeSize: 20
ssh:
allow: true # Optional: Allows SSH access using AWS SSM if needed
labels:
role: "worker-node"
tags:
environment: "practice-lab"

``

apiVersion: eksctl.io/v1alpha5
kind: ClusterConfig

metadata:
name: devsecops-guru-cluster
region: us-east-1
version: "1.34" # Using a modern, supported Kubernetes version

managedNodeGroups:
- name: standard-nodes
instanceType: t3.medium
minSize: 1
maxSize: 2
desiredCapacity: 1
volumeSize: 20
ssh:
allow: true # Optional: Allows SSH access using AWS SSM if needed
labels:
role: "worker-node"
tags:
environment: "practice-lab"

Step 4: Launch the Cluster!​

With your blueprint ready, it's time to trigger the build. Run the following command in the same directory as your cluster.yaml file:

Bash

eksctl create cluster -f cluster.yaml

``

eksctl create cluster -f cluster.yaml

(EKS takes about 15-20 minutes to provision the VPC, Subnets, Control Plane, and Node Groups behind the scenes).

Step 5: Verify the Connection​

Once the terminal outputs that the cluster is ready, eksctl will automatically update your local ~/.kube/config file. This file acts as your VIP pass, telling kubectl exactly where your cluster is and how to securely authenticate with it.

Check your nodes:

Bash

kubectl get nodes

``

kubectl get nodes

You should see two t3.medium instances listed with a Ready status.

Check the system pods:

Bash

kubectl get pods -n kube-system

``

kubectl get pods -n kube-system

This will show you the critical internal components running, such as aws-node (the VPC CNI for networking), coredns (for internal service discovery), and kube-proxy.

Step 6: Mini Project - Deploy a Test Application​

To truly validate your cluster, let's deploy a simple web server and expose it to the internet.

1: Create a Deployment:

Bash

kubectl create deployment nginx-demo --image=nginx:latest

``

kubectl create deployment nginx-demo --image=nginx:latest

2: Expose the Deployment:

Bash

kubectl expose deployment nginx-demo --port=80 --type=LoadBalancer

``

kubectl expose deployment nginx-demo --port=80 --type=LoadBalancer

3: Find your Load Balancer URL:

Bash

kubectl get svc nginx-demo

``

kubectl get svc nginx-demo

Look under the EXTERNAL-IP column. It will look like a long AWS DNS string (e.g., a1b2c3d4...us-east-1.elb.amazonaws.com).

Note: It may take 2-3 minutes for the underlying AWS Load Balancer to provision. Once it does, paste that URL into your web browser to see the default NGINX welcome page!

Step 7: The Clean Up (Crucial for Cost Optimization)​

The most important habit of a good cloud engineer is tearing down infrastructure when it is no longer needed. Do not skip this step, or you will continue to be billed for the Load Balancer, EC2 instances, and the EKS Control Plane.

Ensure you are in the same directory as your cluster.yaml file, and run:

Bash

eksctl delete cluster -f cluster.yaml

``

eksctl delete cluster -f cluster.yaml

Verify the cluster is gone by running kubectl get nodes. You should receive an error stating the server could not be reached or the connection was refused.

Kubernetes API-Server Lab

Β· 6 min read

Most of the labs only works on the Kubernetes and Linux Not on EKS, AKS, GKE.

Lab 1: The "RESTful" Nature (Talking Directly to the Hub)​

Concept: The text states the API Server is the "Central Hub" that speaks standard HTTP. This lab bypasses kubectl abstraction to see the raw JSON.

1: Start a Proxy: Open a terminal and run a proxy to handle authentication for you locally.

`kubectl proxy --port=8080 &`

2: Send a GET Request: act like a browser and query the API server directly.

`curl http://localhost:8080/api/v1/pods`

3: Analyze: You will see a massive JSON output. This proves the API server returns raw data (Desired State + Status) which kubectl usually formats for you.

Filter with jq (Optional):

`curl -s http://localhost:8080/api/v1/pods | jq .items&#91;].metadata.name`

Lab 2: The "Listener" (The Watch Mechanism)​

Concept: The text describes the API Server as "The Listener" that notifies components instantly rather than polling.

1: Terminal 1 (The Watcher): Run a command that establishes a long-lived connection.

`kubectl get pods -w`

2: Terminal 2 (The Actor): Create a new pod.

`kubectl run watch-test --image=nginx`

3: Observe Terminal 1: You will see the status change from Pending -> ContainerCreating -> Running instantly. This is the Watch API in action, pushing updates to the client.


Lab 3: The "Guard" Gate 1 (Authentication - Service Accounts)​

Concept: The text highlights "Service Accounts (Robots)" as a key Identity Type.

1: Create a Service Account:

`kubectl create sa robot-user`

2: Create a Token (Modern approach):

`kubectl create token robot-user`

3: Test Access: Copy the token output and try to talk to the API server as this "Robot".

# Replace with your actual token
kubectl get pods --token=

Result: It should likely succeed (if default permissions allow) or fail with "Forbidden" (if the cluster is secure), proving the API server identified the "Robot".


Lab 4: The "Guard" Gate 1 (Authentication - X.509 Certificates)​

1: Concept: The text details X.509 Certs as the standard for Admins. Let's simulate creating a new human user, "Rajkumar".

Generate a Private Key:

`openssl genrsa -out rajkumar.key 2048`

2: Generate a CSR (Certificate Signing Request): Note CN=rajkumar (User) and O=devs (Group).

`openssl req -new -key rajkumar.key -out rajkumar.csr -subj "/CN=rajkumar/O=devs"`

3: Send CSR to Kubernetes:

cat < rajkumar.crt`

6: Create Kubeconfig Credential:

kubectl config set-credentials rajkumar --client-certificate=rajkumar.crt --client-key=rajkumar.key --embed-certs=true

You now have a valid X.509 user credential managed by the API Server.


Lab 5: The "Guard" Gate 2 (Authorization - RBAC)​

Concept: The text states, "Once identified, the server checks if the user has permission."

1: Test Access (Fail First): Use the user "Rajkumar" from Lab 4.

`kubectl get pods --user=rajkumar`

Expected Result: Error from server (Forbidden): pods is forbidden: User "rajkumar" cannot list resource "pods" (AuthN passed, AuthZ failed).

2: Create the Role (The Permission):

`kubectl create role pod-reader --verb=list,get --resource=pods`

3: Create the Binding (The Link):

`kubectl create rolebinding rajkumar-pod-reader --role=pod-reader --user=rajkumar`

Test Access (Success):

`kubectl get pods --user=rajkumar`

Expected Result: Success. The "Guard" now lets you pass.


Lab 6: The "Gatekeeper" (Admission Control)​

Concept: The text mentions Admission Control as the final safety check (e.g., "Image pull policy"). We will use a LimitRange (a native admission plugin) to mutate a request.

Create a LimitRange: This tells the API server to mutate any pod that doesn't have resource limits defined.

apiVersion: v1
kind: LimitRange
metadata:
name: mem-limit-range
spec:
limits:
- default:
memory: 512Mi
defaultRequest:
memory: 256Mi
type: Container

Create a Pod without limits:

`kubectl run test-pod --image=nginx`

Inspect the Pod:

`kubectl get pod test-pod -o yaml | grep memory`

Result: You will see limits: memory: 512Mi and requests: memory: 256Mi. The API Server (Admission Controller) intercepted your request and injected these values before saving to Etcd.


Lab 7: Extensibility (Custom Resource Definitions - CRDs)​

Concept: The text states, "To the API Server, these look and act just like native Pods."

1: Define a CRD:

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: backups.stable.example.com
spec:
group: stable.example.com
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
cronSpec:
type: string
scope: Namespaced
names:
plural: backups
singular: backup
kind: Backup

Save as crd.yaml and kubectl apply -f crd.yaml.

Create a Custom Resource:

apiVersion: stable.example.com/v1
kind: Backup
metadata:
name: my-new-backup
spec:
cronSpec: "* * * * */5"

Save as my-backup.yaml and apply it.

Verify:

kubectl get backups

Result: The API Server now serves your custom "Backup" object just like it serves Pods.


Lab 8: Observability (The Aggregation Layer)​

Concept: The text mentions kubectl top uses the "Aggregation Layer" to proxy requests to an extension server (metrics-server).

Check Aggregation:

`kubectl get apiservices`

Look for: v1beta1.metrics.k8s.io. If this exists and says True, the aggregation layer is working.

Test the Proxy:

`kubectl top pods`

Explanation: The main API Server receives this request, looks up the metrics.k8s.io service, and forwards the packet to the metrics-server pod.


Lab 9: Troubleshooting (Etcd & Healthz)​

Concept: The text calls Etcd "The Brain's Memory" and mentions checking health.

1: Check API Health Verbose:

`kubectl get --raw='/healthz?verbose'`

Analyze Output: Look specifically for the [+]etcd line.

  • Output: [+]etcd ok

  • Context: This confirms the API Server can successfully read/write to the Etcd database. If this fails, the cluster is down.


Lab 10: API Priority & Fairness (The Scaler)​

Concept: The text mentions "APF" prevents low-priority requests from starving critical ones.

1: View Flow Schemas:

`kubectl get flowschemas`

2: Inspect Priority Levels:

`kubectl get prioritylevelconfigurations`

3: Analyze: Notice categories like system-leader-election (high priority) versus workload-low (low priority). This visualizes the internal traffic shaping described in the text.


Lab 11: Troubleshooting (Expired Certs Simulation)​

Concept: The text lists "Expired Certs" as a common issue.

1: Check Expiration (Kubeadm clusters only):

`kubeadm certs check-expiration`

Note: This command requires you to be logged into the control plane node via SSH.

2: Simulate Solution: The text says the solution is kubeadm certs renew all. (Do not run this unless you are on a sandbox cluster you own!). knowing where to find this info is the practice.

Kubernetes API-Server Quiz

Β· One min read

Control Plane

Score: 0/25

☸️ Master Quiz: Kube-API Server

Validate your knowledge of the Cluster's Brain, Security Gates, and Etcd communication.

πŸŽ‰ Audit Complete!​

Your Control Plane Status:

0/25 Unauthenticated

  • **β†Ί Restart Controller**

Kubernetes Architecture Quiz

Β· One min read

Cluster State

Score: 0/25

☸️ Master Quiz: Kubernetes Architecture

Validate your knowledge of the Control Plane, Worker Nodes, and Internal Components.

πŸŽ‰ Check Complete!​

Your Cluster Health:

0/25 CrashLoopBackOff

  • **β†Ί Restart Controller**

Kubernetes ETCD Lab

Β· 5 min read

Lab 1: The "Hello World" of Etcd (Direct Interaction)​

Goal: Understand how to talk to Etcd directly, bypassing the Kubernetes API.

Prerequisites: A running Kubernetes cluster.

1: Find your Etcd credentials: Kubernetes locks Etcd down with mTLS. You need the certs to talk to it.

`# Standard kubeadm paths export CACERT="/etc/kubernetes/pki/etcd/ca.crt" export CERT="/etc/kubernetes/pki/etcd/server.crt" export KEY="/etc/kubernetes/pki/etcd/server.key"`

2: Write a Key:

`ETCDCTL_API=3 etcdctl --cacert=$CACERT --cert=$CERT --key=$KEY put /test-key "Hello DevSecOps"`

3: Read a Key:

`ETCDCTL_API=3 etcdctl --cacert=$CACERT --cert=$CERT --key=$KEY get /test-key`

4: Watch a Key (Live Monitoring): Open a second terminal and "watch" the key. Then update it in the first terminal.

# Terminal 2
ETCDCTL_API=3 etcdctl --cacert=$CACERT --cert=$CERT --key=$KEY watch /test-key

Lab 2: The "Cluster Saver" (Backup & Restore)​

Goal: This is the #1 most important lab for the CKA exam and production maintenance.

Scenario: You are about to upgrade the cluster, so you need a snapshot. Then, simulate a disaster where data is deleted.

1: Create a Snapshot:

ETCDCTL_API=3 etcdctl --endpoints=https://127.0.0.1:2379 \
--cacert=$CACERT --cert=$CERT --key=$KEY \
snapshot save /tmp/etcd-backup.db

2: Verify the Snapshot:

ETCDCTL_API=3 etcdctl --write-out=table snapshot status /tmp/etcd-backup.db

3: Simulate Disaster: Delete a critical resource (e.g., a Deployment or Namespace).

kubectl delete deployment nginx-deployment

4: Restore the Snapshot:

  • Stop the API Server: Move the manifest file out of /etc/kubernetes/manifests/.

  • Restore:

ETCDCTL_API=3 etcdctl snapshot restore /tmp/etcd-backup.db \
--data-dir /var/lib/etcd-restored
  • Update Configuration: Edit /etc/kubernetes/manifests/etcd.yaml to point the hostPath to the new /var/lib/etcd-restored directory.

  • Restart: Put the API server manifest back. Verify the deleted deployment is back.


Lab 3: The "Secret Shield" (Encryption at Rest)​

Goal: Encrypt Kubernetes Secrets so they aren't stored as plain text in Etcd.

Scenario: An attacker gets access to the Etcd raw data (like in Lab 1). We want to ensure they see garbage instead of passwords.

1: Create a Secret:

kubectl create secret generic my-secret --from-literal=password=supersecret

2: Read it from Etcd (Hacker View):

ETCDCTL_API=3 etcdctl --cacert=$CACERT --cert=$CERT --key=$KEY get /registry/secrets/default/my-secret
# You will see "supersecret" in plain text!

3: Enable Encryption:

  • Create an EncryptionConfiguration YAML file.

  • Mount this file into the kube-apiserver pod.

  • Add the flag --encryption-provider-config to the API server manifest.

4: Verify Encryption: Create a new secret and try to read it from Etcd again. You should see a garbled prefix like k8s:enc:aescbc:v1:....


Lab 4: The "Heart Transplant" (Member Failure & Removal)​

Goal: Handle a broken Etcd node in a multi-node cluster.

Scenario: One of your 3 control plane nodes has hard drive failure.

1: List Members:

ETCDCTL_API=3 etcdctl --cacert=$CACERT --cert=$CERT --key=$KEY member list

2: Identify Leader:

ETCDCTL_API=3 etcdctl --cacert=$CACERT --cert=$CERT --key=$KEY endpoint status --write-out=table

3: Remove a Member (Simulate Failure):

  • Get the ID of a follower node (e.g., a8266ecf031671f3).

  • Remove it:

ETCDCTL_API=3 etcdctl --cacert=$CACERT --cert=$CERT --key=$KEY member remove a8266ecf031671f3

4: Add a New Member:

  • Clean the data directory on the node you want to add.

  • Add it back to the cluster:

ETCDCTL_API=3 etcdctl --cacert=$CACERT --cert=$CERT --key=$KEY member add --peer-urls=https://:2380

Lab 5: The "Janitor" (Defrag & Maintenance)​

Goal: Prevent "Database Space Exceeded" errors.

Scenario: Your cluster has been running for months with high churn (lots of pod creation/deletion). Etcd is getting slow or full.

1: Check Fragmentation:

  • Run endpoint status and look at DB SIZE vs USED SPACE. If DB SIZE is much larger, you have fragmentation.

2: Compact History: Remove old revisions (e.g., keep only the last revision).

# Get current revision
REV=$(ETCDCTL_API=3 etcdctl --cacert=$CACERT --cert=$CERT --key=$KEY endpoint status --write-out="json" | egrep -o '"revision":&#91;0-9]*' | egrep -o '&#91;0-9]*')
# Compact
ETCDCTL_API=3 etcdctl --cacert=$CACERT --cert=$CERT --key=$KEY compact $REV

3: Defrag: Reclaim the disk space.

ETCDCTL_API=3 etcdctl --cacert=$CACERT --cert=$CERT --key=$KEY defrag

Lab 6: The "Time Traveler" (Debugging with Etcd)​

Goal: Use Etcd to understand Kubernetes object versions.

Scenario: You applied a change to a ConfigMap and want to see the exact version history stored in the DB.

1: Edit a ConfigMap multiple times: Change a value in a ConfigMap 3 or 4 times using kubectl edit.

Inspect the Key in Etcd:

# Get all versions/revisions of a key
ETCDCTL_API=3 etcdctl --cacert=$CACERT --cert=$CERT --key=$KEY get /registry/configmaps/default/my-config --prefix --rev=0
  • Note: Detailed history requires configuring Etcd to retain history explicitly, but watching the revision number increment is the key lesson here.

Kubernetes ETCD Quiz

Β· One min read

Data Consistency

Score: 0/25

πŸ’Ύ Master Quiz: Etcd Architecture

Validate your understanding of the Cluster's Memory, Raft Consensus, and Resilience.

πŸŽ‰ Transaction Committed!​

Your Data Integrity:

0/25 Corrupted

  • **β†Ί New Transaction**