Ansible K8s Module - Apply Multiple Yaml Files at Once

6/17/2021

Writing an Ansible playbook where we pull projects from GIT repos and thereafter apply all pulled yamls to a Kubernetes cluster.

I see only an example to apply single yaml files to a Kubernetes cluster but not multiple ones at once. e.g.:

- name: Apply metrics-server manifest to the cluster.
  community.kubernetes.k8s:
    state: present
    src: ~/metrics-server.yaml

Is there any way of applying multiple yaml files? Something like:

- name: Apply Services to the cluster.
  community.kubernetes.k8s:
    state: present
    src: ~/svc-*.yaml

Or:

- name: Apply Ingresses to the cluster.
  community.kubernetes.k8s:
    state: present
    dir: ~/ing/

Is there maybe another Ansible K8s module I should be looking at maybe?

Or should we just run kubectl commands directly in Ansible tasks. e.g.:

- name: Apply Ingresses to the cluster.
  command: kubectl apply -f ~/ing/*.yaml

What is the best way to achieve this using Ansible?

-- Going Bananas
ansible
kubernetes

1 Answer

6/17/2021

You can use k8s Ansible module along with 'with_fileglob' recursive pattern. Below code should work for your requirement.

- name: Apply K8s resources
        k8s:
          definition: "{{ lookup('template', '{{ item }}') | from_yaml }}"
        with_fileglob:
          - "~/ing/*.yaml"
-- Kiruba
Source: StackOverflow