大网数据广告活动
服务器运维问答

Ansible same host on different groups with group_vars

· 52CE 我爱测

I have an Ansible inventory like the following: [group1] host1.mydomain [maingroup:children] group1 [group2] host1.mydomain I need to declare the same host on different groups since in this host there are two similar services col…

问题原文

原帖链接 · trikelef · CC BY-SA 4.0

I have an Ansible inventory like the following:

[group1]
host1.mydomain

[maingroup:children]
group1

[group2]
host1.mydomain

I need to declare the same host on different groups since in this host there are two similar services collocated. In order to distinguish between the two services, I have created the following group vars:

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

group_vars/group2
---
servicepath: /service2/path

When I first run a playbook with hosts: maingroup, then the same playbook with hosts: group2, it used the correct servicepath variable value each time (first run=/service1/path, second run=/service2/path).

However, in all subsequent retries when I run a playbook with maingroup I got the value servicepath: /service2/path

I only managed to run the playbook with correct variables with --extra-vars=@group_vars/group2 ansible-playbook parameter.

Could this be an Ansible bug or am I missing something?

已采纳解答

原帖链接 · TheDESTROS · CC BY-SA 4.0

The fact is that ansible binds the value of variables to the host, not to the group. That is, there can be only one value for one variable on one host.

Try this just to override the value of the variable on the host everytime:

---
- 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 }}"

where {{ hosts }} = "maingroup" or "group2"

Example:

---
- 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 }}"

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-05-06)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。