Search code examples
ansibleansible-inventory

how to build an ansible inventory


I need some structure in ansible inventory to do something like this:

I have multiple addresses (with different items) and every address has multiple queues (with different items) how can I build the inventory file for this.

something like this:

addresses:
  - name: "a-address"
    type: "anycast"
    read_username: "read"
    read_password: "xxxxx"
    write_username: "write"
    write_password: "xxxx"
    - queue_name: "a-queue1"
      queue_type: xxxx
    - queue_name: "a_queue2"
      queue_type: xvx
  - name: "b-address"
    type: "multicast"
    read_username: "readb"
    read_password: "xxxxx"
    write_username: "writeb"
    write_password: "xxxx"
    - queue_name: "b-queue1"
      queue_type: xvx
    - queue_name: "b_que

How can I do this and how should I walk through this in ansible?


Solution

  • Q: "How can I build the inventory file?"

    A: This is the YAML version of the inventory. I've added the variable queues to make it a valid YAML

    shell> cat hosts.yml
    all:
      hosts:
        a-address:
          type: anycast
          read_username: read
          read_password: xxxxx
          write_username: write
          write_password: xxxx
          queues:
            - queue_name: a-queue1
              queue_type: xxxx
            - queue_name: a_queue2
              queue_type: xvx
        b-address:
          type: multicast
          read_username: readb
          read_password: xxxxx
          write_username: writeb
          write_password: xxxx
          queues:
            - queue_name: b-queue1
              queue_type: xxxx
            - queue_name: b_queue2
              queue_type: xvx
    

    For example, the playbook

    - hosts: all
      tasks:
        - debug:
            var: type
    

    gives (abridged)

    ok: [a-address] => 
      type: anycast
    ok: [b-address] => 
      type: multicast
    

    Q: "Loop over addresses and within that loop a loop over the queues."

    A: The playbook below

    - hosts: localhost
      tasks:
        - include_vars: hosts.yml
        - debug:
            msg: "{{ item.0.key }} {{ item.1 }}"
          with_subelements:
            - "{{ all.hosts|dict2items }}"
            - value.queues
    

    gives(abridged)

    msg: 'a-address {''queue_name'': ''a-queue1'', ''queue_type'': ''xxxx''}'
    msg: 'a-address {''queue_name'': ''a_queue2'', ''queue_type'': ''xvx''}'
    msg: 'b-address {''queue_name'': ''b-queue1'', ''queue_type'': ''xxxx''}'
    msg: 'b-address {''queue_name'': ''b_queue2'', ''queue_type'': ''xvx''}'