How to ignore a variable if it's not defined

25 views
Skip to first unread message

Sam Sen

unread,
Nov 2, 2016, 11:24:58 AM11/2/16
to Ansible Project
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
---
  aws_mounts:
    common:
      - { source: "/home",      dest: "/opt/ansible-home",                          opts: "bind" }
    web_mounts:
      - { source: "/tmp",      dest: "/opt/ansible-web",                          opts: "bind" }

Kai Stian Olstad

unread,
Nov 3, 2016, 10:51:17 AM11/3/16
to ansible...@googlegroups.com
On 02. nov. 2016 16:24, Sam Sen wrote:
> 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({}) }}"

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([]) }}"


--
Kai Stian Olstad
Reply all
Reply to author
Forward
0 new messages