lookup module cannot return dict, and gives confusing error

I am creating a Lookup module that should return a dict.

This seems to be not possible:

fatal: [node-01-1]: FAILED! => {“changed”: false, “failed”: true, “invocation”: {“module_args”: {“dest”: “/tmp/testconfig.json”, “src”: “test-template.j2”}, “module_name”: “template”}, “msg”: “AnsibleError: ERROR! an unexpected type error occurred. Error was sequence item 0: expected string, dict found”}

I have 2 issues:

  1. the error above seems to indicate there is something wrong with the calling of the template action, but in fact it is a problem with the return value of the run() function of the lookup module implementation. It would be of great help if this error would specify so, as to be clearer (granted, this is mainly a problem for lookup-module developers, but I was just migrating to Ansible 2.0 so I suspected the problem was in the template module).

  2. Why can I not return a dict? Is this a necessary limitation?

Due to lookup plugins being the mechanism that powers with_ style loops, they are expected to return lists, even if a list of a single element.

All lookup plugins that only return a single thing such as env return a list of a single element, so you could nest your dict inside of a list.

Another way, and it requires you to call lookup a certain way, will allow you to return a dict as is (although if you tried to use with_my_custom_lookup it would cause problems)

This would look like:

“{{ lookup(‘my_custom_lookup’, ‘some_argument’, wantlist=True) }}”

wantlist=True, although sounding like it will return a list, basically tells lookup not to try doing a join on the resultant value obtained from the lookup plugin, and just let it be returned in it’s current format (which is generally expected to be a list)

Thanks a lot Matt!
I figured it out. I can just use the [ { “k” : “v” } ] approach.