In the post Handy Ansible Logic I described a situation where moving ansible logic out of when:
statement and into an inline Jinja achieved a much cleaner solution. Recently, I had a similar situation where I needed to extend what I was doing in the Jinja. This time, I needed to dynamically construct the a variable to pass into a modules parameter.
1
2
3
4
5
6
7
8
9
- name: Example 1 - Set facts
set_fact:
output: >-
{%- set output_list = [] -%}
{%- for server in ip_list -%}
{%- set my_server = {'name': server.name, 'type': 'IPv4'} -%}
{{ output_list.append( my_server ) }}
{%- endfor -%}
{{ output_list }}
Recently I was writing what initially looked like a pretty straight forward ansible play. Everything was progressing quite well until I came to a point where I needed to set one variable, only when another variable was set. My first pass at this logic was to repeat the task, and control which task was run with a when:
statement. This worked, but just wasn’t ideal with all of the duplicated code. I just knew there had to be a better way and there was.