从主机中提取group_name

问题描述 投票:0回答:2

当我运行 Ansible 剧本时,我定义了我的主机,它会查找我的清单中的一个组。

$ ansible-playbook -i inv/hosts conf.yml

conf.yml:

- name: Configure QA Nodes
  hosts: conf_qa

邀请/主持人:

[conf_qa]
confqa1
# confqa2

[conf_prod]
prod1
# prod2
prod3

我的角色(或剧本的其他元素)中有没有办法可以取消正在使用的

group_name
(或同等内容)?

我知道我可以在

group_vars/conf_qa.yml
中设置一个变量,例如
qa: true
,然后在我的角色中引用它

角色/init/tasks/main.yml:

- name: Do this when dealing with the conf_qa group
  when: qa == true

但是当我希望更直接地引用主机组时,使用

group_vars/conf_qa.yml
似乎是一个额外的中间步骤。有更好的办法吗?

ansible ansible-2.x ansible-inventory ansible-facts
2个回答
2
投票

您可以添加以下条件,这是来自我创建的剧本,我可以确认它是否有效。 它仅在属于该组的服务器中运行任务,其余服务器将显示为“已跳过”

- name: create api folder
  file:
    path: /var/log/api
    state: directory
  when: inventory_hostname in groups['switch']

0
投票

@iker lasaga答案绝对是正确的。与大多数编码问题一样,有多个正确答案:D

Ansible 包括

group_names
,这是一个神奇的列表,其中包含主机所属的所有组。然后,您可以查询列表以查看您的目标组是否在该列表中:

- name: Configure QA folder
  import_role:
    name: configure_qa
  when: "'conf_qa' in group_names"

瞧,你有两个选择;)

这是我了解group_names的地方

© www.soinside.com 2019 - 2024. All rights reserved.