How to Apply Multiple Yaml Files at Once on Kubernetes K8s or OpenShift OCP with Ansible?
I'm going to show you a live Playbook and some simple Ansible code.
I'm Luca Berton and welcome to today's episode of Ansible Pilot.
Ansible Apply Multiple YAML Files at Once on K8s or OCP
kubernetes.core.k8s
- Manage Kubernetes (K8s) objects
ansible.builtin.fileglob
- list files matching a pattern
Let's talk about the Ansible module k8s and the Ansible lookup plugin fileglob.
The full name is kubernetes.core.k8s, which means that is part of the collection of modules of Ansible to interact with Kubernetes and Red Hat OpenShift clusters.
It manages Kubernetes (K8s) objects.
Plugins are a way to expand the Ansible functionality. With lookup plugins specifically, you can load variables or templates with information from external sources.
The full name is ansible.builtin.fileglob, it's part of ansible-core and is included in all Ansible installations.
The purpose of the lookup plugin is to list files matching a pattern.
k8s module parameters
namestring - object name
namespacestring - namespace
statestring - present/absent/patched
definitionstring - YAML definition
srcpath - path for YAML definition
There is a long list of parameters of the k8s module. Let me summarize the most used.
Most of the parameters are very generic and allow you to combine them for many use-cases.
The name and namespace specify object name and the object namespace.
The api_version parameter specifies the Kubernetes API version, the default is "v1" for version 1.
The state like for other modules determines if an object should be created - present option, update - patched option, or deleted - absent option.
The definition parameter allows you to provide a valid YAML definition (string, list, or dict) for an object when creating or updating.
If you prefer to specify a file for the YAML definition, the src parameter provides a path to a file containing a valid YAML definition of an object or objects to be created or updated.
Links
- [kubernetes.core.k8s](https://docs.ansible.com/ansible/latest/collections/kubernetes/core/k8s_module.html)
- [ansible.builtin.fileglob](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/fileglob_lookup.html)
- [Kubernetes best practices: Organizing with Namespaces](https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-organizing-with-namespaces)
## Playbook
How to Apply Multiple Yaml Files at Once on Kubernetes K8s or OpenShift OCP with Ansible Playbook.
I'm going to combine the k8s module with the fileglob lookup plugin to be able to process multiple Yaml files.
code
- multiple_yaml.yml
```yaml
---
- name: k8s Playbook
hosts: localhost
gather_facts: false
connection: local
tasks:
- name: Apply K8s resources
kubernetes.core.k8s:
definition: "{{ lookup('template', '{{ item }}') | from_yaml }}