Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable in default filter in Ansible Jinja2 template

Tags:

ansible

Inside a an Ansible Jinja2 template I'm trying to set a "default" value which also has a variable in it but it's printing out the literal rather than interpolating it.

For example:

homedir = {{ hostvars[inventory_hostname]['instances'][app_instance]['homedir'] | default("/home/{{ app_instance }}/airflow") }}

returns:

airflow_home = /home/{{ app_instance }}/airflow

How to refer to the app_instance variable?

like image 848
sebastian wth Avatar asked Jun 11 '18 02:06

sebastian wth


People also ask

Which filter is used to provide default values to variables Ansible?

So if you want to define a default value for a variable you should set it in role/defaults/main.

What character is used to denote use of a Jinja filter on a Ansible variable?

Jinja2 filter is something we use to transform data held in variables. We apply filters by placing pipe symbol | after the variable followed by name of the filter. Filters can change the look and format of the source data, or even generate new data derived from the input values.

Does Ansible use Jinja2 template?

Ansible uses Jinja2 templating to enable dynamic expressions and access to variables and facts.


1 Answers

Inside Jinja2 expression use Jinja2 syntax. You should concatenate strings to a variable value:

homedir = {{ hostvars[inventory_hostname]['instances'][app_instance]['homedir'] | default("/home/" + app_instance + "/airflow") }}
like image 111
techraf Avatar answered Nov 12 '22 14:11

techraf