Search code examples
ansibleansible-2.xansible-inventoryansible-facts

Extracting group_name From hosts


When I run my Ansible playbook, I define my hosts which looks to a group in my inventory.

$ ansible-playbook -i inv/hosts conf.yml

conf.yml:

- name: Configure QA Nodes
  hosts: conf_qa

inv/hosts:

[conf_qa]
confqa1
# confqa2

[conf_prod]
prod1
# prod2
prod3

Is there a way in my Roles (or other elements of the Playbook) where I can back out which group_name (or equivalent) is being used?

I know I could set a variable in group_vars/conf_qa.yml such as qa: true and then reference it later in my Roles

roles/init/tasks/main.yml:

- name: Do this when dealing with the conf_qa group
  when: qa == true

But using group_vars/conf_qa.yml seems like an extra intermediary step when I was hoping to reference the host groups more directly. Is there a better way?


Solution

  • You can add the following condition, this is from a playbook I created and I can confirm that it works. It only runs the task in the servers that belong to that group, the rest of them will appear as "skipped"

    - name: create api folder
      file:
        path: /var/log/api
        state: directory
      when: inventory_hostname in groups['switch']