Ansible template loop with iteritems

Hi,

I would like to create dynamically some configuration files (the configs are used by tomcat) using a template based some variables from group_vars

Below is what I have

  • group_vars/test.yml

file:

  • log4j
  • config

log4j:
log4j.rootCategory: INFO
log4j.appender.SYSLOG: org.apache.log4j.net.SyslogAppender
log4j.appender.SYSLOG.syslogHost: testhost

jira:
jira.soap.url: https://hostname
jira.login.username: test
jira.login.password: test14

  • roles/test/main.yml

  • name: ‘Configure the application properties’
    template:
    src: “template.j2”
    dest: “/tmp/{{ item }}.properties”
    owner: build
    group: build
    backup: yes
    with_items: “{{ file }}”

  • roles/test/template/template.j2

{% for key, value in {{ item.iteritems() }} %}
{{ key }}= {{ value }}
{% endfor %}

So I would like to iterate every “file” and to create the files
I’m receiving “msg”: “AnsibleError: template error while templating string: expected token ‘:’, got ‘}’. String: ## File managed by ansible ##\n\n{{ item }}\n{{ propertyfiles }}\n\n{% for i in {{ propertyfiles }} %}\n {% for key, value in i.items() %}\n {{ key }}= {{ value }}\n {% endfor %} \n{% endfor %} \n”}

You are already in jinja template mode between {% %} so you can't use {{ }} there.

{% for key, value in item.iteritems() %}

I’m receiving the folllowing error “msg”: “AnsibleUndefinedVariable: ‘ansible.utils.unsafe_proxy.AnsibleUnsafeText object’ has no attribute ‘iteritems’”}

I didn't look at what you where trying to do I just saw the syntax error.

But I see what you are trying to do, I'm not sure but maybe this work

{% for key, value in vars[item].iteritems() %}

Works, thank you for your help.

I have another question, after I applied the changes, now every line in the files contains a new empty line. It is possible to be removed ?

{% for key, value in vars[item].iteritems()| sort %}
{{ key }}= {{ value }}
{% endfor %}

log4j.appender.MAIN_APPENDER= org.apache.log4j.RollingFileAppender

log4j.appender.MAIN_APPENDER.File= /tmp/log4j.log

log4j.appender.MAIN_APPENDER.MaxBackupIndex= 5

I don't know why since you shouldn't unless you input contain extra whitespaces.

You can try to use {%- and/or -%} to remove whitespaces, more on the subject here
http://jinja.pocoo.org/docs/2.10/templates/#whitespace-control

Thank you Kai for all the support, works OK