Passing dynamic variable into a role

37 views
Skip to first unread message

Sam Sen

unread,
Jul 25, 2016, 4:32:00 PM7/25/16
to Ansible Project
For each of our servers (webs and perls), we have different mount points for each type of servers. So for web servers, I want to use the entries for "web_mounts" and perls would be "perl_mounts." 

If I hard code "web_mounts" into the "with_items," it works fine. Otherwise, it tells me "nfs_group" is undefined.


# Top Level

roles:
 - { role: webs, nfs_group: "web_mounts" }

# roles/nfs_mounts/vars/main.yml
---
web_mounts:
 - { source: "nfs.local:/nfs/web1, dest: "/web1", opts: "rw,noatime" }
 - { source: "nfs.local:/nfs/web2, dest: "/web2", opts: "rw,noatime" }

perl_mounts:
- { source: "nfs.local:/nfs/perl1, dest: "/web1", opts: "rw,noatime" }
- { source: "nfs.local:/nfs/perl2, dest: "/web2", opts: "rw,noatime" }
# roles/nfs_mounts/tasks/main.yml
- name: Create fstab entries
  mount: fstab=nfs state=present opts="{{ item.opts }}" src="{{ item.source }}" name="{{ item.dest }}"
  with_items: "{{ nfs_group }}"

Artyom Aleksandrov

unread,
Aug 8, 2016, 8:54:35 AM8/8/16
to Ansible Project
Hello,

Here you pass to Ansible that you nfs_group is 'web_mounts' (sting).

roles:
 - { role: webs, nfs_group: "web_mounts" }

Pass a variable


roles:
 - { role: webs, nfs_group: "{{ web_mounts }}" }


But I suggest you to change a way.
Divide you hosts on groups: Web_Hosts, Perl_Hosts and specify the same variable name in group_vars directory on inventory file but with different value based on you needs for specific group.

Then you can use one variable name for any number of groups.

Example:

 
# group_vars/WEB_Hosts

---
nfs_mounts:
 - { source: "nfs.local:/nfs/web1, dest: "/web1", opts: "rw,noatime" }
# group_vars/Perl_Hosts

---
nfs_mounts:
 - { source: "nfs.local:/nfs/perl, dest: "/perl", opts: "rw,noatime" }

# roles/nfs_mounts/tasks/main.yml
- name: Create fstab entries
  mount: fstab=nfs state=present opts="{{ item.opts }}" src="{{ item.source }}" name="{{ item.dest }}"
  with_items: "{{ nfs_mounts }}"

In this case you can even set specific nfs_mounts variable for particular host via host_vars
Reply all
Reply to author
Forward
0 new messages