PART 6: HANDS-ON LABS
Lab 1: Inspect etcd Data
Goal: Read and understand etcd contents.
bash
# Set etcdctl alias
alias etcdctl='ETCDCTL_API=3 etcdctl \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key'
# Health check
etcdctl endpoint health
etcdctl endpoint status --write-out=table
# List all keys (careful — this can be large)
etcdctl get / --prefix --keys-only | head -50
# Get a specific key
etcdctl get /registry/namespaces/default
# Get pods
etcdctl get /registry/pods/default --prefix --keys-only | head -20
# Check database size
etcdctl endpoint status --write-out=table
# Check alarms
etcdctl alarm list
Lab 2: Back Up and Restore etcd
Goal: Practice disaster recovery.
bash
# Backup
ETCDCTL_API=3 etcdctl snapshot save /tmp/etcd-backup.db \
--endpoints=https://127.0.0.1:2379 \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key
# Verify backup
ETCDCTL_API=3 etcdctl snapshot status /tmp/etcd-backup.db --write-out=table
# Restore (in a test environment!)
# WARNING: This replaces etcd data
# 1. Stop API server
# 2. Restore
# 3. Restart API server
# Restore command (do NOT run in production without testing)
# ETCDCTL_API=3 etcdctl snapshot restore /tmp/etcd-backup.db \
# --data-dir=/var/lib/etcd-restored
Lab 3: Trace an API Request Through Admission
Goal: See admission in action.
bash
# Create a simple Pod
kubectl run test --image=nginx
# Check events for admission activity
kubectl get events --field-selector involvedObject.name=test
# Check which admission controllers are enabled
kubectl exec -n kube-system <apiserver-pod> -- \
kube-apiserver --help 2>&1 | grep admission
# Or check the static pod manifest
cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep admission
# Create a Pod that violates a policy
kubectl run privileged --image=nginx --overrides='
{
"spec": {
"containers": [{
"name": "privileged",
"image": "nginx",
"securityContext": {"privileged": true}
}]
}
}'
# Expected: Error from PodSecurity admission
# Cleanup
kubectl delete pod test 2>/dev/null
Lab 4: Write a Mutating Admission Webhook
Goal: Build a webhook that adds labels.
Prerequisites: A Kubernetes cluster with webhook access.
python
# webhook.py
from flask import Flask, request, jsonify
import base64
app = Flask(__name__)
@app.route('/mutate', methods=['POST'])
def mutate():
admission_review = request.get_json()
pod = admission_review['request']['object']
# Add a label
patch = [
{
'op': 'add',
'path': '/metadata/labels/managed-by',
'value': 'my-webhook'
}
]
# Encode patch
patch_bytes = json.dumps(patch).encode()
patch_b64 = base64.b64encode(patch_bytes).decode()
return jsonify({
'apiVersion': 'admission.k8s.io/v1',
'kind': 'AdmissionReview',
'response': {
'uid': admission_review['request']['uid'],
'allowed': True,
'patchType': 'JSONPatch',
'patch': patch_b64
}
})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8443, ssl_context='adhoc')
yaml
# webhook-config.yaml
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
name: label-webhook
webhooks:
- name: label-webhook.example.com
clientConfig:
url: https://webhook-service.default.svc:8443/mutate
rules:
- operations: ["CREATE"]
apiGroups: [""]
apiVersions: ["v1"]
resources: ["pods"]
admissionReviewVersions: ["v1"]
sideEffects: None
failurePolicy: Fail
Lab 5: Write a Validating Admission Webhook
Goal: Build a webhook that blocks privileged Pods.
python
# validating-webhook.py
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/validate', methods=['POST'])
def validate():
admission_review = request.get_json()
pod = admission_review['request']['object']
# Check for privileged containers
for container in pod['spec'].get('containers', []):
if container.get('securityContext', {}).get('privileged', False):
return jsonify({
'apiVersion': 'admission.k8s.io/v1',
'kind': 'AdmissionReview',
'response': {
'uid': admission_review['request']['uid'],
'allowed': False,
'status': {
'message': 'Privileged containers are not allowed'
}
}
})
return jsonify({
'apiVersion': 'admission.k8s.io/v1',
'kind': 'AdmissionReview',
'response': {
'uid': admission_review['request']['uid'],
'allowed': True
}
})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8443, ssl_context='adhoc')
yaml
# validating-webhook-config.yaml
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: privileged-blocker
webhooks:
- name: privileged-blocker.example.com
clientConfig:
url: https://webhook-service.default.svc:8443/validate
rules:
- operations: ["CREATE", "UPDATE"]
apiGroups: [""]
apiVersions: ["v1"]
resources: ["pods"]
admissionReviewVersions: ["v1"]
sideEffects: None
failurePolicy: Fail
Lab 6: Configure API Priority and Fairness
Goal: Create a custom FlowSchema.
yaml
# flow-schema.yaml
apiVersion: flowcontrol.apiserver.k8s.io/v1
kind: FlowSchema
metadata:
name: my-app-flow
spec:
priorityLevelConfiguration:
name: workload-high
matchingPrecedence: 1000
rules:
- resourceRules:
- resources: ["pods", "deployments"]
verbs: ["*"]
apiGroups: ["*"]
subjects:
- kind: ServiceAccount
serviceAccount:
name: my-app
namespace: production
---
apiVersion: flowcontrol.apiserver.k8s.io/v1
kind: PriorityLevelConfiguration
metadata:
name: workload-high
spec:
type: Limited
limited:
nominalConcurrencyShares: 50
limitResponse:
type: Queue
queuing:
queues: 16
queueLengthLimit: 50
handSize: 4
bash
kubectl apply -f flow-schema.yaml
# Check APF debug
kubectl get --raw /debug/api_priority_and_fairness/dump_priority_levels | jq
# Check queues
kubectl get --raw /debug/api_priority_and_fairness/dump_queues | jq
Lab 7: Simulate Control Plane Failure
Goal: Understand what happens when components fail.
bash
# Check current health
kubectl get nodes
kubectl get pods -A | head
# Simulate scheduler failure (if scheduler is a Deployment)
# For static pods, this is more complex
# Alternative: cordon all nodes
kubectl cordon --all
# Try to create a Pod
kubectl run stuck --image=nginx
kubectl get pod stuck
# Expected: Pending
# Uncordon
kubectl uncordon --all
kubectl delete pod stuck
# Simulate API server failure (in a test cluster)
# Stop the API server static pod
# sudo mv /etc/kubernetes/manifests/kube-apiserver.yaml /tmp/
# Wait 30 seconds
# kubectl get nodes
# Expected: Can't connect to server
# Restore
# sudo mv /tmp/kube-apiserver.yaml /etc/kubernetes/manifests/
Lab 8: Rotate Control Plane Certificates
Goal: Practice certificate rotation.
bash
# Check certificate expiry
kubeadm certs check-expiration
# Backup current certificates
sudo cp -r /etc/kubernetes/pki /etc/kubernetes/pki-backup
# Rotate all certificates
sudo kubeadm certs renew all
# Restart control plane components
sudo systemctl restart kubelet
# Verify
kubeadm certs check-expiration
# If something goes wrong, restore
# sudo rm -rf /etc/kubernetes/pki
# sudo cp -r /etc/kubernetes/pki-backup /etc/kubernetes/pki
# sudo systemctl restart kubelet
Lab 9: Set Up a 3-Node HA Control Plane
Goal: Build an HA control plane.
Prerequisites: 3 VMs.
bash
# On all nodes: install kubeadm, kubelet, kubectl
# On node 1 (first control plane)
sudo kubeadm init \
--control-plane-endpoint "k8s-api.example.com:6443" \
--upload-certs \
--pod-network-cidr=10.244.0.0/16
# Set up kubectl
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
# Save the join command for control planes
kubeadm token create --print-join-command
kubeadm init phase upload-certs --upload-certs
# On node 2 and node 3 (join as control planes)
sudo kubeadm join k8s-api.example.com:6443 \
--token <token> \
--discovery-token-ca-cert-hash sha256:<hash> \
--control-plane \
--certificate-key <cert-key>
# Verify HA
kubectl get nodes
kubectl get pods -n kube-system
# Should see 3 apiserver, 3 etcd, 3 scheduler, 3 controller-manager
# Check etcd cluster
kubectl exec -n kube-system etcd-node1 -- \
etcdctl member list --write-out=table
1:1 copy of the class Google Doc, code in code blocks.