In the previous lesson you deployed the Aurora Store catalog API on api1 with Docker Compose. It works, but it has the limits of a single server: if api1 stops there's no catalog, having two copies would mean distributing containers by hand, and an upgrade means a brief outage. Kubernetes solves exactly that: you declare how many replicas you want, with which image and which checks, and the cluster takes care of maintaining it, restarting whatever fails and upgrading progressively. In this lesson you'll use the kubernetes.core collection so that Ansible talks to the Kubernetes API: you'll apply manifests generated from Jinja2 templates, wait for deployments to finish, install a component with Helm, query the cluster from Jinja and deploy the catalog:1.0.0 image you published to registry.aurora-store.example. You'll finish by comparing this approach with GitOps, so you know when each one fits best.

Contents

  1. From standalone containers to an orchestrator
  2. Decision: where Aurora's Kubernetes runs
  3. The kubernetes.core collection and its requirements
  4. Access to the cluster: kubeconfig, context and the k3s-lab host
  5. First steps: k8s_info and k8s with state: present/absent
  6. Manifests from templates: the aurora_catalog_k8s role
  7. Deploying, waiting and rolling back
  8. Helm from Ansible: Traefik as the Ingress controller
  9. Querying the cluster from Jinja: the kubernetes.core.k8s lookup
  10. Ansible operators (a brief mention)
  11. Ansible versus GitOps

  1. From standalone containers to an orchestrator

Review what you already know from Lesson 7.2 (AWX runs on k3s) with the minimal vocabulary you'll use here:

Object What it is Equivalent in Lesson 8.1
Namespace A space that groups and isolates objects The aurora-catalog Compose project
Pod One or more containers that run together A container
Deployment Keeps N replicas of a pod and manages their updates docker compose up + restart: unless-stopped, but with replicas and rolling updates
Service A stable name and address to reach the pods The Compose network (redis is resolved by name)
ConfigMap Configuration data that can be mounted as files or variables The mounted data/ directory
Ingress HTTP rules (host name → Service) applied by an Ingress controller The published port 8080:8080
Probe (readiness, liveness) Health checks used by Kubernetes The image's HEALTHCHECK

The big difference in model: with Docker, Ansible gave orders to a specific server over SSH. With Kubernetes, Ansible declares objects to the cluster API, and it's the cluster that decides which node runs each pod and that continuously corrects any drift. Ansible doesn't log into the nodes: it talks to an HTTPS API.

flowchart LR
    ANS[Ansible on your computer<br/>kubernetes.core] -->|HTTPS + kubeconfig| API[Kubernetes API<br/>k3s on awx1]
    API --> CTRL[Cluster controllers]
    CTRL -->|create and watch| PODS[Catalog API pods]
    PODS -->|pull| REG[(registry.aurora-store.example)]

  1. Decision: where Aurora's Kubernetes runs

The lab already has a cluster: the single-node k3s on awx1 (Lesson 7.2). The options:

Option Advantages Drawbacks
A. The same k3s on awx1, in an aurora namespace No new machines; the registry and internal names already work (CoreDNS and registries.yaml from Lesson 7.6) Mixes the automation platform with the applications
B. Another VM with its own k3s Real separation Another 2-4 GB of memory on your computer
C. A managed cloud cluster (EKS, AKS, GKE) Realistic Cost and credentials; outside the lab

Aurora chooses option A for the lab: an aurora namespace on the k3s on awx1. It's acceptable for learning, but in production they're kept separate:

  • Blast radius: a failure or an upgrade of the application cluster mustn't leave you without the tool you use to fix it (AWX).
  • Resources: the store's traffic peaks mustn't take CPU away from automation jobs, or vice versa.
  • Permissions: whoever deploys applications shouldn't have access to AWX's secrets.
  • Lifecycle: each cluster is upgraded at its own pace.

Everything you'll do works the same against any cluster: only the kubeconfig and the context change.

  1. The kubernetes.core collection and its requirements

3.1. Contents

Module or plugin What it's for
kubernetes.core.k8s Create, update (present, patched) or delete (absent) any object, from a dictionary, a file or a template
kubernetes.core.k8s_info Query objects (read-only), optionally waiting for a condition
kubernetes.core.k8s_scale Change the number of replicas
kubernetes.core.k8s_rollback Go back to a Deployment's previous revision (like kubectl rollout undo)
kubernetes.core.k8s_exec, k8s_log, k8s_cp Run commands in a pod, read its logs, copy files
kubernetes.core.k8s_drain, k8s_taint Node operations
kubernetes.core.helm, helm_repository, helm_info Manage Helm releases and repositories
kubernetes.core.k8s lookup Read cluster objects from a Jinja expression
kubernetes.core.kustomize lookup Generate manifests with Kustomize

There's no k8s_rollout module: waiting for a deployment to finish is done by k8s itself with wait: true, and rolling back by k8s_rollback. And if you come across examples using the kubernetes.core.k8s inventory plugin, they're old: it was removed in version 6.0.0 of the collection.

3.2. Adding it to the project

In collections/requirements.yml, after community.docker (the 6.x series asks for ansible-core >=2.16.0):

  # Kubernetes API and Helm (Lesson 8.2).
  - name: kubernetes.core
    version: "6.1.0"
ansible-galaxy collection install -r collections/requirements.yml

3.3. Where the modules run and what they need

The kubernetes.core modules run on the control node (on your computer, or inside the EE in AWX) and call the cluster API from there. That's why the requirements go on your computer, not on awx1:

Requirement What it's for How to install it
Python kubernetes library (24.2.0 or later) k8s* modules and lookup pipx inject ansible kubernetes (in the same environment as Ansible, Lesson 1.2)
PyYAML, jsonpatch Templates and patches PyYAML already comes with Ansible; pipx inject ansible jsonpatch if you use JSON patches
helm binary (series 3, 3.10 or later) helm* modules Your distribution's package or the official binary from helm.sh
A kubeconfig with access to the cluster Authentication Section 4
pipx inject ansible kubernetes
helm version --short

In AWX: the EE will need the kubernetes library (ansible-builder adds it automatically because the collection declares it), the helm binary and a credential of type OpenShift or Kubernetes API Bearer Token, which injects the API URL and a token into environment variables (K8S_AUTH_HOST, K8S_AUTH_API_KEY…) that the modules read on their own. For now Aurora launches these playbooks from the terminal; the new version of the EE will be built by continuous integration (Lesson 8.3).

  1. Access to the cluster: kubeconfig, context and the k3s-lab host

4.1. The lab kubeconfig

A kubeconfig is a YAML file with three lists (clusters, users and contexts) and a current context. A context ties together a cluster, a user and, optionally, a namespace. k3s generates an administrator one in /etc/rancher/k3s/k3s.yaml; copy it to your computer, outside the repository:

mkdir -p ~/.kube
ssh awx1 'sudo cat /etc/rancher/k3s/k3s.yaml' > ~/.kube/aurora-lab.yaml
chmod 600 ~/.kube/aurora-lab.yaml
# k3s points to 127.0.0.1: replace it with awx1's IP
sed -i 's#https://127.0.0.1:6443#https://192.168.56.30:6443#' ~/.kube/aurora-lab.yaml
# k3s calls the cluster, the user and the context "default": rename them
sed -i -E 's/^( *(name|cluster|user|current-context)): default$/\1: aurora-lab/' ~/.kube/aurora-lab.yaml
grep -E 'server:|current-context:' ~/.kube/aurora-lab.yaml
    server: https://192.168.56.30:6443
current-context: aurora-lab

The k3s server certificate includes the node's IP (--node-ip 192.168.56.30, Lesson 7.2), so the TLS connection is validated without disabling anything.

This file is the key to the entire cluster (cluster-admin user). Treat it like the Vault password: 0600 permissions, never in Git, never in a message. In production, Ansible would use a ServiceAccount with a Role limited to the aurora namespace (Exercise 3) and AWX would receive it as a credential.

4.2. Representing the cluster in the inventory

Which hosts does a play that talks to an API run against? You could use hosts: localhost, but then the deployment data (namespace, replicas, version) wouldn't have a natural place in the inventory. Aurora uses a very widespread pattern: a host that represents the cluster, with a local connection.

In inventory/hosts.yml, at the same level as aurora (not inside it: it isn't a store server and site.yml mustn't touch it):

all:
  children:
    aurora:                      # All of the store's servers
      children:
        # ... loadbalancers, webservers, dbservers, apiservers (unchanged)
    k8s_clusters:                # Kubernetes clusters (managed through their API, no SSH)
      hosts:
        k3s-lab:

inventory/host_vars/k3s-lab.yml:

---
# The k3s-lab "host" represents the lab k3s cluster (on awx1).
# The modules run on the control node and call the Kubernetes API.
ansible_connection: local
ansible_python_interpreter: "{{ ansible_playbook_python }}"

# API access (the file is outside the repository, Lesson 8.2)
k8s_kubeconfig: ~/.kube/aurora-lab.yaml
k8s_context: aurora-lab

# Address and HTTP port of the Ingress controller (Traefik, section 8)
k8s_ingress_address: 192.168.56.30
k8s_ingress_http_port: 30088
  • ansible_connection: local: the tasks run on your computer, without SSH.
  • ansible_python_interpreter: "{{ ansible_playbook_python }}": the same Python that runs Ansible, which is where you injected the kubernetes library. Without this line, Ansible might pick the system Python, which doesn't have it.

Since k3s-lab is in the inventory, it also reaches AWX with the project sync; it doesn't affect any existing template because none of them targets k8s_clusters.

  1. First steps: k8s_info and k8s with state: present/absent

A test playbook, demo-k8s.yml (you'll delete it):

---
- name: First steps with the Kubernetes API
  hosts: k8s_clusters
  gather_facts: false
  module_defaults:
    group/kubernetes.core.k8s:
      kubeconfig: "{{ k8s_kubeconfig }}"
      context: "{{ k8s_context }}"

  tasks:
    - name: Query the cluster nodes
      kubernetes.core.k8s_info:
        kind: Node
      register: demo_nodes

    - name: Show the nodes
      ansible.builtin.debug:
        msg: "{{ demo_nodes.resources | map(attribute='metadata.name') | list }}"

    - name: Create a test namespace
      kubernetes.core.k8s:
        state: present
        definition:
          apiVersion: v1
          kind: Namespace
          metadata:
            name: demo-aurora
            labels:
              app.kubernetes.io/managed-by: ansible

    - name: Delete the test namespace
      kubernetes.core.k8s:
        state: absent
        kind: Namespace
        name: demo-aurora
        wait: true
      tags: [never, cleanup]

What's new:

  • module_defaults with the group/kubernetes.core.k8s action group: sets kubeconfig and context for all the k8s* modules in the play (the collection also defines group/kubernetes.core.helm for the Helm ones). That way you don't repeat the connection in every task and, above all, roles don't need to know which cluster they connect to.
  • definition (alias of resource_definition): the object just as you'd write it in a YAML manifest.
  • state: present: creates the object if it doesn't exist; if it exists and differs, it updates it. state: absent: deletes it; to delete it, kind + name (+ namespace if applicable) is enough. With wait: true, it waits until it has really disappeared (a namespace takes a few seconds because it deletes all its contents).
ansible-playbook demo-k8s.yml
ansible-playbook demo-k8s.yml          # changed=0
ansible-playbook demo-k8s.yml --tags cleanup
rm demo-k8s.yml

The first task shows ["awx1"]. As in the rest of the course, the second run gives changed=0: the modules compare the desired object with the one in the cluster.

  1. Manifests from templates: the aurora_catalog_k8s role

6.1. Shared data

The products and the image name are the same on api1 and in Kubernetes. To avoid duplicating them, move them from inventory/group_vars/apiservers.yml to a new file, inventory/group_vars/all/catalog.yml:

---
# Catalog API data shared by api1 (Docker, Lesson 8.1)
# and by Kubernetes (Lesson 8.2).
aurora_catalog_image: registry.aurora-store.example:5000/aurora/catalog
aurora_catalog_products:
  - sku: CAF-ETI-250
    name: "Ethiopia Yirgacheffe 250 g"
    price: 12.50
  - sku: CAF-COL-250
    name: "Colombia Huila 250 g"
    price: 11.00
  - sku: CAF-GUA-1000
    name: "Guatemala Antigua 1 kg"
    price: 38.00

The inventory's apiservers.yml keeps docker_insecure_registries, docker_users, aurora_catalog_version, aurora_catalog_source and aurora_catalog_port. Check that nothing has changed on api1:

ansible-playbook apiservers.yml --check --diff      # changed=0

And create inventory/group_vars/k8s_clusters.yml with the new role's "wiring":

---
# aurora_catalog_k8s role parameters (catalog API on Kubernetes)
aurora_catalog_k8s_namespace: aurora
aurora_catalog_k8s_image: "{{ aurora_catalog_image }}"
aurora_catalog_k8s_version: "1.0.0"
aurora_catalog_k8s_replicas: 2
aurora_catalog_k8s_host: "catalog.{{ aurora_domain }}"
aurora_catalog_k8s_products: "{{ aurora_catalog_products }}"

Notice that the version in Kubernetes is independent of the one on api1 (aurora_catalog_version): you'll be able to upgrade one environment without touching the other.

6.2. The role

ansible-galaxy role init --init-path roles aurora_catalog_k8s
rm -rf roles/aurora_catalog_k8s/{files,handlers,tests,vars}

roles/aurora_catalog_k8s/defaults/main.yml:

---
aurora_catalog_k8s_namespace: default
aurora_catalog_k8s_version: "1.0.0"
aurora_catalog_k8s_replicas: 1
aurora_catalog_k8s_host: catalog.local
aurora_catalog_k8s_redis_image: docker.io/library/redis:7.4-alpine
aurora_catalog_k8s_products: []
aurora_catalog_k8s_wait_timeout: 180

aurora_catalog_k8s_image is mandatory (required: true in meta/argument_specs.yml). The role has no dependencies and does not know the kubeconfig: it receives it from the play through module_defaults.

6.3. The templates

The templates generate Kubernetes manifests in YAML. The k8s module renders them on the control node (they're looked up in the role's templates/, like those of ansible.builtin.template) and accepts several documents separated by --- in the same file.

roles/aurora_catalog_k8s/templates/redis.yaml.j2:

# {{ ansible_managed }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis
  namespace: {{ aurora_catalog_k8s_namespace }}
  labels:
    app.kubernetes.io/name: redis
    app.kubernetes.io/part-of: aurora-catalog
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: redis
  template:
    metadata:
      labels:
        app.kubernetes.io/name: redis
        app.kubernetes.io/part-of: aurora-catalog
    spec:
      containers:
        - name: redis
          image: {{ aurora_catalog_k8s_redis_image }}
          ports:
            - containerPort: 6379
          readinessProbe:
            exec:
              command: ["redis-cli", "ping"]
            periodSeconds: 10
          resources:
            requests: {cpu: 50m, memory: 64Mi}
            limits: {memory: 128Mi}
---
apiVersion: v1
kind: Service
metadata:
  name: redis
  namespace: {{ aurora_catalog_k8s_namespace }}
spec:
  selector:
    app.kubernetes.io/name: redis
  ports:
    - port: 6379
      targetPort: 6379

Here Redis is a cache: if its pod restarts, it starts empty and nothing bad happens. That's why it has no persistent storage (a PersistentVolumeClaim, which a database would need).

roles/aurora_catalog_k8s/templates/catalog.yaml.j2:

# {{ ansible_managed }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: catalog-products
  namespace: {{ aurora_catalog_k8s_namespace }}
data:
  products.json: |
    {{ aurora_catalog_k8s_products | to_nice_json(indent=2) | indent(4) }}
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: catalog
  namespace: {{ aurora_catalog_k8s_namespace }}
  labels:
    app.kubernetes.io/name: catalog
    app.kubernetes.io/part-of: aurora-catalog
    app.kubernetes.io/version: "{{ aurora_catalog_k8s_version }}"
spec:
  replicas: {{ aurora_catalog_k8s_replicas }}
  selector:
    matchLabels:
      app.kubernetes.io/name: catalog
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 0
      maxSurge: 1
  template:
    metadata:
      labels:
        app.kubernetes.io/name: catalog
        app.kubernetes.io/part-of: aurora-catalog
    spec:
      securityContext:
        runAsNonRoot: true
      containers:
        - name: catalog
          image: "{{ aurora_catalog_k8s_image }}:{{ aurora_catalog_k8s_version }}"
          ports:
            - containerPort: 8080
          env:
            - name: AURORA_REDIS_HOST
              value: redis
            - name: AURORA_CATALOG_DATA
              value: /data/products.json
          volumeMounts:
            - name: data
              mountPath: /data
              readOnly: true
          readinessProbe:
            httpGet: {path: /health, port: 8080}
            periodSeconds: 5
          livenessProbe:
            httpGet: {path: /health, port: 8080}
            initialDelaySeconds: 10
            periodSeconds: 20
          resources:
            requests: {cpu: 50m, memory: 64Mi}
            limits: {memory: 128Mi}
      volumes:
        - name: data
          configMap:
            name: catalog-products
---
apiVersion: v1
kind: Service
metadata:
  name: catalog
  namespace: {{ aurora_catalog_k8s_namespace }}
spec:
  selector:
    app.kubernetes.io/name: catalog
  ports:
    - port: 80
      targetPort: 8080
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: catalog
  namespace: {{ aurora_catalog_k8s_namespace }}
spec:
  ingressClassName: traefik
  rules:
    - host: {{ aurora_catalog_k8s_host }}
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: catalog
                port:
                  number: 80

What Jinja2 brings here:

  • Inventory values at the variable points (version, replicas, host name, namespace). The rest of the manifest is fixed and readable.
  • to_nice_json | indent(4) inserts the catalog as a block of text inside the ConfigMap: the indent filter adds 4 spaces to every line from the second one on, so the JSON stays inside the YAML | block.
  • maxUnavailable: 0 and maxSurge: 1: when updating, Kubernetes first starts a new pod and only removes an old one when the new one is ready (readiness). It's the in-cluster equivalent of the rolling deployment with the load balancer from Lesson 5.7, but without writing a single delegation task.
  • The same pattern from Lesson 8.1 repeats itself: the ConfigMap is mounted as a directory. When it changes, Kubernetes updates the mounted files (with a delay of up to a minute) without restarting pods; the API reads the file on every request.

Tip: if an application only read its configuration at startup, you'd add something like checksum/products: "{{ aurora_catalog_k8s_products | to_json | hash('sha256') }}" to spec.template.metadata.annotations. When the data changes, the annotation changes, and that forces a rolling update of the pods.

  1. Deploying, waiting and rolling back

7.1. The role tasks

roles/aurora_catalog_k8s/tasks/main.yml:

---
- name: Create the application namespace
  kubernetes.core.k8s:
    state: present
    definition:
      apiVersion: v1
      kind: Namespace
      metadata:
        name: "{{ aurora_catalog_k8s_namespace }}"
        labels:
          app.kubernetes.io/managed-by: ansible
  tags: [deploy, config]

- name: Deploy the Redis cache
  kubernetes.core.k8s:
    state: present
    apply: true
    template: redis.yaml.j2
    wait: true
    wait_timeout: "{{ aurora_catalog_k8s_wait_timeout }}"
  tags: [deploy, config]

- name: Deploy the catalog API
  tags: [deploy, config]
  block:
    - name: Apply the API manifests and wait for the update to finish
      kubernetes.core.k8s:
        state: present
        apply: true
        template: catalog.yaml.j2
        wait: true
        wait_timeout: "{{ aurora_catalog_k8s_wait_timeout }}"
  rescue:
    - name: Roll back to the previous revision of the deployment
      kubernetes.core.k8s_rollback:
        api_version: apps/v1
        kind: Deployment
        name: catalog
        namespace: "{{ aurora_catalog_k8s_namespace }}"

    - name: Stop the deployment
      ansible.builtin.fail:
        msg: >-
          Version {{ aurora_catalog_k8s_version }} never became ready
          and the deployment has been rolled back to the previous revision. Error: {{ ansible_failed_result.msg | default('unknown') }}
  • template: instead of definition:: the module renders the template with the play's variables and applies all its documents.
  • apply: true: compares with the last applied definition (like kubectl apply). That way, if you remove a field from the template, it also disappears from the cluster; with the default merge, removed fields would remain.
  • wait: true: on a Deployment, it waits for the update to finish (all new replicas available); on other objects, for them to exist. If wait_timeout runs out, the task fails.
  • The block/rescue reproduces the home page pattern from Lesson 5.5: if the new version never becomes ready, it goes back to the previous one with k8s_rollback and the playbook stops with a clear message. (On the first deployment there's no previous revision, and the rollback would fail too; that's acceptable.)

7.2. The playbook

Create kubernetes.yml at the root:

---
# Deploys the Aurora Store applications to the Kubernetes clusters.
# Requirements on the control node: kubernetes library, helm and the kubeconfig (Lesson 8.2).
- name: Deploy the Aurora Store applications to Kubernetes
  hosts: k8s_clusters
  gather_facts: false
  module_defaults:
    group/kubernetes.core.k8s:
      kubeconfig: "{{ k8s_kubeconfig }}"
      context: "{{ k8s_context }}"
    group/kubernetes.core.helm:
      kubeconfig: "{{ k8s_kubeconfig }}"
      context: "{{ k8s_context }}"

  roles:
    - aurora_catalog_k8s

  post_tasks:
    - name: Query the status of the API deployment
      kubernetes.core.k8s_info:
        kind: Deployment
        name: catalog
        namespace: "{{ aurora_catalog_k8s_namespace }}"
      register: aurora_catalog_k8s_deploy
      tags: always

    - name: Check that all replicas are available
      ansible.builtin.assert:
        that:
          - (aurora_catalog_k8s_deploy.resources[0].status.availableReplicas | default(0)) == aurora_catalog_k8s_replicas
        fail_msg: "Available replicas: {{ aurora_catalog_k8s_deploy.resources[0].status.availableReplicas | default(0) }} of {{ aurora_catalog_k8s_replicas }}"
        quiet: true
      tags: always

Do not add it to site.yml: site.yml configures servers over SSH; kubernetes.yml deploys applications to clusters and has other requirements. They're different cycles (in Lesson 9.1 you'll organize the repository's entry points).

ansible-playbook kubernetes.yml
ansible-playbook kubernetes.yml        # changed=0
ssh awx1 'sudo kubectl -n aurora get deploy,pods,svc,ingress'

The first run spends a few seconds on "Apply the API manifests…": that's the wait for the two pods to pull the image from the registry and pass the readiness probe. The Ingress doesn't have anyone to serve it yet (there's no controller); you'll solve that in section 8.

7.3. Scaling and triggering a rollback

Scaling without touching the template, as a one-off operation:

ansible k3s-lab -m kubernetes.core.k8s_scale \
  -a "kind=Deployment name=catalog namespace=aurora replicas=3 wait=true kubeconfig=~/.kube/aurora-lab.yaml context=aurora-lab"

Notice that an ad hoc command has no module_defaults: you pass the connection by hand. And since the template says replicas: 2, the next run of kubernetes.yml corrects the drift and goes back to 2. If you want 3 permanently, change aurora_catalog_k8s_replicas in the inventory.

Now simulate a bad release with a version that doesn't exist in the registry:

ansible-playbook kubernetes.yml -e aurora_catalog_k8s_version=9.9.9 -e aurora_catalog_k8s_wait_timeout=60

What happens, step by step:

  1. Kubernetes creates a pod with catalog:9.9.9, which ends up in ImagePullBackOff.
  2. Since maxUnavailable: 0, the two 1.0.0 pods keep serving: the store doesn't notice.
  3. After 60 seconds, wait fails; the rescue runs k8s_rollback (the Deployment goes back to the revision with 1.0.0 and the faulty pod disappears) and fail stops the playbook with the message.
ssh awx1 'sudo kubectl -n aurora rollout history deploy/catalog'
ansible-playbook kubernetes.yml        # leaves exactly what's in the inventory again: changed=0

Make a commit:

git add .
git commit -m "Catalog API on Kubernetes: k3s-lab host, aurora_catalog_k8s role and kubernetes.yml"

  1. Helm from Ansible: Traefik as the Ingress controller

8.1. Helm in two sentences

Helm is the Kubernetes package manager: a chart is a parameterizable template of manifests (in Go templates) that's installed as a release with a set of values. For complex third-party software (Ingress controllers, monitoring, databases with operators) it's the norm: you don't write their hundreds of lines of manifests, you just choose values.

Helm or Ansible templates? Use Helm for third-party software that's already distributed as a chart, and your own templates (or your own chart, if your organization already uses them) for your simple applications. Ansible orchestrates both.

8.2. Installing Traefik

In Lesson 7.2 you installed k3s with --disable traefik, so the cluster has no Ingress controller. You'll install Traefik with its official chart, managed from Ansible. Add to inventory/host_vars/k3s-lab.yml:

# Cluster Ingress controller (official Traefik chart).
# Example version: check the available ones with "helm search repo traefik/traefik --versions".
k8s_traefik_chart_version: "37.1.1"

And add a play before the applications play in kubernetes.yml (the cluster components go first):

- name: Install the cluster platform components
  hosts: k8s_clusters
  gather_facts: false
  module_defaults:
    group/kubernetes.core.helm:
      kubeconfig: "{{ k8s_kubeconfig }}"
      context: "{{ k8s_context }}"

  tasks:
    - name: Register the Traefik chart repository
      kubernetes.core.helm_repository:
        name: traefik
        repo_url: https://traefik.github.io/charts

    - name: Install the Traefik Ingress controller
      kubernetes.core.helm:
        name: traefik
        chart_ref: traefik/traefik
        chart_version: "{{ k8s_traefik_chart_version }}"
        release_namespace: traefik
        create_namespace: true
        update_repo_cache: true
        wait: true
        values:
          service:
            type: NodePort
          ports:
            web:
              nodePort: "{{ k8s_ingress_http_port | int }}"
          ingressClass:
            enabled: true
            isDefaultClass: true
  • helm_repository is equivalent to helm repo add (in your user's Helm configuration, on the control node).
  • helm is equivalent to helm upgrade --install: it installs or upgrades the traefik release in the traefik namespace with a pinned version of the chart (the same discipline as with collections). If the version and values don't change, it returns changed=false.
  • values: the chart values as a YAML dictionary, with Ansible variables. Here, a NodePort Service with the HTTP port on 30088 (port 80 on awx1 is taken by Gitea) and the traefik Ingress class, the one used by the API manifest.
  • wait: true: waits for the release resources to be ready.

Add the API name to /etc/hosts on your computer (on the same line as awx1):

192.168.56.30 awx1 git.aurora-store.example registry.aurora-store.example catalog.aurora-store.example

Run and test:

ansible-playbook kubernetes.yml
curl -s http://catalog.aurora-store.example:30088/health
curl -s http://catalog.aurora-store.example:30088/api/products
{"status": "ok", "version": "1.0.0", "redis": true}

For the playbook to check this itself, add the following at the end of the applications play's post_tasks (without depending on the /etc/hosts of whoever runs it, by sending the Host header):

    - name: Check the API through the Ingress
      ansible.builtin.uri:
        url: "http://{{ k8s_ingress_address }}:{{ k8s_ingress_http_port }}/health"
        headers:
          Host: "{{ aurora_catalog_k8s_host }}"
        return_content: true
      register: aurora_catalog_k8s_check
      until: aurora_catalog_k8s_check.status == 200
      retries: 10
      delay: 3
      failed_when: aurora_catalog_k8s_check.json.version | default('') != aurora_catalog_k8s_version
      tags: always

To uninstall a release: state: absent in the helm module. Make a commit ("Traefik with Helm from kubernetes.yml").

  1. Querying the cluster from Jinja: the kubernetes.core.k8s lookup

Sometimes you need a piece of cluster data inside an expression, without a k8s_info + register task. The kubernetes.core.k8s lookup returns API objects:

- name: Report the version running in the cluster
  ansible.builtin.debug:
    msg: >-
      {{ k8s_context }} is running the image
      {{ (query('kubernetes.core.k8s', kind='Deployment', namespace='aurora',
               resource_name='catalog', kubeconfig=k8s_kubeconfig, context=k8s_context)
          | first).spec.template.spec.containers[0].image }}
  tags: [never, info]

Remember what you learned in Lesson 5.3:

  • Lookups run on the control node (it makes no difference here, because the modules do too) and are re-evaluated on every use.
  • query() always returns a list; lookup() returns the bare object if there's only one.
  • Lookups do not receive module_defaults: you have to pass kubeconfig and context.

Add this task to the post_tasks of kubernetes.yml with the [never, info] tags (the same convention as "Show the nginx version") and try it with ansible-playbook kubernetes.yml --tags info.

A typical use of the lookup: deciding something based on the current state (for example, not running a migration if the target version is already running), or reading a value published by another component (a Service's IP, a ConfigMap value).

  1. Ansible operators (a brief mention)

You already know an operator: the AWX Operator you installed in Lesson 7.2. An operator is a controller that lives inside the cluster, watches objects of a custom type (the AWX CR) and acts continuously so that reality matches what's declared. The AWX Operator is written precisely with Ansible: the Operator SDK lets you build operators whose logic is roles and playbooks, run with kubernetes.core every time an object changes (remember that in Lesson 7.2 you saw that the operator's logs were a playbook's output).

kubernetes.yml playbook Ansible operator
Where it runs Outside the cluster, when someone launches it Inside the cluster, continuously
What triggers it A person, AWX or CI Changes to the objects it watches
What it's for Deploying and configuring Managing the lifecycle of complex software (backups, upgrades, recovery)

Writing operators is beyond the scope of this course; it's enough to know they exist and that, if you need to, your Ansible knowledge will help you do it.

  1. Ansible versus GitOps

GitOps is another deployment model for Kubernetes: an agent inside the cluster (Argo CD or Flux) watches a Git repository with the manifests and automatically applies any change, also continuously correcting drift. Nobody "launches" a deployment: a change is merged in Git.

Aspect Ansible (kubernetes.core) GitOps (Argo CD / Flux)
Model Push: someone runs the playbook Pull: the cluster agent applies what's in Git
Drift correction Only when it runs (e.g., scheduled in AWX) Continuous and automatic
Cluster credentials Outside the cluster (your computer, AWX, CI) They never leave the cluster
Orchestrating steps outside Kubernetes Its strong point: DNS, database, load balancers, VMs, notifications, approvals Limited to Kubernetes objects (with basic hooks)
Logic and conditions Complete (blocks, rescue, lookups, variables) Declarative; logic goes in Helm/Kustomize
State visibility Job output An interface showing what's in sync and what isn't
Installing the cluster itself and its base components Yes Needs someone to install the agent first

They aren't mutually exclusive. A common split in mature teams:

  • Ansible provisions and prepares the cluster (or the nodes), installs the base components (including Argo CD or Flux) and orchestrates processes that cross boundaries (migrating the database on db1, changing the load balancer, deploying to the cluster, sending notifications).
  • GitOps keeps the applications inside the cluster in sync with Git.

For Aurora, today, with a single application on Kubernetes and AWX already in place, Ansible is enough and consistent with the rest of the platform. If the number of applications and teams on Kubernetes grows, adopting GitOps for them would be the natural step.

Common Mistakes and Tips

  • Failed to import the required Python library (kubernetes): the library isn't in the Python that runs the module. Check ansible_python_interpreter on the k3s-lab host and repeat pipx inject ansible kubernetes.
  • Max retries exceeded ... 127.0.0.1:6443: you copied the k3s kubeconfig without changing the server address.
  • Failed to get client due to ... context: the k8s_context name doesn't match any context in the file.
  • The task with wait: true times out: almost always, the pods aren't starting. ssh awx1 'sudo kubectl -n aurora describe pod -l app.kubernetes.io/name=catalog' shows the reason (ImagePullBackOff, failed probe, insufficient memory…).
  • ImagePullBackOff with an image that does exist: the node can't resolve registry.aurora-store.example or doesn't have the HTTP mirror in /etc/rancher/k3s/registries.yaml (Lesson 7.6).
  • Broken YAML after rendering: an indentation error in the template (typical when inserting blocks). Render it separately to look at it: ansible k3s-lab -m ansible.builtin.debug -a "msg={{ lookup('ansible.builtin.template', 'roles/aurora_catalog_k8s/templates/catalog.yaml.j2') }}".
  • Manual changes with kubectl edit that disappear: with apply: true and periodic runs, the inventory rules. That's what you want; if a change has to stay, it goes into Git.
  • Tip: always pin the versions of Helm charts and images; without a version, helm installs the latest available one and a reinstall can change the software without anyone deciding to.

Exercises

Exercise 1: three permanent replicas

The team wants 3 replicas of the API in the cluster permanently. State which file you change, how you check it before applying and what order of pod creation and removal you'll see during the update with the template's strategy.

Exercise 2: tearing down the application

Write a kubernetes-delete.yml playbook that removes the catalog API from the cluster (without touching Traefik), asking for explicit confirmation with a -e confirm=aurora variable and failing if it isn't given.

Exercise 3: a user with fewer permissions

Describe which Kubernetes objects you'd create so that Ansible doesn't use the administrator kubeconfig but an identity that can only manage the aurora namespace. What could and couldn't kubernetes.yml do with it?

Solutions

Exercise 1. You change aurora_catalog_k8s_replicas: 3 in inventory/group_vars/k8s_clusters.yml. To check it beforehand: ansible-playbook kubernetes.yml --check --diff --limit k3s-lab shows the difference in spec.replicas. Changing only the replicas does not modify the pod template, so there's no rolling update: Kubernetes simply creates a third pod and doesn't remove any. (If you changed the version at the same time, with maxSurge: 1 and maxUnavailable: 0 a new pod would be created, Kubernetes would wait for it to be ready and then remove an old one, and so on.) The post_tasks check that there are 3 available replicas. Finish with a commit.

Exercise 2.

---
- name: Remove the catalog API from Kubernetes
  hosts: k8s_clusters
  gather_facts: false
  module_defaults:
    group/kubernetes.core.k8s:
      kubeconfig: "{{ k8s_kubeconfig }}"
      context: "{{ k8s_context }}"

  tasks:
    - name: Require explicit confirmation
      ansible.builtin.assert:
        that: confirm | default('') == aurora_catalog_k8s_namespace
        fail_msg: "To delete, add -e confirm={{ aurora_catalog_k8s_namespace }}"

    - name: Delete the application namespace and all its contents
      kubernetes.core.k8s:
        state: absent
        kind: Namespace
        name: "{{ aurora_catalog_k8s_namespace }}"
        wait: true
        wait_timeout: 300

Deleting the namespace cascades to its Deployments, Services, ConfigMaps and Ingress; Traefik is in its own namespace and isn't affected. If you only wanted to delete part of it, you'd use state: absent with template: catalog.yaml.j2 (the module deletes the objects the template describes).

Exercise 3. A ServiceAccount (for example ansible-deployer) in the aurora namespace; a Role in aurora with permissions on the resources the role uses (deployments, services, configmaps, ingresses, pods and pods/log for troubleshooting, with the verbs get, list, watch, create, update, patch, delete); a RoleBinding that binds the Role to the ServiceAccount; and a token for it (kubectl create token or a Secret of type kubernetes.io/service-account-token), which would go into a kubeconfig of its own or an AWX credential. With it, kubernetes.yml could deploy, scale and roll back the API, but not create the namespace (a cluster-scoped object: an administrator would create it once), install Traefik (it needs cluster objects such as IngressClass and RBAC permissions of its own) or query the nodes. That's why, in a real environment, the platform play runs with an administrator identity and the applications play with the limited one.

Conclusion

You've taken the catalog API from a server to an orchestrator. With the kubernetes.core collection, run on the control node with the kubernetes library and a kubeconfig outside the repository, you've represented the cluster in the inventory as the k3s-lab host of the k8s_clusters group, set the connection with module_defaults and the group/kubernetes.core.k8s and group/kubernetes.core.helm groups, and written the aurora_catalog_k8s role, which generates the manifests with Jinja2 templates (Redis, ConfigMap, a Deployment with zero-downtime rolling updates, Service and Ingress) and applies them with apply: true and wait: true, with automatic rollback through k8s_rollback. You've installed Traefik with helm_repository and helm, queried the cluster with the kubernetes.core.k8s lookup, and you know where Ansible operators fit and when GitOps is the better choice. The API runs in the aurora namespace of the k3s on awx1, a valid decision for the lab that's separated in production. But every deployment in this module still starts with someone typing a command: catalog-image.yml, kubernetes.yml, the AWX survey… In the next lesson, CI/CD with Ansible, you'll build a pipeline that checks the aurora-infra code on every change, builds and publishes the execution environment, and launches AWX deployments from a version tag in Git.

Ansible Course: From Beginner to Advanced

Module 1: Introduction to Ansible

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved