Ansible - 为多个组中使用的主机指定主机变量

Vas*_*pov 3 yaml ansible ansible-inventory

是否有一种DRY方法可以为多个组中的主机指定主机变量?例如:

all:
  hosts:
    mail.example.com:
      ansible_host: 10.10.10.33
  children:
    webservers:
      hosts:
        foo.example.com:
          ansible_host: 10.10.10.17
        bar.example.com:
          ansible_host: 10.10.10.18
    dbservers:
      hosts:
        one.example.com:
          ansible_host: 10.10.10.1
        two.example.com:
          ansible_host: 10.10.10.2
        three.example.com:
          ansible_host: 10.10.10.3
    test:
      hosts:
        bar.example.com:
          ansible_host: 10.10.10.18 # Don't like this being defined in a 2nd place
        three.example.com:
          ansible_host: 10.10.10.3  # =( Same
Run Code Online (Sandbox Code Playgroud)

是否可以将主机变量(如ansible_host示例(或软件许可证)中那样)仅定义在一个位置?我无法在 ansible 文档中找到任何合适的内容,因此占位符解决方案是使用YAML 锚点

all:
  hosts:
    mail.example.com:
      ansible_host: 10.10.10.33
  children:
    webservers:
      hosts:
        foo.example.com:
          ansible_host: 10.10.10.17
        bar.example.com: &bar
          ansible_host: 10.10.10.18
    dbservers:
      hosts:
        one.example.com:
          ansible_host: 10.10.10.1
        two.example.com:
          ansible_host: 10.10.10.2
        three.example.com: &three
          ansible_host: 10.10.10.3
    test:
      hosts:
        bar.example.com:
          << : *bar
        three.example.com:
          << : *three
Run Code Online (Sandbox Code Playgroud)

lar*_*sks 7

是否可以将主机变量(例如示例中的 ansible_host(或软件许可证))仅定义在一个位置?

如果您在清单文件中的任何位置为主机定义变量,则当 Ansible 运行时,将为该主机设置这些变量。例如,您可以这样编写库存:

all:
  hosts:
    mail.example.com:
      ansible_host: 10.10.10.33
    foo.example.com:
      ansible_host: 10.10.10.17
    bar.example.com:
      ansible_host: 10.10.10.18
    one.example.com:
      ansible_host: 10.10.10.1
    two.example.com:
      ansible_host: 10.10.10.2
    three.example.com:
      ansible_host: 10.10.10.3
  children:
    webservers:
      hosts:
        foo.example.com:
        bar.example.com:
    dbservers:
      hosts:
        one.example.com:
        two.example.com:
        three.example.com:
    test:
      hosts:
        bar.example.com:
        three.example.com:
Run Code Online (Sandbox Code Playgroud)

但这也行得通:

all:
  hosts:
    mail.example.com:
      ansible_host: 10.10.10.33
  children:
    webservers:
      hosts:
        foo.example.com:
          ansible_host: 10.10.10.17
        bar.example.com:
          ansible_host: 10.10.10.18
    dbservers:
      hosts:
        one.example.com:
          ansible_host: 10.10.10.1
        two.example.com:
          ansible_host: 10.10.10.2
        three.example.com:
          ansible_host: 10.10.10.3
    test:
      hosts:
        bar.example.com:
        three.example.com:
Run Code Online (Sandbox Code Playgroud)

我认为第一个版本更明显一些。