Ansible inventory - List and organize the managed hosts

mail

How to list the group(s) a host belongs to ?

with an ad-hoc command

ansible -m debug -a 'msg={{group_names}}' myServer1,myServer2

with a playbook

  1. create an executable playbook file
    playbookFile=./showAnsibleGroups; cat << EOF > "$playbookFile" && chmod +x "$playbookFile"
    #!/usr/bin/env ansible-playbook
    
    - hosts: all
      gather_facts: no
      tasks:
      - name: show the groups the host(s) are in
        debug:
          msg: "{{group_names}}"
    EOF
    
  2. run it :
    ./showAnsibleGroups -i inventories/ -l myServer1,myServer2
    TASK [show the groups the host(s) are in] ***********************************************************************
    ok: [myServer1] => {
        "msg": [
            "RHEL",
            "RHEL8",
            "preprod"
        ]
    }
    
    
    PLAY RECAP ******************************************************************************************************
    myServer1	: ok=1	changed=0	unreachable=0	failed=0	skipped=0	rescued=0	ignored=0
    myServer2	: ok=1	changed=0	unreachable=0	failed=0	skipped=0	rescued=0	ignored=0
mail

Can an inventory file include another inventory file ?

How to proceed :

  1. create several inventory files matching your needs :
    [project root]
    inventories/ the inventory files directory
    hosts an inventory file
    other_hosts another inventory file
    more_hosts one more inventory file
    This works both with
    • ini-style
    • yaml-style
    Ansible inventories.
  2. that's it, you can address :
    • all hosts from all inventory files :
      <ansible command> -i inventories/ all
      -i inventories/ is equivalent to calling each inventory file with a distinct -i inventoryFile
    • all hosts from specific inventory files :
      <ansible command> -i inventories/hosts -i inventories/other_hosts all
    • hosts from a specific group :
      <ansible command> -i inventories/hosts -i inventories/other_hosts myGroup
  3. feel free to test your targeting with ansible-inventory
mail

How to proof inventory expression ?

Situation

Solution

ansible-inventory to the rescue !!!
mail

The inventory file

The inventory file :

Default groups

  • The implicit group all includes all slaves.
  • There is also another group named ungrouped. The logic behind Ansible is that all slaves must belong to at least 2 groups : all and "an other one". If there is no such "other one", ungrouped will be that one.
Both groups will always exist and don't need to be explicitly declared.