https://drive.google.com/file/d/1H1E5ZmpeUGX-fgF4_kl85a0QnShOWGW1/view?usp=sharing

πŸ” Script Breakdown (imperative-deployment.sh)

#!/bin/sh
# A: Create Deployment with latest nginx
kubectl create deployment nginx-imperative --image=nginx:latest

# B: Scale to 3 replicas
kubectl scale deployment/nginx-imperative --replicas=3

# C & D: Add metadata annotations
kubectl annotate deployment/nginx-imperative environment=prod
kubectl annotate deployment/nginx-imperative organization=sales

πŸ”‘ Key Insight:

This script uses imperative commands β€” you tell Kubernetes what to do step-by-step.


πŸ“Œ Imperative vs Declarative: Core Differences

Aspect Imperative (kubectl create ...) Declarative (kubectl apply -f ...)
Approach "Do this, then that" "Here’s the desired state β€” make it so"
Audit Trail ❌ Hard to track changes βœ… Full history in Git
Reproducibility ❌ Manual steps βœ… git clone && kubectl apply
Team Collaboration ❌ Error-prone βœ… Code-reviewed YAML
Rollback ❌ Manual βœ… git revert && kubectl apply
Use Case Quick testing, learning Production, GitOps, CI/CD

βœ… Kubernetes Best Practice:

Use declarative YAML for production

Use imperative for quick experiments


πŸ§ͺ k3s Lab: Run Imperative Script & Compare

πŸ”§ Step 1: Run the Script

# Make script executable
chmod +x imperative-deployment.sh

# Run it
./imperative-deployment.sh

# Verify
kubectl get deployments
# NAME                  READY   UP-TO-DATE   AVAILABLE
# nginx-imperative      3/3     3            3

kubectl describe deployment nginx-imperative | grep -A 2 Annotations
# Annotations:
#   environment: prod
#   organization: sales

πŸ”§ Step 2: Export to YAML (See What Was Created)

# Get the full Deployment spec
kubectl get deployment nginx-imperative -o yaml > nginx-imperative.yaml

# View key parts
grep -A 5 "replicas\\\\|image\\\\|annotations" nginx-imperative.yaml

πŸ” You’ll see:

replicas: 3
template:
  spec:
    containers:
    - image: nginx:latest
annotations:
  environment: prod
  organization: sales

πŸ”§ Step 3: Try to "Recreate" Declaratively

πŸ’‘ Now you have a YAML file β€” you could version-control it!

# Delete imperative Deployment
kubectl delete deployment nginx-imperative

# Recreate from YAML
kubectl apply -f nginx-imperative.yaml

# Result: Identical Deployment!

βœ… This is the power of declarative:

Once you have YAML, you’re in GitOps territory.