Conditional loop using hostvars

Hi all,

I am encountering a problem using a conditional loop with hostvars. I am getting an error, that the conditional is not correct. Here underneath is my module:

hostlist: “{{ hostlist | default() + [item] }}”
loop: “{{ groups[‘ios’] }}”
when: hostvars.[‘item’].[‘failed_attempt’] == “failed”

I am using ansible 2.10.

Do you have any idea, how can I fix this?

Thanks a lot!

when: hostvars.['item'].['failed_attempt'] == "failed"

You did not include the error (which is something you should definitely do when you want help), but: this is not valid syntax. . is an accessor, as is []; you should only use one of them for each access.

when: hostvars['item']['failed_attempt'] == "failed"


when: hostvars.item.failed_attempt == "failed"

However, what you probably actually want is

when: hostvars[item]['failed_attempt'] == "failed"


when: hostvars[item].failed_attempt == "failed"

with an unquoted item so that the value of the variable is used rather than the literal string.

1 Like


Thank you for you support. I gave it a try, but it didn’t work.

    hostlist: "{{ hostlist | default([]) + [item] }}"
  loop: "{{ groups['ios'] }}"
  when: hostvars[item]['failed_attempt'] == "failed"

And the error:

fatal: [xxx]: FAILED! => {“msg”: “The conditional check ‘hostvars[item][‘failed_attempt’] == "failed"’ failed. The error was: error while evaluating conditional (hostvars[item][‘failed_attempt’] == "failed"): ‘ansible.vars.hostvars.HostVarsVars object’ has no attribute ‘failed_attempt’\n\nThe error appears to be in ‘xxx’: line 103, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: "Create a list with all failed attempts"\n ^ here\n”}

Hi @chtsalid - just note that I’ve deleted your duplicate posts. I’m assuming your were trying to edit your original post, so I’ve left the one that seems formatted best.

1 Like