Member-only story
Clean Up Your Kubernetes Deployments Using Ansible
Playbooks and templates make rolling out K8s objects a breeze

We’ve all heard nightmare horror stories of Kubernetes deployments gone awry. Trying to rollout a new service or deployment ends in catastrophe as pods begin crashing and requests start getting dropped. Avoiding chaos in Kubernetes is easier said than done.
Kubernetes is an incredibly complex, powerful beast. There are tons and tons of abstraction layers, each with its own lexicon of terms. Understanding every single moving piece of K8s is a huge undertaking. Not only that, but keeping everything neat and tidy is a totally separate chore.
Kubernetes runs on YAML. You deploy services and pods using YAML and the source of truth for most deployments comes down to the YAML running behind the scenes. Managing gigantic YAML files filled with different objects and repetitive statements is a headache. Sadly, there isn’t a great way to do this natively for Kubernetes. You can’t template repetitive YAML using just kubectl
. This is where Ansible comes in handy.
In this article, we’ll explore how you can use Ansible to manage K8s deployments. You can leverage Ansible’s powerful template engine to keep things tidy while being able to use existing inventory, group variables and much more for maximum flexibility.
Let’s see how this works.
Dependencies
In order to use the k8s
module in Ansible you’ll need to ensure you have a few things setup first:
- Install the Kubernetes Python module
- Install Kubectl and configure it to connect to your desired cluster (this assumes you already have a working, properly credentialed Kubernetes cluster)
Once you have these setup and kubectl
is working normally you can begin using the module.
Building the base playbook
Before we get started with the K8s specifics, we need to build a simple playbook. Let’s create a new base playbook now:
# playbook.yml
---
- name: deploy kubernetes objects
hosts: localhost
tasks:
- debug:
msg: "first task"