Using patterns to populate host properties in Ansible inventory file

前端 未结 2 1754
心在旅途
心在旅途 2021-01-15 06:22

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 conci

相关标签:
2条回答
  • 2021-01-15 07:16

    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).

    0 讨论(0)
  • 2021-01-15 07:25

    This is best done using Ansible's Dynamic Inventory features. See Developing Dynamic Inventory Sources.

    This means writing a script that returns your hostname in a JSON format.

    0 讨论(0)
提交回复
热议问题