Search code examples
hostansibleinventory

Using patterns to populate host properties in Ansible inventory file


I have a host file that looks like

[foo]
foox 192.168.0.1 id=1
fooy 192.168.0.1 id=2
fooz 192.168.0.1 id=3

However, I'd like to more concisely write this using patterns like:

[foo]
foo[x:z] 192.168.0.1 id=[1:3]

But this is getting interpreted as id equaling the raw text of "[1:3]", rather than 1, 2, or 3. Is there a way to achieve this in the inventory file, or will I need to do something through host vars and/or group vars?


Solution

  • This can't be done within an inventory file. I think set_fact is your best bet to programmatically build an inventory this simple.

    ---
    - hosts: all
      tasks:
        - add_host:
            name: "host{{ item }}"
            ansible_ssh_host: "127.0.0.1"
            ansible_connection: "local"
            group: "new"
            id: "{{ item }}"
          with_sequence: count=3
          delegate_to: localhost
          run_once: yes
    - hosts: new
      tasks:
        - debug:
            msg: "{{ id }}"
    

    If I recall correctly, Jinja capabilities have been removed from every place they shouldn't have been, i.e. outside quotes, braces, special cases like when: in YML files.

    When I say programmatically, though, we're talking about Ansible.. one of the last candidates on earth for general purpose scripting. Dynamic inventory scripts are a better approach to problems like these, unless we're talking three servers exactly.

    The simplest inventory script to accomplish this would be (in your hosts dir or pointed to by the -i switch:

    #!/usr/bin/env python
    import json
    inv = {}
    for i in range(3):
      inv[i] = {"hosts":["host%s" % i],"vars":{"id":i,"ansible_ssh_host":"127.0.0.1", "ansible_connection":"local"}}
    print json.dumps(inv)
    

    Again, I'm afraid there is nothing as "pretty" as what you're looking for. If your use case grows more complex, then set_fact, set_host and group_by may come in handy, or an inventory script, or group_vars (I do currently use group_vars files for server number).