Issue when iterating over hostvars attribute

17 views
Skip to first unread message

Jorge Rúa

unread,
Jul 11, 2023, 3:42:58 PM7/11/23
to ansible...@googlegroups.com
Hey folks,

Not sure if I'm too tired today or what but I'm stuck on a relatively easy task. Here's the thing:
I have a task which runs a command for each host in the inventory. For each host, I will need to run this command as many times as elements in  "{{ hostvars[inventory_hostname]['hostgroups'] }}". However I'm getting the list as literal on each loop, which is not what I want. 

Here's the task and the output:

- name: 'Adding servers to each respective hostgroup'
  ansible.builtin.debug:
    msg: 'echo command-hostgroup addhostgroup {{ inventory_hostname }} {{ item }}'
  register: '__r_tb_hostgroups_add'
  changed_when: false
  loop:
    - "{{ hostvars[inventory_hostname]['hostgroups'] }}"

TASK [ Adding servers to each respective hostgroup] *************************************************************************************************
ok: [aaa -> localhost] => (item=['foobar_service_web', 'foobar_service_unstable']) => {
    "msg": "echo command-hostgroup addhostgroup aaa ['foobar_service_web', 'foobar_service_unstable']"
}
ok: [bbb -> localhost] => (item=['foobar_service_db', 'foobar_service_testing']) => {
    "msg": "echo command-hostgroup addhostgroup bbb ['foobar_service_db', 'foobar_service_testing']"
}
ok: [ccc -> localhost] => (item=['foobar_service_app', 'foobar_service_stable']) => {
    "msg": "echo command-hostgroup addhostgroup ccc ['foobar_service_app', 'foobar_service_stable']"
}

Any thoughts? 

Thanks,


Vladimir Botka

unread,
Jul 11, 2023, 4:12:11 PM7/11/23
to Jorge Rúa, ansible...@googlegroups.com
On Tue, 11 Jul 2023 20:42:30 +0100
Jorge Rúa <jruar...@gmail.com> wrote:

> loop:
> - "{{ hostvars[inventory_hostname]['hostgroups'] }}"
>
> TASK [ Adding servers to each respective hostgroup]
> *************************************************************************************************
> ok: [aaa -> localhost] => (item=['foobar_service_web',
> 'foobar_service_unstable']) => {

Try

- debug:
msg: "echo {{ inventory_hostname }} {{ item }}"
loop: "{{ hostgroups|from_yaml }}"

--
Vladimir Botka

Jorge Rúa

unread,
Jul 11, 2023, 5:38:40 PM7/11/23
to Vladimir Botka, ansible...@googlegroups.com
I've finally managed to get it working by using with_items instead of loop
Thanks anyway Vlad,
Cheers
Reply all
Reply to author
Forward
0 new messages