Search code examples
ansibleansible-inventoryansible-factsansible-template

ansible variables usage - ansible_hostname or {{ ansible_hostname }}


I am new to ansible. What is the correct to call ansible variables? Here are the 3 playbooks, playbook 1 uses "{{ ansible_hostname }}", however, playbook 2 and 3 uses "ansible_hostname" directly. What are the differences? Thanks!

Playbook 1:

  tasks:
    - name: Jinja2 template
      template:
        src: template.j2
        dest: "/tmp/{{ ansible_hostname }}_template.out"
        trim_blocks: true
        mode: 0644

Playbook 2:

  tasks:
    - name: Ansible Jinja2 if
      debug:
        msg: >
             --== Ansible Jinja2 if statement ==--
 
             {# If the hostname is ubuntu-c, include a message -#}
             {% if ansible_hostname == "ubuntu-c" -%}
                   This is ubuntu-c
             {% endif %}

Playbook 3:

  tasks:
    - name: Exploring register
      command: hostname -s
      when: 
        - ansible_distribution == "CentOS" 
        - ansible_distribution_major_version | int >= 8
      register: command_register

Solution

  • playbook 1 uses "{{ ansible_hostname }}", however, playbook 2 uses "ansible_hostname"

    That's not entirely correct. Both playbooks use the variable name ansible_hostname inside a Jinja templating context.

    • In the first playbook, it's simple variable substitution, so we use the {{ ... }} markers.

    • In the second playbook, it's being used in a control expression, so we use the {% ... %} markers.

    • In the third playbook, you're looking at the clauses of a when expression. From the documentation:

      The when clause is a raw Jinja2 expression without double curly braces...

    You can read more about Jinja syntax here.