Skip to content

Example 4

hosts.yml

centos:
  hosts:
    provisioner:
      ansible_connection: local
    centos1:
      ansible_host: '192.168.77.22'
ubuntu:
  hosts:
    ubuntu1:
      ansible_host: '192.168.77.23'

playbook.yml

- hosts: all
  tasks:
    - name: Jinja2 if/else statement
      debug:
        msg: >
          {% set some_var = 'some_value' -%}
          {# This is a comment in Jinja2 -#}
          {% if some_var is defined -%}
            some_var is defined
          {% else -%}
            some_var is not_defined
          {% endif %}

Tip

Jinja2 allows the user to set task-scoped vars.

Execute the following command

ansible-playbook playbook.yml

Bonus round

Check how Jinja2 deals with playbook-scoped vars by modyfing the playbook.