Lesson 4 / 10
Module 4Lesson 1⏱ 55 min study

Lesson 4: Kubernetes Architecture & the kubernetes.core Collection

Deconstruct Kubernetes API server internals, set up laboratory clusters, and use the kubernetes.core.k8s Ansible module to manage declarative resources.

✦ Key Architectural Takeaways
  • •The kube-apiserver is an active gateway processing authentication, RBAC authorization, and mutating/validating admission webhooks.
  • •etcd guarantees strong consistency across cluster state using Raft consensus, requiring fast SSD storage and low network latency.
  • •The kubernetes.core.k8s module communicates with Kubernetes clusters natively via the official Python Kubernetes client without invoking raw kubectl.
  • •Ansible handles embedded YAML manifests directly inline or loads external Jinja2 templates via the template lookup plugin.
  • •Clusters can be authenticated seamlessly using standard kubeconfig files, in-cluster ServiceAccount tokens, or cloud IAM credentials.

1. Inside the Kubernetes API Request Pipeline

Every operation in Kubernetes—whether executed via kubectl, the web dashboard, or an Ansible playbook—is a REST request sent to kube-apiserver.

The API server processes every incoming request through a rigorous multi-stage pipeline:

ARCHITECTURE DIAGRAMSYSTEM SCHEMATIC
Client (Ansible k8s module)
            | HTTPS Request (POST/PUT/GET)
            v
+-----------------------------------------------------------------+
|                        KUBE-APISERVER                           |
|                                                                 |
|  1. Authentication & Identification                             |
|     (Client TLS Certs, Bearer Tokens, OpenID Connect / OIDC)    |
|            |                                                    |
|  2. Authorization                                               |
|     (Role-Based Access Control - RBAC, Webhooks)                |
|            |                                                    |
|  3. Mutating Admission Controllers                             |
|     (Injects default values, sidecars, and resource defaults)   |
|            |                                                    |
|  4. Schema Validation                                           |
|     (Validates request body against OpenAPI spec)               |
|            |                                                    |
|  5. Validating Admission Controllers                           |
|     (Enforces security policies, quotas, and constraints)       |
|            |                                                    |
|  6. Persistence                                                 |
|     (Atomic write to etcd with optimistic locking)              |
+------------|----------------------------------------------------+
             v
+----------------------------+
| etcd Distributed Datastore |
+----------------------------+
§

2. Setting Up the Kubernetes Lab Environment

Before automating enterprise clusters, set up a local testing laboratory using lightweight tools:

  • Minikube: Spins up a single-node VM or containerized Kubernetes cluster, ideal for rapid testing.
  • Kind (Kubernetes in Docker): Runs multi-node clusters using Docker containers as nodes, widely used in CI/CD test automation.
  • k3s: A lightweight, certified Kubernetes distribution developed by Rancher, packaged as a single binary under 100 MB.
BASHSYSTEM SCHEMATIC
# Install and start Minikube with 4GB RAM and 2 CPUs
minikube start --memory=4096 --cpus=2 --driver=docker

# Verify cluster connectivity
kubectl cluster-info
kubectl get nodes
§

3. Configuring the kubernetes.core Collection

To automate Kubernetes with Ansible, install the official kubernetes.core collection and its Python SDK dependencies on the control machine:

BASHSYSTEM SCHEMATIC
# Install Python client libraries
pip install kubernetes PyYAML jsonpatch

# Install Ansible collection from Ansible Galaxy
ansible-galaxy collection install kubernetes.core

Ansible Verification Playbook

YAMLSYSTEM SCHEMATIC
---
- name: Verify Kubernetes Cluster Connectivity
  hosts: localhost
  connection: local
  tasks:
    - name: Query Cluster Version Information
      kubernetes.core.k8s_cluster_info:
      register: cluster_info

    - name: Display Kubernetes API Server Version
      ansible.builtin.debug:
        msg: "Connected to Kubernetes {{ cluster_info.version.server.kubernetes.gitVersion }}"
§

4. Native Ansible k8s Module vs. Shell kubectl

Why use Ansible's native kubernetes.core.k8s module instead of writing bash scripts wrapping kubectl?

CapabilityRaw kubectl in Shell ScriptAnsible kubernetes.core.k8s
IdempotencyPartial; complex diff parsing requiredFull; native diff evaluation
Error HandlingExit codes; fragile string greppingStructured JSON return objects
Dynamic TemplatingRequires external tools (envsubst, sed)Integrated Jinja2 templates & filters
Multi-Cluster OrchestrationHard to coordinate across contextsSimple inventory & loop abstractions
Drift DetectionManual inspectionAutomated --check / dry-run mode

Declarative Resource Creation via Ansible

YAMLSYSTEM SCHEMATIC
- name: Create Production Namespace with Metadata Labels
  kubernetes.core.k8s:
    state: present
    definition:
      apiVersion: v1
      kind: Namespace
      metadata:
        name: production-workloads
        labels:
          environment: production
          pod-security.kubernetes.io/enforce: restricted