Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ansible - example of template if else
{# style 1 - long form #}
{% if filepath == '/var/opt/tomcat_1' %}
{% set tomcat_value = tomcat_1_value %}
{% else %}
{% set tomcat_value = tomcat_2_value %}
{% endif %}
{# style 2 - short form #}
{% set tomcat_value = tomcat_1_value if (filepath == '/var/opt/tomcat_1') else tomcat_2_value %}
{# style 3 - with ternary filter #}
{% set tomcat_value = (filepath == '/var/opt/tomcat_1')|ternary(tomcat_1_value, tomcat_2_value) %}
<Server port={{ tomcat_value }} shutdown="SHUTDOWN">
---
- hosts: foo
vars:
tomcat_1_value: 'bob'
tomcat_2_value: 'bar'
tasks:
# style 1 using filter
- set_fact:
tomcat_value: "{{ (filepath == '/var/opt/tomcat_1') | ternary(tomcat_1_value, tomcat_2_value) }}"
# style 2
- set_fact:
tomcat_value: "{{ tomcat_1_value if (filepath == '/var/opt/tomcat_1') else tomcat_2_value }}"
- template:
...
<Server port={{ tomcat_value }} shutdown="SHUTDOWN">
@rimiti

This comment has been minimized.

Copy link

@rimiti rimiti commented Jun 14, 2017

Thanks for sharing ;)

@Dmitri10

This comment has been minimized.

Copy link

@Dmitri10 Dmitri10 commented Sep 22, 2017

Indeed! Thank you

@racingferret

This comment has been minimized.

Copy link

@racingferret racingferret commented Sep 25, 2017

FYI, the set statement only needs one "=", not "==". Thanks for sharing!

@XDanny322

This comment has been minimized.

Copy link

@XDanny322 XDanny322 commented Jul 12, 2018

Good stuff - Thank you sir!

@bovito

This comment has been minimized.

Copy link

@bovito bovito commented Jul 17, 2018

Thank you!

@Marwan-Gh

This comment has been minimized.

Copy link

@Marwan-Gh Marwan-Gh commented Feb 19, 2019

thanks for sharing

@sagespidy

This comment has been minimized.

Copy link

@sagespidy sagespidy commented Dec 16, 2019

Thanks . you are awesome

@vi2co

This comment has been minimized.

Copy link

@vi2co vi2co commented Mar 21, 2020

Thanks!

@daretogo

This comment has been minimized.

Copy link

@daretogo daretogo commented Aug 11, 2020

👍 Thanks again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.