4

I have a question when I was using Ansible role NFS.

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

My situation is like this: We will create a list of VMs which are NFS clients. And we need access control on NFS server. So, we set a list named 'nfs_exports' in Ansible inventory according to the role above.

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

If there is one VM, 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 VMs,

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 VMs,

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. Because each time the quantity of the VMs changed, I need to change the 'nfs_exports' manually.

I need to build the strings in the list 'nfs_exports' dynamically. So if there is one VM, there will be only one client in 'nfs_exports'. If there are several VMs, all the VMs should be included in 'nfs_exports' automatically.

Can anyone provide a solution about building strings in 'nfs_exports', not to change 'nfs_exports' manually when 'client_group' changes?

Hao Zhang
  • 41
  • 3

1 Answers1

4

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

Output:

ok: [localhost] => {
    "nfs_exports": [
        "path1 server1(rw) server2(rw) server3(rw)",
        "path2 server1(ro) server2(ro) server3(ro)"
    ]
}
Konstantin Suvorov
  • 55,178
  • 7
  • 115
  • 152