jardindeden
jardindeden

Reputation: 124

Ansible lookup plugin with special variables

Is Ansible lookup plugin able to support special characters ?

example:

vars:
  stage: prod
debug:
  msg: "{{ lookup('?', 'groups.' + stage + '.index(inventory_hostname)') }}"

If not, is it still possible to solve this problem any other way in order to get the index of the host which belong to a group stage ?

Thanks for the help here.

Upvotes: 0

Views: 505

Answers (1)

Zeitounator
Zeitounator

Reputation: 44605

To get the index of an element in a list, you can indeed use index() in jinja2 as you seem to have already discovered. But there is no need to use a lookup for that (and there is no lookup named ? anyway). To do that on a dynamically named group like in your example, this gives.

debug:
  msg: "{{ groups[stage].index(inventory_hostname) }}"

See the documentation on accessing complex variables for more info on the syntax.

Meanwhile, you should be aware that this method will fire an error if the value does not exist in the list (i.e. the host does not exist in the group) and that it cannot be recovered with the default filter like with normal undefined variables.

So if there is any chance your targe host is not in the stage group, you should add some extra jinja2 expression to make sure you always get a value without error (e.g. return -1 if host is not in list):

debug:
  msg: "{%if machine in groups[stage] %}{{ groups[stage].index(inventory_hostname) }}{% else %}-1{% endif %}"

Since you mentioned lookups, there is an other solution using the indexed_items plugin. The idea here is to transform the group list in a list of (<index>, <host>) tuples, search tuples having second element equal to the current host, keep only first element of the result, default to a dummy tuple in case the result is empty and print the first element of the retained tuple:

debug:
  msg: "{{ (lookup('indexed_items', groups[stage]) | selectattr('1', 'eq', inventory_hostname) | first | default([-1]))[0] }}"

Upvotes: 2

Related Questions