如何为 Ansible 剧本中的所有主机全局设置 params/vars?

How to set params/vars globally for all hosts in Ansible's playbook?

现在我有一个剧本看起来像

- hosts: hws
  gather_facts: no
  vars_files:
    - variables.yml
  roles:
    - role: hypervisor

- hosts: vms
  gather_facts: no
  vars_files:
    - variables.yml
  roles:
    - role: web-server

而且看起来很丑。如何设置

  gather_facts: no
  vars_files:
    - variables.yml

全局为整个文件中的每个主机?

您可以使用 ansible 目录布局根据主机组或主机对变量进行分组。

ansible.cfg
hosts
group_vars/
    hws.yml   #variables for hws hosts
    vms.yml   #variables for vms hosts
    all  #here you can put variables commont to both hws + vms
roles/
    hypervisor
    web-server
playbook.yml

这样你就不需要在你的剧本中包含变量文件。

您还可以在此处阅读有关 ansible 目录结构的更多信息: http://docs.ansible.com/ansible/playbooks_best_practices.html

这里是关于变量优先级的: http://docs.ansible.com/ansible/playbooks_variables.html

祝你好运!