Difficulty: beginner
Estimated Time: 15 minutes

Since you are interested in using Ansible for lifecycle management of applications on Kubernetes, it will be beneficial to learn how to use the Ansible k8s (Kubernetes) module.

The k8s module allows you to:

  • Leverage your existing Kubernetes resource files (written in YAML)
  • Express Kubernetes lifecycle management actions in native Ansible.

One of the biggest benefits of using Ansible in conjunction with existing Kubernetes resource files is the ability to use Ansible's built-in Jinja templating engine to customize deployments by simply setting Ansible variables.


By the end of this scenario, you'll be able to use the Ansible k8s module to:

  • Create and remove Kubernetes resources
  • Reuse existing Kubernetes manifest files with Ansible

Ansible Kubernetes Module

Step 1 of 3

Running the k8s Ansible modules locally

For this example we will create and delete a namespace with the switch of an Ansible variable.


a. Modify tasks file example-role/tasks/main.yml to contain the Ansible shown below.
---
- name: set test namespace to {{ state }}
  k8s:
    api_version: v1
    kind: Namespace
    name: test
    state: "{{ state }}"
  ignore_errors: true

Notes:

  • You must have the target file open and the active tab in the edit pane in order for the 'Copy to Editor' button to work properly.
  • Set 'ignore_errors: true' so that attempting deletion of a nonexistent project doesn't error out.

b. Modify vars file example-role/defaults/main.yml, setting state: present by default.
---
state: present


c. Run playbook.yml, which will execute 'example-role'.

ansible-playbook -i myhosts playbook.yml


d. Check that the namespace test was created.

$ oc get projects

NAME              DISPLAY NAME   STATUS
default                          Active
kube-public                      Active
kube-system                      Active
openshift                        Active
openshift-infra                  Active
test                             Active