shepster
shepster

Reputation: 499

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?

Upvotes: 0

Views: 597

Answers (2)

Becky Saunders
Becky Saunders

Reputation: 40

The answer by @iker lasaga is definitely correct. As with most coding questions, there are multiple correct answers :D

Ansible includes group_names, which is a magical list containing all of the groups that the host is a part of. You can then query the list to see if your target group is in that list:

- name: Configure QA folder
  import_role:
    name: configure_qa
  when: "'conf_qa' in group_names"

Voila, you have two options ;)

Here's where I learned about group_names

Upvotes: 0

iker lasaga
iker lasaga

Reputation: 394

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']

Upvotes: 2

Related Questions