Issue when iterating over hostvars attribute

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,

Try

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

I’ve finally managed to get it working by using with_items instead of loop
Thanks anyway Vlad,
Cheers