你如何在ansible中获得执行角色的组名 [英] How do you get group name of the executing role in ansible
问题描述
我有一个用例,我需要在一个组中的所有主机中创建一个目录,该目录的名称将是该组的名称.
I have a use case where I need to create a directory in all hosts in a group whose name will be the name of the group.
例如:我创建了一个带有以下形式输出的动态清单文件:
Eg : I create a dynamic inventory file with output of the form :
{
"db": ["host1", "host2", "host3"],
"logs": ["host2"],
"misc": ["host4"]
}
我需要在 db 组的每个主机中创建一个名为 db 的目录,并在组 log 的每个主机中创建一个名为 log 的目录.
I need to create a directory by the name db in every host of the group db and directory named log in every host of the group log.
到目前为止我的剧本看起来像:
My playbook so far looks like :
- hosts: db
tasks:
- name: create db directory
file: path=db state=directory
- hosts: logs
tasks:
- name: create logs directory
file: path=logs state=directory
组数至少为 10+.这在未来可能会增长.我想为未来的团队编写一些易于扩展和管理的内容.
The number of groups is at least 10+. This may grow in the future. I want to write something that will be easily extendable and manageable for the future groups.
我读到 ansible 没有为任务的组名提供默认事实或变量.我发现如果我在主机中提供一个像 groupname 这样的变量,这是最好的.
I read that ansible doesn't provide a default fact or variable for group name for the task. I see that this can be best done if I provide a variable like groupname in host.
是否有更好的解决方案可以使用循环而不是重复相同的任务?
Is there a better solution that could use looping instead of repeating the same task?
推荐答案
您可以使用魔法变量 group_names
.该变量是当前主机所在的所有组的列表(数组).更多信息可从 文档
You can use the magic variable group_names
. The variable is a list (array) of all the groups the current host is in. More information is available per the documentation
- hosts: all
tasks:
- name: create db directory
file:
path: "{{ item }}"
state: directory
with_items: "{{ group_names }}"
免责声明:未测试此代码.
Disclaimer: Did not test this code.
这篇关于你如何在ansible中获得执行角色的组名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!