How to ignore a variable if it's not defined

I have a var file with mount points that should be mounted. A common entry for /home goes on all servers. Some servers (e.g. web and perl) have their own set of mount points. I’m using Ansible pull and I build the element dynamically. So for webs, I reach in by using “aws_mounts[nfs_group]”, with “nfs_group” equal to “web_mounts” for web servers and “perl_mounts” for perl servers. Generating the variable isn’t an issue. However, some servers do not have “nfs_group” defined and the task will fail w/ a “variable is undefined error”

I tried the following:

tasks

  • name: Create fstab entries

mount:
fstype: nfs
state: mounted
opts: “{{ item.opts }}”
src: “{{ item.source }}”
name: “{{ item.dest }}”
when: item.source is defined
with_items:

  • “{{ aws_mounts[nfs_group] | default({}) }}”
  • “{{ aws_mounts.common }}”

vars/main.yml

This run the nfs_group through the default filter and default to empty list as the second default filter.
So this should work.

- "{{ aws_mounts[nfs_group | default(None)] | default() }}"