Search code examples
ansibleautomated-testsansible-inventory

Ansible check hosts file


Ansible: 2.9

I search a command or option how to check consistency between my "hosts" inventory file vs. group_vars tree fs.

I explain:

  • My Host file:
[all]
N01
N02
S01
S02

[zone1]
N01
N02

[zone2]
S01
S02

[zone3]
Z01
Z02

  • Group_vars tree FS:
PlayBook_dir
\__group_vars:
   - zone1.yml
   - zone2.yml
  • Desired, make a Test with this check:

When I launch my Playbook he show a similar of "Error No zone3 in group_var dir tree".

You know for this or other tests?

Thank's!


Solution

  • You could have a play on localhost that checks for the existence of the group_vars files using the stat module. The results of this can be checked with assert.

        # First stat the path for file existence by looping over inventory groups
        - stat:
            path: "{{ playbook_dir }}/group_vars/{{ item.key }}.yml"
          loop: "{{ groups | dict2items }}"
          register: gvars
    
        # Loop over the registered variable and fail assertion if path doesn't exist
        - assert:
            that:
            - item.stat.exists
            fail_msg: "{{ item.invocation.module_args.path }} does not exist"
          when:
            - item.item.key not in ["all", "ungrouped"]
          loop: "{{ gvars.results }}"
          loop_control:
            label: "{{ item.item.key }}"