Search code examples
ansibleansible-inventory

Ansible - reading inventory file


I have an inventory file

[hosttype1]
Server
Server2
[hosttype2]
server3
server4

I am trying to read this as a whole into ansible. The file is used in the normal way to define hosts and types for code deploy, but I need to also read the full content for adding into a config file.

the inventory file differs for different environments being deployed, so there is no fixed location for it.

Is it possible to read the file and create a variable that I can then loop over and use the hosttype and a comparitor?


Solution

  • The easiest way is to use it as an inventory. For example

    shell> cat hosts
    [hosttype1]
    Server
    Server2
    [hosttype2]
    server3
    server
    
    shell> cat pb.yml
    - hosts: localhost
      vars:
        my_groups: "{{ groups|difference(['all', 'ungrouped']) }}"
        my_hosts: "{{ my_groups|map('extract', groups)|list }}"
        my_inventory: "{{ dict(my_groups|zip(my_hosts)) }}"
      tasks:
        - debug:
            var: my_inventory
    

    gives

    shell> ansible-playbook -i hosts pb.yml 
    
    PLAY [localhost] ******************************************************
    
    TASK [debug] **********************************************************
    ok: [localhost] => 
      my_inventory:
        hosttype1:
        - Server
        - Server2
        hosttype2:
        - server3
        - server