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
- From standalone containers to an orchestrator
- Decision: where Aurora's Kubernetes runs
- The
kubernetes.corecollection and its requirements - Access to the cluster:
kubeconfig, context and thek3s-labhost - First steps:
k8s_infoandk8swithstate: present/absent - Manifests from templates: the
aurora_catalog_k8srole - Deploying, waiting and rolling back
- Helm from Ansible: Traefik as the Ingress controller
- Querying the cluster from Jinja: the
kubernetes.core.k8slookup - Ansible operators (a brief mention)
- Ansible versus GitOps
- 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)]
- 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.
- The
kubernetes.core collection and its requirements
kubernetes.core collection and its requirements3.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):
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 |
In AWX: the EE will need the
kuberneteslibrary (ansible-builderadds it automatically because the collection declares it), thehelmbinary 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).
- Access to the cluster:
kubeconfig, context and the k3s-lab host
kubeconfig, context and the k3s-lab host4.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.yamlThe 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-adminuser). Treat it like the Vault password:0600permissions, never in Git, never in a message. In production, Ansible would use a ServiceAccount with a Role limited to theauroranamespace (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: 30088ansible_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 thekuberneteslibrary. 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.
- First steps:
k8s_info and k8s with state: present/absent
k8s_info and k8s with state: present/absentA 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_defaultswith thegroup/kubernetes.core.k8saction group: setskubeconfigandcontextfor all thek8s*modules in the play (the collection also definesgroup/kubernetes.core.helmfor 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 ofresource_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(+namespaceif applicable) is enough. Withwait: 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.ymlThe 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.
- Manifests from templates: the
aurora_catalog_k8s role
aurora_catalog_k8s role6.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.00The 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:
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: 180aurora_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: 6379Here 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: 80What 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: theindentfilter adds 4 spaces to every line from the second one on, so the JSON stays inside the YAML|block.maxUnavailable: 0andmaxSurge: 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') }}"tospec.template.metadata.annotations. When the data changes, the annotation changes, and that forces a rolling update of the pods.
- 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 ofdefinition:: the module renders the template with the play's variables and applies all its documents.apply: true: compares with the last applied definition (likekubectl 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. Ifwait_timeoutruns out, the task fails.- The
block/rescuereproduces the home page pattern from Lesson 5.5: if the new version never becomes ready, it goes back to the previous one withk8s_rollbackand 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: alwaysDo 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=60What happens, step by step:
- Kubernetes creates a pod with
catalog:9.9.9, which ends up inImagePullBackOff. - Since
maxUnavailable: 0, the two 1.0.0 pods keep serving: the store doesn't notice. - After 60 seconds,
waitfails; therescuerunsk8s_rollback(the Deployment goes back to the revision with 1.0.0 and the faulty pod disappears) andfailstops 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=0Make a commit:
git add .
git commit -m "Catalog API on Kubernetes: k3s-lab host, aurora_catalog_k8s role and kubernetes.yml"
- 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: truehelm_repositoryis equivalent tohelm repo add(in your user's Helm configuration, on the control node).helmis equivalent tohelm upgrade --install: it installs or upgrades thetraefikrelease in thetraefiknamespace with a pinned version of the chart (the same discipline as with collections). If the version and values don't change, it returnschanged=false.values: the chart values as a YAML dictionary, with Ansible variables. Here, aNodePortService with the HTTP port on 30088 (port 80 onawx1is taken by Gitea) and thetraefikIngress 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.exampleRun and test:
ansible-playbook kubernetes.yml
curl -s http://catalog.aurora-store.example:30088/health
curl -s http://catalog.aurora-store.example:30088/api/productsFor 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: alwaysTo uninstall a release: state: absent in the helm module. Make a commit ("Traefik with Helm from kubernetes.yml").
- Querying the cluster from Jinja: the
kubernetes.core.k8s lookup
kubernetes.core.k8s lookupSometimes 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 passkubeconfigandcontext.
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).
- 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.
- 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. Checkansible_python_interpreteron thek3s-labhost and repeatpipx inject ansible kubernetes.Max retries exceeded ... 127.0.0.1:6443: you copied the k3skubeconfigwithout changing the server address.Failed to get client due to ... context: thek8s_contextname doesn't match any context in the file.- The task with
wait: truetimes 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…). ImagePullBackOffwith an image that does exist: the node can't resolveregistry.aurora-store.exampleor 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 editthat disappear: withapply: trueand 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,
helminstalls 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: 300Deleting 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
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
