When to use {{}} ? How to interpolate variables or dynamic variable names?

devquora
devquora

Posted On: Feb 22, 2018

 

  • 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 templates and you should avoid adding {{}}.
  • It is always recommended to use brackets even if you have previously used variables without specifying (like with_clauses). This makes it hard to distinguish between a string and an undefined variable.
  • 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] }}

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Ansible interview questions

    What is Ansible?

    Ansible is an open source automation platform which can help you with configuration management, task automation and appl..

    Ansible interview questions

    Talk about Ansible architecture.

    Ansible works on ‘agentless architecture’. It works by connecting to your nodes and pushes out Ansible modules to th..

    Ansible interview questions

    List some advantages of using Ansible.

    Unlike other configuration management system, Ansible is the most sought after software applications these days. it off..