使用模式填充Ansible清单文件中的主机属性

Sha*_*ark 2 host inventory ansible

我有一个看起来像的主机文件

[foo]
foox 192.168.0.1 id=1
fooy 192.168.0.1 id=2
fooz 192.168.0.1 id=3
Run Code Online (Sandbox Code Playgroud)

但是,我想更简洁地使用以下模式来编写:

[foo]
foo[x:z] 192.168.0.1 id=[1:3]
Run Code Online (Sandbox Code Playgroud)

但这被解释为id等于"[1:3]"的原始文本,而不是1,2或3.有没有办法在库存文件中实现这一点,或者我需要通过主机做一些事情变种和/或群变?

nik*_*kov 5

这不能在库存文件中完成.我认为set_fact以编程方式构建库存是最好的选择.

---
- 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 }}"
Run Code Online (Sandbox Code Playgroud)

如果我没记错的话,Jinja的功能已经从他们不应该去过的每个地方删除,即外部引号,大括号,when:YML文件中的特殊情况.

但是,当我以编程方式说,我们谈论的是Ansible,它是地球上用于通用脚本编写的最后候选人之一.动态库存脚本是解决这些问题的更好方法,除非我们正在谈论三台服务器.

完成此任务的最简单的库存脚本(在您的hosts目录中或由-i交换机指向:

#!/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)
Run Code Online (Sandbox Code Playgroud)

再说一遍,我担心没有像你想要的那样"漂亮".如果你的使用情况变得更复杂,那么set_fact,set_host并且group_by可能会派上用场,或库存脚本,或group_vars(我目前使用的group_vars文件服务器的数量).