剧本中ansible主机的默认值?

A K*_*A K 4 ansible

我的示例剧本(适用于 ansible 2.1)是:

---
# This is sample playbook.

- name: add sample_role
  hosts: '{{ target }}'
  become: true
  become_user: root
  roles:
    - sample role
Run Code Online (Sandbox Code Playgroud)

当我运行它时,一切都很好:

ansible-playbook -i staging test_playbook.yml --extra-vars "target=192.168.15.29"
Run Code Online (Sandbox Code Playgroud)

我怎样才能省略目标?

我尝试过这样的事情:

  hosts: '{{ target | default(all) }}'
Run Code Online (Sandbox Code Playgroud)

或者

  hosts: '{{ target | default(hostvars) }}'
Run Code Online (Sandbox Code Playgroud)

然后运行:

ansible-playbook -i staging test_playbook.yml
Run Code Online (Sandbox Code Playgroud)

, 但不幸的是:

错误!“全部”未定义

或者:

错误!“hostvars”未定义

Arb*_*zar 5

如果您只是添加all不带引号的内容,那么它会将其作为变量,因此您可以像这样修复它:

hosts: '{{ target | default("all") }}'

到目前为止,hostvars它是 ansible 中的保留字,我认为不能将其用于此目的。它的值将是这样的:

ok: [localhost] => {
    "msg": {
        "localhost": {
            "ansible_check_mode": false,
            "ansible_version": {
                "full": "2.1.0.0",
                "major": 2,
                "minor": 1,
                "revision": 0,
                "string": "2.1.0.0"
            },
            "group_names": [],
            "groups": {
                "all": [
                    "localhost"
                ],
                "ungrouped": []
            },
            "inventory_dir": null,
            "inventory_file": null,
            "inventory_hostname": "localhost",
            "inventory_hostname_short": "localhost",
            "omit": "__omit_place_holder__41c600ef78930ed8b38e6eed4e5b5ab51199729e",
            "playbook_dir": "/Users/xyz/test-ansible"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

希望对您有帮助。