使用 group_vars 在不同组上使用同一主机

tri*_*lef 4 ansible ansible-playbook

我有一个 Ansible 清单,如下所示:

[group1]
host1.mydomain

[maingroup:children]
group1

[group2]
host1.mydomain
Run Code Online (Sandbox Code Playgroud)

我需要在不同的组上声明相同的主机,因为在这个主机中有两个类似的服务并置。为了区分这两个服务,我创建了以下组变量:

group_vars/maingroup
---
servicepath: /service1/path

group_vars/group2
---
servicepath: /service2/path
Run Code Online (Sandbox Code Playgroud)

当我第一次使用 运行剧本hosts: maingroup,然后使用相同的剧本时hosts: group2,它servicepath每次都使用正确的变量值(第一次运行= /service1/path,第二次运行= /service2/path)。

但是,在我运行剧本时的所有后续重试中,我都maingroup获得了价值servicepath: /service2/path

我只设法使用--extra-vars=@group_vars/group2ansible-playbook 参数使用正确的变量运行 剧本。

这可能是 Ansible 错误还是我遗漏了什么?

The*_*ROS 6

事实是 ansible 将变量的值绑定到主机,而不是组。也就是说,一台主机上的一个变量只能有一个值。

试试这个只是为了每次都覆盖主机上变量的值:

---
- hosts: "{{ hosts }}"
  vars_files:
    - group_vars/{{ hosts }}.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"

- hosts: "{{ hosts }}"
  vars_files:
    - group_vars/{{ hosts }}.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"
Run Code Online (Sandbox Code Playgroud)

其中 {{ hosts }} = "maingroup" 或 "group2"

例子:

---
- hosts: "maingroup"
  vars_files:
    - group_vars/maingroup.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"

- hosts: "group2"
  vars_files:
    - group_vars/group2.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"

- hosts: "maingroup"
  vars_files:
    - group_vars/maingroup.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"
Run Code Online (Sandbox Code Playgroud)