Search code examples
ansibleansible-inventory

Run roles according to host from Ansible playbook


I have to use two playbooks as my host are changing for each role. Is there any workaround so that I can get this done in single playbook??

Playbook-1:

- name: Install & configure SSH on servers
  gather_facts: True
  sudo: yes
  hosts: zookeeper
  roles:
  - { role: discover-zookeeper,         tags: ['discover-zookeeper']}

Playbook-2:

- name: Install & configure SSH on servers
  gather_facts: True
  sudo: yes
  hosts: kafka
  roles:
  - { role: discover-kafka,             tags: ['discover-kafka']}

I have tried this approach, but it seems that it's not how Ansible works..

playbook.yml:

- name: Install & configure SSH on servers
  gather_facts: True
  sudo: yes
  roles:
  - { role: discover-zookeeper,         tags: ['discover-zookeeper'],   hosts: zookeeper}
  - { role: discover-kafka,             tags: ['discover-kafka'],   hosts: kafka}

Solution

  • If I see it correctly, you are talking about two plays, NOT two playbooks. Because a playbook is, as fas as I understand your question, exactly what you are looking for. As an example:

    - hosts: hostA
      roles:
        - roleA
        - roleB
    - hosts: hostB
      roles:
        - roleC
        - roleD
    

    (comment: please use "(cmd/ctrl) + k" to format in better readable code-style)