How to specify different hosts for different playbooks in one ansible script

ansible

As I understand, each playbook takes one hosts entry. I want to know that if I create a container playbook that includes other playbooks, can I parameterize the hosts for each playbook include. So something like

---
- include playbook_1.yml
    hosts: tag_postgres
- include: playbook_2.yml
    hosts: tag_rabbitmq

I am able to put all different playbooks in one script and call, but then this way I am not able to reuse some set_fact from one playbook into another and hence there is a lot of task duplication.

Another corollary of the question is, can I launch ec2s on amazon which would have

hosts: localhost

and configuration of the launched ec2s, which would basically configure inventory from -i ec2.py, and have hosts specified as

hosts: tag_<some_tag>

happening through the same playbook or a set of included playbooks (different roles)?

Best Answer

Actually, you can have more than one hosts: section per playbook. It appears that a hosts: starts a new play. See http://www.tecmint.com/use-ansible-playbooks-to-automate-complex-tasks-on-multiple-linux-servers/, for example.

Something like this works for me (ansible 2.2):

---
- hosts: localhost 
  connection: local
  roles:
    - { role: ec2,
        tag: 'master',
        instance_type: t2.2xlarge,
        count: 1
      }
  tasks:
  - shell: hostname # reports localhost

- hosts: tag_master
  tasks:
  - shell: hostname # reports instance(s) with tag 'master'

So, put hosts: at the top of each included .yml, not after the include:.

Related Topic