Skip to content

Example 3

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: >
          {# This is a comment in Jinja2 -#}
          {% if ansible_distribution == "CentOS" -%}
            This is one of CentOS VMs - {{ ansible_hostname }}
          {% else -%}
            This is one of Ubunut VMs - {{ ansible_hostname }}
          {% endif %}

Tip

Jinja2 blocks can be combined with internal Ansible variables to match more complex scenarios.

Execute the following command

ansible-playbook playbook.yml