我是ansible的新手,我想为运行cacti应用程序的所有节点部署prometheus-grok-exporter (通过ansible-grok-exporter角色),并使用特定的配置。
我的清单是这样的:
cacti_first ansible_host=192.168.50.50
cacti_second ansible_host=192.168.50.51
[group__cacti]
cacti_first
cacti_second
在group_vars/group__cacti
中,我想添加如下内容:
---
prometheus_grok_services_template:
- name: cacti_metrics
config_version: 3
input:
type: file
paths:
{% for cacti_dir in cacti_path %}
- "{{cacti_dir}}/log/cacti.log"
{% endfor %}
readall: false
extaConfigContinuesFromHere: true
我的主机配置如下:host_vars/cacti_first
---
cacti_path:
- /usr/share/cacti
prometheus_grok_services:
- prometheus_grok_services_template
host_vars/cacti_second
---
cacti_path:
- /usr/share/cacti
- /usr/share/cacti2
prometheus_grok_services:
- prometheus_grok_services_template
在攻略中,我为prometheus_grok_services
做了一个循环,并使用yaml数据来提供服务。
现在-只要我不试图在group_vars/group__cacti
中使用循环,这个方法就可以工作。ansible-inventory报告:
$ ansible-inventory -i hosts --list cacti_second
ERROR! Syntax Error while loading YAML.
found character that cannot start any token
The error appears to be in '/home/bastion/ansible-playbooks/group_vars/group__cacti': line 8, column 10, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
paths:
{% for cacti_dir in cacti_path %}
^ here
那么,我想问一下--允许使用jinja循环来为group vars构建yaml吗?这是我这一端的语法错误吗?我该如何模版它呢?
我希望避免将块移动到托管vars (我知道这是可行的),主要是因为它是一段很大的代码(大约2KB的yaml配置),而且它没有使用group var那么优雅。
谢谢!
发布于 2021-06-02 23:00:28
修复group_vars。例如
shell> cat group_vars/group__cacti
---
prometheus_grok_services_template:
- name: cacti_metrics
config_version: 3
input:
type: file
paths: "{{ paths_str|from_yaml }}"
readall: false
extaConfigContinuesFromHere: true
paths_str: |
{% for cacti_dir in cacti_path %}
- {{ cacti_dir }}/log/cacti.log
{% endfor %}
然后,攻略
- hosts: group__cacti
gather_facts: false
tasks:
- debug:
msg: "{{ lookup('vars', item) }}"
loop: "{{ prometheus_grok_services }}"
给出
ok: [cacti_first] => (item=prometheus_grok_services_template) =>
msg:
- config_version: 3
input:
extaConfigContinuesFromHere: true
paths:
- /usr/share/cacti/log/cacti.log
readall: false
type: file
name: cacti_metrics
ok: [cacti_second] => (item=prometheus_grok_services_template) =>
msg:
- config_version: 3
input:
extaConfigContinuesFromHere: true
paths:
- /usr/share/cacti/log/cacti.log
- /usr/share/cacti2/log/cacti.log
readall: false
type: file
name: cacti_metrics
发布于 2021-06-02 22:51:03
您不能在变量文件或剧本中使用这种for循环-它只在模板文件中有效。要获得您想要的内容,您可以使用产品过滤器,如https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#products所述
在您的示例中,您将拥有:
---
prometheus_grok_services_template:
- name: cacti_metrics
config_version: 3
input:
type: file
paths: "{{ cacti_path | product(['/log/cacti.log']) | map('join') | list }}"
readall: false
extaConfigContinuesFromHere: true
https://stackoverflow.com/questions/67804918
复制相似问题