Using patterns to populate host properties in Ansible inventory file

ε祈祈猫儿з 提交于 2019-12-01 08:03:10

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/28440509/using-patterns-to-populate-host-properties-in-ansible-inventory-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!