I'm trying to dynamically configure multiple NFS servers in my system by generating their /etc/exports files using Ansible. I'm hoping to be able to do this with a jinja2 template. It's the jinja2 template that I can't figure out based on my exports list.
I have the following variables defined in my nfs role:
site_nfs_servers: ['ansibletarget1', 'ansibletarget2']
exports:
- server: "ansibletarget1"
shares:
- path: "/my/first/share/path"
client: "*"
options: "rw,sync"
- path: "/my/second/share/path"
client: "*"
options: "rw,sync,root_squash"
- server: "ansibletarget2"
shares:
- path: "/another/shared/path/different/server"
client: "*"
options: "ro,sync"
I then have the following ansible play to generate the template:
- name: Generate the exports file.
template:
src: exports.j2
dest: /etc/exports
owner: root
group: root
mode: '0750'
My template currently looks like this:
{% for export in exports %}
{% if ansible_hostname in export.server %}
{% for share in shares %}
{{ share.path }} {{ share.client }} {{ share.options }}
{% endfor %}
{% endif %}
{% endfor %}
I don't think I'm anywhere near close to having the correct template structure. How on earth does one iterate through this list?
You are missing the reference to the
export
in your second loop.It would however be better to define the shares in host variables, as shown in the answer by Vladimir.
Create inventory
and put the shares into the host_vars
Create a simplified role for testing
Then, use the inventory group and the role in a playbook
Run the playbook and create the files
See Sample Ansible setup.
If you want to keep the shares in one object put the list into the groups_vars. To simplify the code, convert the list to a dictionary. You can use community.general.groupby_as_dict for example
gives
Then modify the template. This should create the same files as before.