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

Solution 1:

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:.

Solution 2:

http://docs.ansible.com/ansible/playbooks_variables.html#information-discovered-from-systems-facts

... There are other places where variables can come from, but these are a type of variable that are discovered, not set by the user.

Facts are information derived from speaking with your remote systems...

The facts are derived from your remote hosts. So this is the reason why normally you can share facts between your different hosts when your *.yml File have several playbooks.

Now, you can access facts from other hosts if you do something like this in another part of your playbook:

{{ hostvars['server01.example.com']['ansible_eth0']['ipv4']['address'] }}
...
...
{{ hostvars[groups['servers'][0]]['ansible_eth0']['ipv4']['address'] }}

but in this case, you need to remember that you need to get the facts before you use this. Then you can setup a first part in your playbook that get all the facts for all the hosts or use fact caching for this (see: http://docs.ansible.com/ansible/playbooks_variables.html#fact-caching)

Now, If you like to share options in your playbooks maybe can be better to rethink the info to put in variables and, with this, you can "share" your variables with the same include instruction, look at this:

http://docs.ansible.com/ansible/playbooks_variables.html#variables-defined-from-included-files-and-roles