0

If the user passes perform_action parameter as any of these telnetcurlnslookuptracerouteget_ip_address then i want the play to run on localhost else it should run on remotehosts

ansible-playbook test.yml -e perform_action='nslookup'

- name: "Play 1"
  hosts: localhost
  tasks:
    - set_fact:
        final_delegate: "{{ 'localhost' if perform_action in 'telnetcurlnslookuptracerouteget_ip_address' else 'remotehosts' }}    "

    - debug:
        msg: "Play needs to run on {{ final_delegate }}"

- name: "Play 2"
  hosts: "{{ final_delegate }}"
  tasks:
    - debug:
        msg: "Im running on {{ inventory_hostname }}"

Output:

The Play needs to run on localhost

However, Play 2 fails with the below error:

ERROR! The field 'hosts' has an invalid value, which includes an undefined variable. The error was: 'final_delegate' is undefined

Can this condition be set with the play as i m doing or is it possible only by putting a condition on -e parameter?

Ashar
  • 2,942
  • 10
  • 58
  • 122
  • 1
    Have you tried with Ansible's delegation feature? https://docs.ansible.com/ansible/latest/user_guide/playbooks_delegation.html – Carlos Monroy Nieblas Oct 28 '22 at 05:58
  • `hosts: "{{ hostvars.localhost.final_delegate }}"` > https://stackoverflow.com/questions/33896847/how-do-i-set-register-a-variable-to-persist-between-plays-in-ansible – β.εηοιτ.βε Oct 28 '22 at 07:21
  • 1
    This said, you can put your ternary if in the host directly: `hosts: "{{ 'localhost' if perform_action in 'telnetcurlnslookuptracerouteget_ip_address' else 'remotehosts' }}"` – β.εηοιτ.βε Oct 28 '22 at 07:23
  • @β.εηοιτ.βε suggestion helped. Thank you ~~ – Ashar Oct 28 '22 at 11:22

1 Answers1

1

Your problem is that at the moment of evaluating which hosts to run play 2 on, you are polling a variable which is only defined for localhost. It's the chicken or the egg thing. It's technically not running on localhost, so it doesn't know which host to check the variable on, to find that it should run on localhost.

I would try...

hosts: "{{ hostvars['localhost']['final_delegate'] }}"

That might work for you. The templating for host patterns can be a little picky about things.