Search code examples
ansibleansible-facts

Using Host Group as Variable in Ansible Task


I'm working on putting together a playbook that will deploy local facts scripts to various groups in my Ansible inventory, and I would to be able to utilize the group name being worked on as a variable in the tasks themselves. Assume for this example that I have the traditional Ansible roles directory structure on my Ansible machine, and I have subdirectories under the "files" directory called "apache", "web", and "db". I'll now illustrate by example, ...

---
- hosts: apache:web:db

  tasks:
  - name: Set facts for facts directories
    set_fact:
      facts_dir_local: "files/{{ group_name }}"
      facts_dir_remote: "/etc/ansible/facts.d"

   - name: Deploy local facts
     copy:
       src: "{{ item }}"
       dest: "{{ facts_dir_remote }}"
       owner: ansible
       group: ansible
       mode: 0750
     with_fileglob:
      - "{{ facts_dir_local }}/*.fact"

The goal is to have {{ group_name }} above take on the value of "apache" for the hosts in the apache group, "web" for the hosts in the web group, and "db" for the hosts in the db group. This way I don't have to copy and paste this task and assign custom variables for each group. Any suggestions for how to accomplish this would be greatly appreciated.


Solution

  • While there is no group_name variable in ansible, there is a group_names (plural). That is because any host may be part of one or more groups.

    It is described in the official documentation as

    group_names List of groups the current host is part of

    In the most common case each host would only be part of one group and so you could simply say group_names[0] to get what you want.

    TLDR;

    Use group_names[0].