how to generate an iterable on with_items with the attributes of a group's members ??

60 views
Skip to first unread message

Alejandro Comisario

unread,
May 13, 2016, 3:35:15 PM5/13/16
to Ansible Project
Hi guys, suppose i have this task like the one below, where i want all servers from the haproxy group to access a specific mysql database 

- name: ensure murano database user is present
mysql_user:
login_host: "{{ mysql_host }}"
login_password: "{{ mysql_root_password }}"
login_user: root
name: myuser
host: "{{ item }}"
password: "{{ myuser_mysql_password }}"
priv: myuserdb*:ALL
state: present
ignore_errors: true
with_items: groups['haproxy']
run_once: True

so, what i want an advice, is what would be the "Ansible" way to make, not only the "names" on the haproxy group to be able to run as an item, but also the fqdn of those names, something like (and im totally inventing here, since i dont know how to do it, its just to make a point)

- name: ensure murano database user is present
mysql_user:
login_host: "{{ mysql_host }}"
login_password: "{{ mysql_root_password }}"
login_user: root
name: myuser
host: "{{ item }}"
password: "{{ myuser_mysql_password }}"
priv: myuserdb*:ALL
state: present
ignore_errors: true
with_items
    - groups['haproxy']
    - hostvars.groups.haproxy['ansible_fqdn']
run_once: True

any help is more than appreciated
best

Johannes Kastl

unread,
May 13, 2016, 3:56:36 PM5/13/16
to ansible...@googlegroups.com
On 13.05.16 21:35 Alejandro Comisario wrote:

> with_items:
>
> - groups['haproxy']
>
> - hostvars.groups.haproxy['ansible_fqdn']

I think I read that joining two lists (thats what they are) is done
using a plus sign:

with_items: groups['haproxy'] + groups['foobar']


In your case you do not have a second list foobar, you want to iterate
over the first list but get another item, not the name that is in the
inventory (ansible_hostname) but something else. I do not know if that
is possible.

Johannes

signature.asc

Kai Stian Olstad

unread,
May 13, 2016, 5:25:02 PM5/13/16
to ansible...@googlegroups.com
On 13. mai 2016 21:35, Alejandro Comisario wrote:
> - name: ensure murano database user is present
> mysql_user:
> login_host: "{{ mysql_host }}"
> login_password: "{{ mysql_root_password }}"
> login_user: root
> name: myuser
> host: "{{ item }}"
> password: "{{ myuser_mysql_password }}"
> priv: myuserdb*:ALL
> state: present
> ignore_errors: true
> with_items:
>
> - groups['haproxy']
>
> - hostvars.groups.haproxy['ansible_fqdn']
> run_once: True

I don't think you can do this in one task since host: need to have to
different values.

So split in two tasks, one with

host: "{{ item }}"
with_items: groups['haproxy']

and the second with

host: "{{ hostvars[item]['ansible_fqdn'] }}"
with_items: groups['haproxy']

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