您如何在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的目录.
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屋!