Python

How to Do an If-Statement in Jinja2

Various pre-constructed conditionals in Jinja2 provide quick access to advanced methods on Jinja documents. The purpose of implementing the Jinja2 conditionals in Ansible is explained in this article, along with what they are in general. This article also has a detailed if-statement for one of the Jinja2 conditionals and what the Jinja2 document if-statement syntax and functionality is. We’ll also go over a different operator that the Ansible programmers can use to perform the if-statements.

Among the most effective and well-known Python-based documents is Jinja2. Since this uses the same coding languages as Ansible, it is most widely used by Ansible users. This is one of the benefits for IT professionals in countless ways. The Jinja2 document can employ the Ansible conditional structures. Whenever a Boolean condition that is supplied by the developer translates to either true or false, distinct operations or activities are carried out by conditional statements. Inside an Ansible playbook, based on the information about the target server, an if-statement, or the outcome of a previous action, you might want to run some alternative actions or have different aims. The fundamental structure element that is used to assess the conditions is the “if” expression. When evaluating multiple conditions, the “if” expression is frequently used during combination with both the “elif” and “else” commands. If a parameter occurs and is not null or if the parameter has the Boolean expression as “True”, a conditional if-statement with an input parameter translates to true. In simpler explanation, the “if” expression is used to restrict the execution of a collection of statements two times when a particular condition is met.

Syntax of the “If” Condition in Jinja2

Jinja2, despite not being a language of programming, has a list of phrases that you must employ to put the “script” in the Ansible playbook. These are simply collectively referred to as syntax, and they’re structured by a series of basic principles that lets the users communicate their goals to the machine in the terms that it can understand.

We start by using a curly open brace with a percentage indicator. The “if” keyword, a reserved word in Jinja2, is used. After writing any conditions or expressions, we close the if-statement line once more with the percent symbol and close the curly brace. Then, in the next line, the “if” condition’s body is written. Finally, the condition is closed by writing “endif” inside the if-statement’s opening and closing tags. If the specified condition returns true, the statements that are included in the “if” block of the code are executed. If the condition is false, it returns false.

{% if (condition) %}
    Body
{% endif %}

Prerequisites of Utilizing the If-Statement in Jinja2

To quickly configure the Jinja2 if-statement in Ansible, we consider, for the sake of this session, that we comply with the following criteria:

  • To perform the tasks in Ansible, we should first set up the Ansible tool on the system.
  • The Jinja2 if-statement whole operation is handled by the Ansible controller in this session, which acts as the primary domain controller which sets up and maintains the jinja2 conditionals on the targeted machine.
  • In addition, a targeting server is necessary where the Jinja2 if-statement is configured. The remote server in this instance is determined to be the local host.

Let’s begin with a quick practice run of the Jinja2 if-statement from the Ansible Playbook.

Example: Implementation of the If-Statement

Now, using the if-statement of Jinja, which is based on Python programming, we create the basic example in Ansible. We need a playbook to include all of the commands, tasks, and Jinja2 conditionals that we need to implement in Ansible. The Ansible terminal command that we use to construct the playbook is shown in the following:

[root@master ansible]# nano ansible_if.yml

After entering the aforementioned command, a playbook with the “.yml” extension and the “if.yml” identifier Ansible are produced and launched instantly in a new tab of the Ansible tool interface. Now that the conditional if-statement is implemented, let’s begin creating the necessary commands. To implement the if-statement in the remote host device, we first specify the target remote host in the playbook. We provide the local host throughout this situation. The gathering of information in the Ansible option is employed to receive the data about the local host. Thus, if the true Boolean value is passed to the option, we obtain all information that are relevant to the local host. However, we supply a false Boolean value if all that appears in the output terminal are the name of the remote host and not any other information about the local host when the playbook is executed. After giving the relevant information to the local host, we then define the operations that we like to accomplish in the if-statement playbook.

First, we define the task in which we want to check the availability of the document in Ansible. Then, we pass the path of the document and register it. Next, we execute and print the results using the debug option. Then, we utilize the if-statement to check whether the file is available or not. In the next task, we check whether the “host.yml” is accessible by the current Ansible controller or not. So, we use the shell option to declare the path of the “host.yml” document Ans through the register variable where we pass the access to the “host.yml” document. Then, we use the if-statement to check the “if” condition.

- hosts:
    - localhost
  gather_facts: false

  tasks:
    - name: Check file existance
      stat: path=./host.yml
      register: fileExists

    - debug:
        msg: "{{ 'File exists' if fileExists.stat.exists}}"

    - name: Check if host.yml is accessible by current user
      shell: stat -c "%a" ./host.yml
      register: accessPath

    - debug:
        msg: "{{ 'File accessible' if (accessPath.stdout|int) < 660}}"

Then, we execute the playbook in Ansible. We write the following command to get the desired outcomes:

[root@master ansible]# ansible-playbook ansible_if.yml –i host.yml

As you can see, the conditional if-statement is executed successfully. In the first task, the “host.yml” document exists in Ansible, and we successfully accessed the “host.yml” file.

Conclusion

We used one of the conditionals of Jinja2 in Ansible which is the if-statement. We discussed the writing style of the if-statement in Jinja2 and learned the requirements that must be configured in the control host and remote host devices. We implemented an example of the Jinja2 if-statement in Ansible so that we can easily configure the statement.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content