我在 Ansible 中有一個模板可以為 Prometheus 製作設定檔。我想使用變數動態新增主機prometheus_hosts
。該變數在每個主機的 host_vars 中定義,但 Ansible 的模板可能存在一些問題。
變數設定如下:prometheus_hosts: [ host1, host2, host3 ]
範本
global:
scrape_interval: 15s
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'prometheus'
scrape_interval: 5s
static_configs:
- targets: ['localhost:9090']
{% if prometheus_hosts is defined %}
{% for host in prometheus_hosts %}
- job_name: '{{ host }}'
scrape_interval: 5s
static_configs:
- targets: ['{{ host }}:9100']
{% endfor %}
- job_name: 'mysql'
scrape_interval: 5s
static_configs:
- targets: ['localhost:9104']
- job_name: 'redis'
scrape_interval: 5s
static_configs:
- targets: ['localhost:9121']
{% for host in prometheus_hosts if host.name.startswith('edge') %}
- job_name: '{{ host }}_varnish'
scrape_interval: 5s
static_configs:
- targets: ['{{ host }}:9131']
{% endfor %}
{% endif %}
錯誤
致命:[test-mw]:失敗! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'ansible.parsing.yaml.objects.AnsibleUnicode object' has no attribute 'name'"} 若要重試,請使用: --limit @/home/ gitlab-跑者/builds/xw_vGpUQ/0/ansible/middleware/middleware.retry
您知道如何修復它嗎?謝謝你!
答案1
在表達式中
{% for host in prometheus_hosts if host.name.startswith('edge') %}
「host」是清單「prometheus_hosts」中的一項。此清單中的項目沒有屬性「名稱」。這就是錯誤的原因
"msg": "AnsibleUndefinedVariable: 'ansible.parsing.yaml.objects.AnsibleUnicode 物件'沒有屬性'名稱'
可以使用測試字串。例如
{% for host in my_hosts %}
{% if host is regex('^edge(.*)$') %}