Build strings dynamically in Ansible inventory

I have a question when I used the Ansible role NFS.

NFS Role: https://github.com/geerlingguy/ansible-role-nfs

My situation is this: we will create a list of virtual machines that are NFS clients. And we need access control on the NFS server. Thus, we set the list named nfs_exports to Ansible inventory according to the role above.

Some of the VMs will be terminated and decommissioned after full workload. And we will restart the playbook, including the NFS role, to update the settings of the NFS server. Thus, there is a host group "client_group", and the number of hosts is a variable.

If there is one virtual machine, the nfs_exports list will be:

nfs_clients: "{{ groups['client_group'] }}"
nfs_exports:
- "{{ nfs_dirs[0] }}  {{ nfs_clients[0] }}(rw)"
- "{{ nfs_dirs[1] }}  {{ nfs_clients[0] }}(ro)"

And if there are two virtual machines,

nfs_clients: "{{ groups['client_group'] }}"
nfs_exports:
- "{{ nfs_dirs[0] }}  {{ nfs_clients[0] }}(rw) {{ nfs_clients[1] }}(rw)"
- "{{ nfs_dirs[1] }}  {{ nfs_clients[0] }}(ro) {{ nfs_clients[1] }}(ro)"

And if there are three virtual machines,

nfs_clients: "{{ groups['client_group'] }}"
nfs_exports:
- "{{ nfs_dirs[0] }}  {{ nfs_clients[0] }}(rw) {{ nfs_clients[1] }}(rw) {{ nfs_clients[2] }}(rw)"
- "{{ nfs_dirs[1] }}  {{ nfs_clients[0] }}(ro) {{ nfs_clients[1] }}(ro) {{ nfs_clients[2] }}(ro)"

This is not good in our case. Since every time the number of virtual machines changes, I need to manually change "nfs_exports".

I need to dynamically build the strings in the nfs_exports list. Therefore, if there is one virtual machine, there will be only one client in "nfs_exports". If there are multiple virtual machines, all virtual machines should automatically be included in "nfs_exports".

Can someone provide a solution for building strings in 'nfs_exports' instead of manually changing nfs_exports when changing client_group?

+4
source share
1 answer

Here you go:

- hosts: localhost
  gather_facts: no
  vars:
    nfs_clients:
      - server1
      - server2
      - server3
    nfs_dirs:
      - path1
      - path2
    nfs_exports:
      - "{{ nfs_dirs[0] }} {{ ' '.join(nfs_clients | map('regex_replace','$','(rw)')) }}"
      - "{{ nfs_dirs[1] }} {{ ' '.join(nfs_clients | map('regex_replace','$','(ro)')) }}"
  tasks:
    - debug: var=nfs_exports

:

ok: [localhost] => {
    "nfs_exports": [
        "path1 server1(rw) server2(rw) server3(rw)",
        "path2 server1(ro) server2(ro) server3(ro)"
    ]
}
+4

Source: https://habr.com/ru/post/1666887/


All Articles