How to select the host in Ansible depending on the value of a variable?

Viewed 92

I want to use the answer provided by the user to select the hosts in an Ansible playbook, like the following pseudocode:

---   
- name: feed the machines

  vars_prompt:
    - name: food
      prompt: "Which food do you have? b:Banana, g:grass, m:meat."
      default: "b"
      private: no

  hosts: 'monkeys' if food=='b' else {'cows' if food=='g' else 'lions'}

I am aware that using a dictionary would also be an option.

How do I implement it? It would be nice to have answers with ifs or with a dictionary.

1 Answers

You just need to template the hosts parameter with the correct Jinja expression, so an inline-if:

- hosts: "{{ 'monkeys' if food=='b' else 'cows' if food=='g' else 'lions' }}"
  gather_facts: no

  vars_prompt:
    - name: food
      prompt: "Which food do you have? b:Banana, g:grass, m:meat."
      default: "b"
      private: no

Which would yield:

Which food do you have? b:Banana, g:grass, m:meat. [b]: 

PLAY [monkeys] ***************************************************************

PLAY RECAP *******************************************************************

The same with a dictionary that would make a food correspond to an animal:

- hosts: "{{ food_to_animal[food] }}"
  gather_facts: no

  vars:
    food_to_animal:
      b: monkeys
      g: cows
      m: lions

  vars_prompt:
    - name: food
      prompt: "Which food do you have? b:Banana, g:grass, m:meat."
      default: "b"
      private: no
Related