PRASHANT JHA
PRASHANT JHA

Reputation: 39

Running the ansible play on particular group of servers by taking the name of groups as input dynamically

Lets say I have got inventory file like this
inventory.txt

abc
cde 
def 

[check1:children]
abc

[check2:children]
cde

[check3: children]
def

Now I will take input from user eg: check1,check3 separated by comma in a variable and then I want to run my next play on those groups check1,check3.
How can I achieve this?

Upvotes: 1

Views: 490

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39294

A comma separated list of groups or hosts is a perfectly valid pattern for the hosts of a playbook.

So you can just pass it directly in the hosts attribute of your playbook:

- hosts: "{{ user_provider_hosts }}"
  gather_facts: no
  
  tasks:
    - debug:

Then, you just have to add this values in the --extra-vars (or short, -e) flag of the playbook command:

ansible-playbook play.yml --extra-vars "user_provider_hosts=check1,check3"

This would yield:

TASK [debug] ******************************************************************
ok: [abc] => 
  msg: Hello world!
ok: [def] => 
  msg: Hello world!

Another option is to target all hosts:

- hosts: all
  gather_facts: no
  
  tasks:
    - debug:

And use the purposed --limit flag:

ansible-playbook play.yml --limit check1,check3

A third option would be to use a play targeting localhost to prompt the user for the groups to target, then use a fact set by localhost to target those groups in another play:

- hosts: localhost
  gather_facts: no

  vars_prompt:
    - name: _hosts
      prompt: On which hosts do you want to act? 
      private: no

  tasks:
    - set_fact:
        user_provider_hosts: "{{ _hosts }}"

- hosts: "{{ hostvars.localhost.user_provider_hosts }}"
  gather_facts: no
  
  tasks:
    - debug:

Would interactively ask for hosts and act on the user provider hosts:

On which hosts do you want to act?: check1,check3

PLAY [localhost] **************************************************************

TASK [set_fact] ***************************************************************
ok: [localhost]

PLAY [check1,check3] **********************************************************

TASK [debug] ******************************************************************
ok: [abc] => 
  msg: Hello world!
ok: [def] => 
  msg: Hello world!

Upvotes: 1

Related Questions