Ansible需要制作一个替换了变量的json列表

1 json jinja2 ansible

我有这个json文件:

}
  "retry_join": ["192.168.100.11","192.168.100.12","192.168.100.14"],
  "server": true,
  "data_dir": "/var/lib/consul",
  "log_level": "INFO",
  "enable_syslog": false,
  "datacenter": "Morrisville",
  "rejoin_after_leave": true,
  "client_addr": "0.0.0.0",
  "bind_addr": "{{ ansible_host }}",
  "advertise_addr": "{{ ansible_host }}"
}
Run Code Online (Sandbox Code Playgroud)

我需要在这里用不确定的清单文件中不确定数量的主机替换此行,例如顶部标头(mville)中的主机:

    [mville]
swarm000 ansible_host=192.168.100.11
swarm001 ansible_host=192.168.100.12
swarm002 ansible_host=192.168.100.14

[000servers]
swarm000 ansible_host=192.168.100.11

[001servers]
swarm001 ansible_host=192.168.100.12

[002-00xservers]
swarm002 ansible_host=192.168.100.14
Run Code Online (Sandbox Code Playgroud)

所以这行在这里:

"retry_join": ["192.168.100.11","192.168.100.12","192.168.100.14"],
Run Code Online (Sandbox Code Playgroud)

需要用ansible填充,但我不知道它们可以容纳多少个主机,因此需要在正确的位置放置逗号。

我知道如何在ansible中执行这样的for循环:

{% for host in groups['000servers'] %}
*.info;mail.none;authpriv.none;cron.none   @{{ hostvars[host]['ansible_host'] }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

我该如何应用呢?

谢谢!

Jos*_*ner 5

看一下Ansible中可用过滤器。特别是to_json过滤器

{{ some_variable | to_json }}
Run Code Online (Sandbox Code Playgroud)

join过滤器

{{ list | join(" ") }}
Run Code Online (Sandbox Code Playgroud)

应该能够帮助您正确地模板化这些值。


小智 5

我在构建 consul 时遇到了同样的问题。一件事(有点离题,但值得分享)我建议您:构建小模板,假设您有 1 个用于 consul 服务器的模板和一个用于加入列表的模板。它会让你的生活更轻松,也更灵活。Consul 将按字母顺序包含文件。

为了回答你的问题,这是我所做的:

// Join local DC agents
{ 
    "start_join": [ {%for host in groups.dc1 %} {% if hostvars[host]['inventory_hostname'] != inventory_hostname %} "{{hostvars[host]['inventory_hostname']}}" {% if not loop.last %}, {%endif%}{%endif%}{%endfor%}]
}
Run Code Online (Sandbox Code Playgroud)

请注意,我使用的主机名,但你可以简单地改变inventory_hostnameansible_host

希望有所帮助,如果您希望我更具体地了解某些内容,请告诉我。