How do you get group name of the executing role in ansible [duplicate]

帅比萌擦擦* 提交于 2020-01-24 05:50:09

问题


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

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

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.

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?


回答1:


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.



来源:https://stackoverflow.com/questions/49390513/how-do-you-get-group-name-of-the-executing-role-in-ansible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!