| 1. |
When Should I Use {{ }}? Also, How To Interpolate Variables Or Dynamic Variable Names? |
|
Answer» A STEADFAST rule is ‘always USE {{ }} except when when:‘. Conditionals are always run through Jinja2 as to resolve the expression, so when: failed_when: and changed_when: are always templated and you should avoid adding {{}}. In most other cases you should always use the brackets, even if previouslly you could use variables without specifying (like with_ clauses), as this MADE it hard to distinguish between an UNDEFINED variable and a string. Another rule is ‘moustaches don’t stack’. We often see this: {{ somevar_{{other_var}} }} The above DOES NOT WORK, if you need to use a dynamic variable use the hostvars or vars DICTIONARY as appropriate: {{ hostvars[inventory_hostname]['somevar_' + other_var] }} A steadfast rule is ‘always use {{ }} except when when:‘. Conditionals are always run through Jinja2 as to resolve the expression, so when: failed_when: and changed_when: are always templated and you should avoid adding {{}}. In most other cases you should always use the brackets, even if previouslly you could use variables without specifying (like with_ clauses), as this made it hard to distinguish between an undefined variable and a string. Another rule is ‘moustaches don’t stack’. We often see this: {{ somevar_{{other_var}} }} The above DOES NOT WORK, if you need to use a dynamic variable use the hostvars or vars dictionary as appropriate: {{ hostvars[inventory_hostname]['somevar_' + other_var] }} |
|