Ansible host in different groups and group_vars

Ansible host in different groups and group_vars

When you try to organize your variables in Ansible, storing them in your inventory will help you to keep all your environments metadata in one place. Splitting host and group variables into separate files make it easier to catalogue different components variables.

Let say you have configured SOA, WebCenter Portal, Identity Manager Oracle Fusion Middleware products in highly available mode, and created a set of files in group_vars directory:
group_vars/soa.yml
group_vars/wcp.yml
group_vars/idm.yml

Your SOA servers belong to soa group, WebCenter portal servers to wcp group, and Identity Management servers to idm group. You have three WebLogic domains, and you have three Admin servers. There are separate scripts for WebLogic Admin servers maintenance, and you keep them in independent groups: soa-admin, wcp-admin, idm-admin.

Now you need to create more files in the group_vars directory. And you could end up with duplicate copies of your metadata for servers, clusters, machines.

Thanks to the fact that Ansible binds the value of variables to the host, not to the group, you only have to add your admin hosts to exiting groups without duplicating files in group_vars directory.

For example, in your hosts.yml file:

wcp-admin:
  hosts:
    adm1.acme.com
wcp:
  hosts:
    adm1.acme.com
    wcp1.acme.com
    wcp2.acme.com

Now, when you execute your playbook for wcp-admin group, you have full visibility to variables from group_vars/wcp.yml file.

You might have all Admin servers on one host, keep the host in the admin group, and use the following approach to specify the group_var directory file to use depending on the product you are performing maintenance on:

---
- hosts: admin
  vars_files:
    - group_vars/{{ product }}.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"

"servicepath" variable would be taken from the respective product group_var file.