如何在ansible [duplicate]中获取执行角色的组名

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

这个问题在这里已有答案:

我有一个用例,我需要在一个组中的所有主机中创建一个目录,其名称将是该组的名称。

例如:我创建了一个动态库存文件,其输出格式为:

{
   "db": ["host1", "host2", "host3"],
   "logs": ["host2"],
   "misc": ["host4"]
}

我需要在组日志的每个主机中创建一个名为db的目录,并在组日志的每个主机中创建名为log的目录。

到目前为止我的剧本看起来像:

- 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+。这可能会在未来增长。我想写一些可以轻松扩展和管理未来组的东西。

我读到ansible没有为任务的组名提供默认事实或变量。我看到如果我在主机中提供类似groupname的变量,这样做最好。

有没有更好的解决方案可以使用循环而不是重复相同的任务?

ansible ansible-inventory
1个回答
3
投票

你可以使用魔法变量group_names。该变量是当前主机所在的所有组的列表(数组)。更多信息可根据documentation获得

- hosts: all
  tasks:
  - name: create db directory
    file: 
      path: "{{ item }}" 
      state: directory
    with_items: "{{ group_names }}"

免责声明:没有测试此代码。

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