Pages

Thursday, 22 April 2021

EX294 important Magic variables

1 Example Inventory

[dev]
node1

[ist]
node2

[uat]
node3
node4

[prd]
node4
node5
node6

2 "groups" is a dictionary of all groups in the inventory

groups=
{
 'all': ['node1', 'node2', 'node3', 'node4', 'node5', 'node6'],
 'dev': ['node1'],
 'ist': ['node2'],
 'prd': ['node4', 'node5', 'node6'],
 'uat': ['node3', 'node4'],
 'ungrouped': []
}

e.g 
we can get all node names by groups['all'].

3 "hostvars" is a dictionary of all inventory hosts with variables

hostvars
{
'node1': {'ansible_check_mode': False,
           'ansible_diff_mode': False,
           'ansible_facts': {},
           'ansible_forks': 5,
          ...
           'playbook_dir': '/home/smstong/ansible'},
 'node2': {'ansible_check_mode': False,
           'ansible_diff_mode': False,
           'ansible_facts': {},
           'ansible_forks': 5,
           ...
           'playbook_dir': '/home/smstong/ansible'},
 'node3': {'ansible_check_mode': False,
           'ansible_diff_mode': False,
           'ansible_facts': {},
           'ansible_forks': 5,
           'ansible_inventory_sources': 
           ...
           'playbook_dir': '/home/smstong/ansible'},
 'node4': {'ansible_check_mode': False,
           'ansible_diff_mode': False,
           'ansible_facts': {},
           'ansible_forks': 5,
           
            ...
           'playbook_dir': '/home/smstong/ansible'},
 'node5': {'ansible_check_mode': False,
           'ansible_diff_mode': False,
           'ansible_facts': {},
          ...
}

4 "inventory_hostname" is the node name of the current node

- name: only run on node1
  command: uname -r
  when: inventory_hostname == "node1"

5 "group_names" is a list of group names current node belongs to

e.g. for node1, 

group_names = ['dev']

use case:

- name: only run on group dev
  command: uname -r
  when: '"dev" in group_names"


No comments:

Post a Comment