Pass hosts from master playbook to included playbook

cpburnz asked:

How can I pass the hosts from a master playbook to an included playbook?

I’m trying to create a master playbook for a type of server (e.g., a web server) which shares some common playbooks with other types of servers (e.g., gateway server, database server, etc.). I’m running Ansible 1.9.1 on Ubuntu 14.04.

The inventory file is:

[web-servers]
192.168.0.217

[db-servers]
192.168.0.218

The master playbook deploy-web-servers.yml is:

---
- hosts: web-servers
  tasks:
    - debug: var=hostvars

- include: setup-common.yml
  vars:
    server: "{{ hostvars['inventory_hostname'] }}"

The included playbook setup-common.yml is:

---
- hosts: "{{ server }}" 
  tasks:
    - debug: var=server

When I run this using the command:

ansible-playbook deploy-web-servers.yml -i inventory

It outputs:

PLAY [web-servers] ************************************************************ 

TASK: [debug var=hostvars] **************************************************** 
ok: [192.168.0.217] => {
    "var": {
        "hostvars": {
            "group_names": [
                "web-servers"
            ],
            "groups": {
                "all": [
                    "192.168.0.218",
                    "192.168.0.217"
                ],
                "db-servers": [
                    "192.168.0.218"
                ],
                "ungrouped": [],
                "web-servers": [
                    "192.168.0.217"
                ]
            },
            "inventory_hostname": "192.168.0.217",
            "inventory_hostname_short": "192"
        }
    }
}

PLAY [{{ hostvars['inventory_hostname'] }}] *********************************** 
skipping: no hosts matched

PLAY RECAP ******************************************************************** 
192.168.0.217              : ok=1    changed=0    unreachable=0    failed=0   

The included playbook setup-common.yml is never run because the host was not successfully forwarded as indicated by the lines:

PLAY [{{ hostvars['inventory_hostname'] }}] *********************************** 
skipping: no hosts matched

How can I forward the host to the included playbook?

My answer:


Here’s the problem:

- include: setup-common.yml
  vars:
    server: "{{ hostvars['inventory_hostname'] }}"

You do not need to specify this variable at all, nor should you be attempting to use it in the other playbook. By default the playbook will run for all hosts that it specifies. So don’t do this, and just write a normal playbook.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.