Search code examples
ansiblejinja2monit

Does Ansible Jinja2 Templating support list arguments in for loop?


I'm trying to dynamically create a template from a list and I'm wondering if Ansible supports something like

{% for server in [sg-bend1, sg-bend2] %}
check program {{ server }}_test
  with path /home/ubuntu/t.sh {{ server }}
  if status != 0 then alert
{% endfor %}

theoretically this should produce

check program sg-bend1_test
  with path /home/ubuntu/t.sh sg-bend1
  if status != 0 then alert

check program sg-bend2_test
  with path /home/ubuntu/t.sh sg-bend2
  if status != 0 then alert

Solution

  • According the provided description I understand your question is related to Jinja2 Templating and syntax only.

    One approach you could try is the following

    {% for i in range(1,3) %}
    check program sg-bend{{ i }}_test
      with path /home/ubuntu/t.sh sg-bend{{ i }}
      if status != 0 then alert
    {% endfor %}
    

    Similar Q&A

    Documentation

    As far as I understand the documentation the solution should be to provide the list in a variable

    {% for SERVER in SERVERS %}`
    

    or an other syntax

    {% for SERVER in ('test1', 'test2') %}
    

    Example

    ---
    - hosts: localhost
      become: false
      gather_facts: false
    
      vars:
    
        SERVERS: ['test1', 'test2']
    
      tasks:
    
      - name: Show result
        debug:
          msg: "{% for SERVER in SERVERS %}{{ SERVER }}{% endfor %}"
    
      - name: Show result
        debug:
          msg: "{% for SERVER in ('test1', 'test2') %}{{ SERVER }}{% endfor %}"
    

    will result into an output of

    TASK [Show result] ******
    ok: [localhost] =>
      msg: test1test2
    
    TASK [Show result] ******
    ok: [localhost] =>
      msg: test1test2