texasdave
texasdave

Reputation: 706

Match single custom host inventory variable when using multiple nested host variables

I'm trying to loop through matched hosts in an inventory file where each host has certain variables, but, each host might have multiple nested variables associated with it, like this below:

inventory file:

[support]
myhost1 application_role="['role1', 'role2']" team="['ops', 'dev']"
myhost2 application_role="['role1']" team="['ops', 'sales']"

My goal is to try and deliver a file to only the hosts that match the customer variable key "team" equal to value "sales".

I'm testing with this test task just to get some response but as you can see from the output, it is skipping all of them because it's not catching the nested variable, it seems to be reading the variable as one whole string and not splitting?

test task:

- name: Loop through example servers and show the hostname, team attribute
  debug:
    msg: "team attribute of {{ item }} is {{ hostvars[item]['team'] }}"
  when: hostvars[item]['team'] == "sales"
  loop: "{{ groups['support'] }}"

output:

PLAY [support] ************************************************************************

TASK [ssh_key_push : Loop through example servers and show the hostname, team attribute msg=team attribute of {{ item }} is {{ hostvars[item]['team'] }}] ***
skipping: [myhost1] => (item=myhost1) 
skipping: [myhost1] => (item=myhost2) 
skipping: [myhost1]
skipping: [myhost2] => (item=myhost1) 
skipping: [myhost2] => (item=myhost2) 
skipping: [myhost2]

I'm not sure how to get ansible to read a single nested variable from the host inventory.

Upvotes: 0

Views: 182

Answers (1)

Zeitounator
Zeitounator

Reputation: 44595

when: hostvars[item]['team'] == "sales"

This expression is comparing a list e.g.

team:
 - ops
 - sales

to a single string value sales. This will always return false.

What you want to do is check if the list contains that value. As explained in this link, Jinja2 provides an in test, but ansbile provides contains which can ease writing in some cases. Both versions are equivalent:

when: hostvars[item]['team'] is contains 'sales'
# or
when: "'sales' in hostvars[item]['team']"

Upvotes: 2

Related Questions