'hostvars' is undefined

Encountered below error:

ERROR! the field ‘hosts’ has an invalid value, which appears to include a variable that is undefined. The error was: ‘hostvars’ is undefined
I am using below command to define hosts value:

  • hosts: “{{ ‘prod-app-servers’ if hostvars[‘127.0.0.1’].result.stdout == ‘prod’ else ‘dr-app-servers’ }}”

I have tried different possibilities but of no use:

  • hosts: “{{ ‘prod-app-servers’ if hostvars[‘127.0.0.1’][result].stdout == ‘prod’ else ‘dr-app-servers’ }}”

I have tried below jinja format aswell, but of no use…

{% if {{hostvars[127.0.0.1][result][stdout]}} == prod %}prod-app-servers{% else %}dr-app-servers{% endif %}

My intention is to decide host during runtime based on a result.

I am not sure what is the mistake. prod-app-servers & dr-app-servers are the host groups that i defined in inventory file. ‘result’ is the value that gets populated at the begining of the playbook execution:

  • hosts: 127.0.0.1
    connection: local
    gather_facts: no
    tasks:
  • name: Check Failover or Failback
    command: --Executing a script file with some parameters–
    register: result

It fails on the syntax check, however the playbook run fine as expected.

This will only work if both play is in the same playbook, you error message indicate that this is not the case.

Hi,
Thanks for your reply.

All the plays are in same playbook.

My script is something like below:

  • hosts: 127.0.0.1
    connection: local
    gather_facts: no
    tasks:

  • name: Execute script
    command:
    register: result

  • hosts: “{{ ‘prod-app-servers’ if hostvars[‘127.0.0.1’].result.stdout == ‘prod’ else ‘dr-app-servers’ }}”
    gather_facts: no
    tasks:

  • name: Stop IIS
    win_command: iisreset /stop

As mentioned earlier, my script works as expected during execution but it throws error during syntax check.

Thanks