如何使用 Ansible 中的模板在同一任务中生成 json 文件



我需要从Hazelcast产品中获取JMX指标。我创建了一个连接到JMX端口的Logstash进程。这个过程必须读取一个json,其中是Hazelcast JMX的主机名,端口,集群,环境等信息。我需要在 Logstash 机器上为每个 Hazelcast 机器/端口部署 json 文件。在这种情况下,有三台 Hazelcast 机器和总共 6 个具有不同端口的进程。

示例数据:

榛子广播主机名: 榛子cast01, 榛子cast02, 榛子广播03 榛子端口: 6661, 6662, 6663, 6664, 6665 Logstash 主机名: logstash01, logstash02, logstash03

Ansible中的Hazelcast信息词典:

logstash_hazelcast_jmx:
- hazelcast_pre:
name: hazelcast_pre
port: 15554
cluster: PRE
- hazelcast_dev:
name: hazelcast_dev
port: 15555
cluster: DEV

Ansible 中的任务示例:

- name: Deploy HAZELCAST JMX config
template:
src: "hazelcast_jmx.json.j2"
dest: "{{ logstash_directory_jmx_hazelcast }}/hazelcast_jmx_{{ item }}_{{ item.value.cluster }}.json"
owner: "{{ logstash_system_user }}"
group: "{{ logstash_system_group }}"
mode: 0640
with_dict: 
- "{{ groups['HAZELCAST'] }}"
- logstash_hazelcast_jmx

最终结果应如下:

/opt/logstash/jmx/hazelcast/hazelcast_jmx_hazelcast01_DEV.json
/opt/logstash/jmx/hazelcast/hazelcast_jmx_hazelcast01_PRE.json
/opt/logstash/jmx/hazelcast/hazelcast_jmx_hazelcast02_DEV.json
...

下面是 json 内容的示例:

{
"host" : "{{ hostname of groups['HAZELCAST' }}",
"port" : {{ item.value.port }},
"alias" : "{{ hostname of groups['HAZELCAST' }}_{{ item.value.cluster }}",
"queries" : [
{
"object_name" : "com.hazelcast:instance=_hz_{{ item.value.cluster }},type=XXX,name=YYY",
"attributes" : [ "size", "localHits"  ],
"object_alias" : "Hazelcast_map"
}   ,{
"object_name" : "com.hazelcast:instance=_hz_{{ item.value.cluster }},type=IMap,name=user",
"attributes" : [ "size", "localHits"  ],
"object_alias" : "Hazelcast_map"
}
]
}

我认为我遇到的问题是with_dict选项不允许使用清单主机列表和字典。

如何为每个计算机/端口获取这一代 json 文件?

如果针对 logstash 主机运行 playbook,则可以使用 with_nested:

---
- hosts: logstash_hosts
tasks:
- name: Deploy HAZELCAST JMX config
template:
src: "hazelcast_jmx.json.j2"
dest: "{{ logstash_directory_jmx_hazelcast }}/hazelcast_jmx_{{ helper_host }}_{{ helper_cluster }}.json"
owner: "{{ logstash_system_user }}"
group: "{{ logstash_system_group }}"
mode: 0640
with_nested: 
- "{{ groups['HAZELCAST'] }}"
- "{{ logstash_hazelcast_jmx }}"
vars:
helper_host: "{{ item.0 }}"
helper_cluster: "{{ item.1.cluster }}"
helper_port: "{{ item.1.port }}"

我还使用了具有更有意义的名称的辅助变量。您还应该使用帮助程序 var 或item.0item.1修改模板,其中item.0是组中HAZELCAST主机,item.1logstash_hazelcast_jmx列表中的项目。

相关内容

  • 没有找到相关文章

最新更新