bug in "with_items" or misunderstanding?

I have an inventory of hosts that defines “my_groups” hash:

my_groups:
group1=val1
group2=val2

Note - it’s a dynamic inventory which in fact produces valid JSON that works otherwise.

Then I try to use it to auto-populate groups via:

  • hosts: all
    tasks:
  • debug: var=hostvars[inventory_hostname][‘my_groups’].keys()
  • set_fact: my_group_list=“{{ hostvars[inventory_hostname][‘my_groups’].keys() }}”
    when: hostvars[inventory_hostname].my_groups is defined
  • debug: var=my_group_list
  • group_by: key={{ item }}_group
    with_items: hostvars[inventory_hostname].my_group_list
    when: my_group_list is defined

and receive lovely:

TASK: [group_by key={{ item }}_group] *****************************************
fatal: [moo.foo.com] => with_items expects a list or a set

even though last debug confirms that my_group_list is a proper list. When I used “my_group_list” instead - it acted as if “my_group_list” was the item to iterate over rather than variable:

TASK: [group_by key={{ item }}_group] *****************************************
<moo.foo.com> ESTABLISH CONNECTION FOR USER: root
created ‘group_by’ ActionModule: key=my_group_list_group
changed: [moo.foo.com] => (item=my_group_list) => {“changed”: true, “groups”: {“my_group_list_group”: [“moo.foo.com”, “bar.foo.com”]}, “item”: “my_group_list”}

Am I doing something wrong or am I facing a bug?

$ rpm -q redhat-release-server
redhat-release-server-6Server-6.6.0.2.el6.x86_64

$ rpm -q ansible

ansible-1.7.2-2.el6.noarch

try this:

  • group_by: key={{ item }}_group
    with_items: my_group_list|list

btw, this won’t do what you think it will, it gets evaluated for each iteration of with_items
when: my_group_list is defined

So I have modified my playbook (see https://gist.github.com/droopy4096/98864a10359f5cf27bab ), then played with “|list” but the results of it were that all of sudden it grabs JSON string and walks through that string one char at a time, resulting in:

changed: [undefined.host.com] => (item=[) => {“changed”: true, “groups”: {“[_group”: [“undefined.host.com”, “defined.host.com”]}, “item”: “[”}

fatal: [undefined.host.com] => error parsing argument string ‘key="_group’, try quoting the entire line.

If you look carefully at the gist - when I do the same “loop” “with_items” using “debug:” - everything works as expected, with “group_by” it gets screwed up in a major fashion.

I can invert the question and ask: given the existing dynamic inventory script, which can add some more “facts” per-host - I’d like to [re]create groups based on some of those “facts”. What is the best approach?

there is also a from_json filter, sometimes it is hard to see what is
json in a var as the output is normally 'jsonized'.