1

I have a template in Ansible to make a config file for Prometheus. I would like to add hosts dynamically, using variable prometheus_hosts. This variable is defined in host_vars per each host, but Ansible has probably some problem with the template.

Variable is set like: prometheus_hosts: [ host1, host2, host3 ]

The template

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 %}

The Error

fatal: [test-mw]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'ansible.parsing.yaml.objects.AnsibleUnicode object' has no attribute 'name'"} to retry, use: --limit @/home/gitlab-runner/builds/xw_vGpUQ/0/ansible/middleware/middleware.retry

Do you have any idea how to fix it? Thank you!

1 Answer 1

1

In the expression

 {% for host in prometheus_hosts if host.name.startswith('edge') %}

"host" is an item from the list "prometheus_hosts". The items in this list have no attributes "name". This is the reason for the error

"msg": "AnsibleUndefinedVariable: 'ansible.parsing.yaml.objects.AnsibleUnicode object' has no attribute 'name'


It is possible to use Testing strings. For example

{% for host in my_hosts %}
{% if host is regex('^edge(.*)$') %}
1
  • Thank you so much! Didn't see that.
    – Netheme
    Commented Aug 23, 2019 at 7:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .