Skip to main content
Ansible Configuration
CHAPTER 12

Ansible and Kubernetes

Updated: May 15, 2026
30 min read

# CHAPTER 12

Ansible and Kubernetes

1. Introduction

Kubernetes (K8s) is the undisputed king of container orchestration. It handles the auto-scaling, load balancing, and self-healing of massive container fleets. However, interacting with Kubernetes usually requires writing hundreds of lines of complex, raw YAML manifest files and executing them manually via kubectl. Ansible can dramatically simplify this process. By integrating Ansible with Kubernetes, we can apply the power of Jinja2 templating, dynamic variables, and encrypted Vault secrets directly to our Kubernetes deployments. In this chapter, we will explore the kubernetes.core collection and learn how Ansible acts as the ultimate wrapper for K8s orchestration.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the relationship between Ansible automation and Kubernetes orchestration.
  • Install and configure the kubernetes.core Ansible collection.
  • Deploy native Kubernetes resources (Namespaces, Deployments, Services) using Ansible modules.
  • Utilize Jinja2 templates to dynamically generate K8s manifests.
  • Understand the authentication mechanisms required for Ansible to speak to the K8s API.

3. Beginner-Friendly Explanation

Imagine Kubernetes is the conductor of an orchestra.
  • Raw Kubernetes (kubectl): You (the composer) hand the conductor a stack of 50 handwritten sheet music pages (YAML files). If you want to change the song from a major to a minor key, you have to manually erase and rewrite all 50 pages.
  • Ansible + Kubernetes: You write one smart sheet of music with a variable: {{ key = "minor" }}. You hand it to Ansible. Ansible instantly generates all 50 pages perfectly in the minor key and hands them to the conductor.

Ansible doesn't replace Kubernetes; it makes commanding Kubernetes infinitely faster and dynamic.

4. Setting up the K8s Environment

To talk to Kubernetes, your Ansible Control Node needs the kubernetes Python library and the official collection.

*On your Control Node:*

bash
12
pip install kubernetes
ansible-galaxy collection install kubernetes.core

Ansible authenticates to your K8s cluster exactly the same way you do: it looks for the ~/.kube/config file on the Control Node.

5. Deploying Kubernetes Resources

Instead of writing a raw Kubernetes YAML file, we use the k8s module inside our Ansible playbook.
yaml
123456789101112131415161718192021222324252627282930313233343536373839
---
- name: Deploy Nginx to Kubernetes
  hosts: localhost # We run this on the Control Node, not a remote server!
  
  tasks:
    # 1. Create a logical workspace (Namespace)
    - name: Ensure namespace exists
      kubernetes.core.k8s:
        name: frontend-app
        api_version: v1
        kind: Namespace
        state: present

    # 2. Deploy the containers
    - name: Deploy Nginx Pods
      kubernetes.core.k8s:
        state: present
        definition:
          # This is raw K8s YAML embedded inside Ansible!
          apiVersion: apps/v1
          kind: Deployment
          metadata:
            name: nginx-deployment
            namespace: frontend-app
          spec:
            replicas: 3
            selector:
              matchLabels:
                app: nginx
            template:
              metadata:
                labels:
                  app: nginx
              spec:
                containers:
                - name: nginx
                  image: nginx:1.21.6
                  ports:
                  - containerPort: 80

6. Mini Project: Dynamic K8s Deployment with Templates

Embedding raw K8s YAML inside Ansible (like above) is fine, but the true power is separating them. We can write a Kubernetes .yml.j2 template and use Ansible variables to dynamically scale it!

Step-by-Step Architecture Concept: 1. The Template (templates/deployment.yml.j2)

yaml
1234567891011
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ app_name }}
spec:
  replicas: {{ container_count }} # Dynamic scaling!
  template:
    spec:
      containers:
      - name: {{ app_name }}
        image: "{{ image_name }}:{{ image_version }}"

2. The Playbook (deploy.yml)

yaml
123456789101112131415
---
- name: Dynamic Kubernetes Orchestration
  hosts: localhost
  vars:
    app_name: "payment-service"
    container_count: 5
    image_name: "mycompany/payment"
    image_version: "v2.0"

  tasks:
    - name: Apply dynamic K8s template
      kubernetes.core.k8s:
        state: present
        # Ansible compiles the Jinja2 template into raw K8s YAML and deploys it!
        template: 'templates/deployment.yml.j2'

*If you need to update the app to v2.1 and scale up to 10 containers, you just change the variables in the playbook. You don't touch the K8s manifest!*

7. Real-World Scenarios

A company managed 20 different microservices in Kubernetes. Every microservice required its own Deployment, Service, and ConfigMap YAML files. That meant maintaining 60 different raw YAML files. Whenever a global security standard changed, the team had to manually edit 60 files. The DevOps team migrated to Ansible. They wrote *one* master Jinja2 template. Their Ansible Playbook simply looped through a list of the 20 microservices, dynamically generating and applying the K8s manifests. Modifying the global security standard now requires changing exactly one template file.

8. Best Practices

  • hosts: localhost: Notice in the examples we used hosts: localhost. When deploying to Kubernetes, Ansible does not SSH into the worker nodes. Ansible runs the python scripts locally on the Control Node, which makes HTTP API calls directly to the Kubernetes API server.

9. Security Recommendations

  • Kubeconfig Security: Since Ansible relies on the ~/.kube/config file to authenticate, whoever has access to the Ansible Control Node has administrator access to the entire Kubernetes cluster. In a CI/CD pipeline, you must inject the Kubeconfig file dynamically as an encrypted secret, use it for the deployment, and immediately delete it.

10. Troubleshooting Tips

  • Python Module Missing: The most common error is Failed to import the required Python library (openshift or kubernetes). Ensure you ran pip install kubernetes on the machine executing the playbook. If using a virtual environment, ensure Ansible is using the correct python interpreter.

11. Exercises

  1. 1. Explain the architectural difference in how Ansible communicates with a standard Linux server versus how it communicates with a Kubernetes Cluster.
  1. 2. What is the operational advantage of using the template parameter in the k8s module over embedding the resource definition directly in the playbook?

12. FAQs

Q: Should I use Ansible or Helm for Kubernetes deployments? A: Helm is the industry standard package manager for Kubernetes and is specifically built for complex K8s deployments. However, Ansible is a general-purpose orchestrator. If you need to spin up an AWS RDS Database, create a DNS record, *and* deploy the application to Kubernetes in a single automated pipeline, Ansible is vastly superior. (Ansible also has a kubernetes.core.helm module so you can use both!).

13. Interview Questions

  • Q: Describe the integration architecture between Ansible and Kubernetes. How does leveraging Jinja2 templating within Ansible playbooks resolve the rigidity inherent in native Kubernetes manifest files?
  • Q: An engineering team is manually running kubectl apply across multiple environments. Propose an automated Ansible workflow to standardize these deployments, specifically addressing parameterization and credential management.

14. Summary

In Chapter 12, we elevated Ansible to the highest tier of cloud orchestration. We demonstrated that Ansible is not constrained to legacy SSH administration; it seamlessly integrates with modern API-driven platforms like Kubernetes. By utilizing the kubernetes.core.k8s module, we translated raw, static YAML manifests into dynamic, intelligent templates via Jinja2. We empowered our playbooks to dynamically scale deployments and inject variables, transforming the management of massive container fleets into a standardized, parameterized, and highly automated DevOps pipeline.

15. Next Chapter Recommendation

Ansible can configure the servers and deploy the containers. But who creates the actual, physical cloud servers in the first place? Proceed to Chapter 13: Cloud Automation with Ansible.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·