Reputation: 131
I'm using ansible to build some swatch conf files, trying to make it as flexible as possible to allow for different actions. I'm stuck on a nested loop in the .j2 file. I have the Ansible vars like so:
swatch_files:
- name: 'syslog'
tail: '/var/log/syslog'
watchfor:
-
string: 'Stupid FIrst String'
actions:
-
action: "1/2 Slack blah blah action"
threshold: "Threshold For This first Action"
actions:
-
action: "2/2 Slack blah blah action"
threshold: "Threshold For This second Action"
-
string: 'Crappy Second String'
actions:
-
action: "1/2 Slack blah blah action"
threshold: "Threshold For This 1 Action"
actions:
-
action: "2/2 Slack blah blah action"
threshold: "Threshold For This 2 Action"
The task does indeed create the file:
- name: Swatch | Create the Monit swatch conf files template:
src="swatch.monit.j2"
dest="/etc/monit/conf.d/{{ item.name }}.conf"
owner=root
group=root
mode=0700 with_items: swatch_files tags:
- monit
And my swatch.conf.j2 file looks like this:
{% for watchfor in item.watchfor recursive %}
watchfor /{{ watchfor.string }}/
{% for actions in watchfor.actions %}
Action: {{ actions.action }}
Threshold: {{ actions.threshold }}
{% endfor %}
{% endfor %
But my /etc/swatch/syslog.conf ends up like this:
watchfor /Stupid FIrst String/
Action: 2/2 Slack blah blah action
Threshold: Threshold For This second Action
watchfor /Crappy Second String/
Action: 2/2 Slack blah blah action
Threshold: Threshold For This 2 Action
It goes through the {% for watchfor in item.watchfor recursive %} loop fine, but then I have the {% for actions in watchfor.actions %} wrong somehow. It ends up only writing the second action and threshold. I assume it overwrites the first?
Upvotes: 1
Views: 1329
Reputation: 60059
Looks like a pure YAML problem. You are overriding the key actions
in your dict:
watchfor:
-
string: 'Stupid FIrst String'
actions:
-
action: "1/2 Slack blah blah action"
threshold: "Threshold For This first Action"
actions:
-
action: "2/2 Slack blah blah action"
threshold: "Threshold For This second Action"
If your actions
list should have multiple items it should look like this:
watchfor:
- string: 'Stupid FIrst String'
actions:
- action: "1/2 Slack blah blah action"
threshold: "Threshold For This first Action"
- action: "2/2 Slack blah blah action"
threshold: "Threshold For This second Action"
Upvotes: 1