EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Ansible Conditional

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » Ansible Tutorial » Ansible Conditional

ansible conditional

Introduction to Ansible Conditional

In Ansible, we mostly fetch and used at a from remote target nodes and then use this data to make the decision to execute play sort asks. Similarly results also depend on the value of variables passed to plays and tasks, facts fetched or created, or the results from past results. Many times this also works in a way where one variable’s value is dependent on another variable. So all these kinds of situations, are handled by Ansible conditionals. In Ansible, conditionals include when, loop, custom facts, register variables, and commonly used facts. In this article, we will try to cover these.

What is Ansible Conditional?

In Ansible, we have many useful features parameters that are not modules but can be used in tasks to specify a condition or pre-requisite to execute this task. These are basically the options to control the execution of a task or play. This is an important aspect as when working on many remote hosts, the conditions may vary like their Operating systems are different, in such cases, it becomes very important that only the tasks written for that particular condition must run on that else it will be ignored. This makes us not to break a system and successfully run our playbooks.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Below is the list of main conditionals which you will end you using in day to day operations.

  1. when
  2. loop and conditionals
  3. custom facts
  4. register variables
  5. conditional imports
  6. selecting files and templates based on variables
  7. Commonly used facts

We will learn these conditionals in the next section of this article.

How Does Ansible Conditionals Works?

To work with Ansible Conditionals, one must accustom herself of the keywords, which Ansible takes as acceptable values in playbooks. Also, the syntax part of using these conditionals is an important aspect to learn. Here in this section, we will see more details about the acceptable keywords and their use as conditionals.

1. When

This is used in situations where we need to run a task on a host or multiple hosts which satisfy the given condition or conditions. Also, where the specified condition does not match, the task will be skipped. The conditions given under when can be as simple as to check the operating system version or can be a bit complex where values of a Jinja2 template contained in a variable is checked.

Syntax:

- name: <some task>
command: <command to be executed> when: <condition to check>

Also, when we have more than one condition, then we can specify those like below:

Popular Course in this category
Ansible Training (1 Course, 4 Projects)1 Online Courses | 4 Hands-on Projects | 8+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (3,180 ratings)
Course Price

View Course

Related Courses
Linux Training Program (16 Courses, 3+ Projects)Kali Linux Training (3 Courses, 3+ Projects)Red Hat Linux Training Program (4 Courses, 1+ Projects)

tasks:
name: <some task>
command: <command to be executed> when:
<first condition to check>
<second condition to check>

Note below points as well, while using variables or when you want to use some math operations.

  • We do not need to use {{ }}, when specifying variables inside conditions, as these are already implicit.
  • When a mentioned variable is not set, you can pass or fail using Jinja2 defined test.
  • When fetching variables from remote target hosts. Then be cautious on the fact that the data generated on target hosts may be dependent on some package’s availability.

2. Loop and Conditionals

These are needed whenever we want to run a task against a list of items. The task will run in each host for all listed items separately. Loop can be used with The condition will be checked against each item in the list. Sample code will be like below:

Code:

tasks:
- command: <some command> loop: [ 1, 2, 3, 4 ] when: item > 3

we can also make use of jinja2 templates while using a dictionary or similar cases.

3. Custom Facts

This is used in cases when you have been fetching some data using a custom module. On the basis of that fetched data, we set the facts and use them in conditionals.

4. Register Variables

Most of the time in playbooks we store the output values into a variable and then later in playbook access this variable or a part of it to use in another task. Similarly, these registered variables can be used in templates, action lines, and conditionals to take decision.

Below is sample syntax for this which can be converted to actual.

Syntax:

- shell: <some command>register:<var_output>
shell: <some command based on registered variable> when: <condition checking register variable part>

5. Conditional Imports

Though this is not mostly used there are some cases when we need such features. A good example would be when you have different operating systems on remote target nodes. Sample code will be like below:-

Code:

---
hosts: webhost vars_files:
"vars/file_common.yaml"
[ "vars/{{ ansible_facts['os_family'] }}.yaml", "vars/defaults.yaml"] tasks:
- name: making httpd service in started state service: name={{ httpd }} state=started

Here in this sample variable httpd is defined in either of the files imported.

Now we will try to do some practical work in this section, by working on the same example. Here, in our test lab, we have a controller node named ansible–controller and two remote target machines named host- one and host-two.

Examples of Ansible Conditional

In this example, we have a playbook like below, where we will use some conditions based on registered variables and another condition.

Code:

---
hosts: all tasks:
name: Here we check whether OS is Redhat and print amsg shell: echo "This is a RHEL basedmachine"
when: ansible_distribution == "RedHat"
name: Here we check whether OS is Ubuntu and print amsg shell: echo "This is a Ubuntu basedmachine"
when: ansible_distribution == "Ubuntu"

Running this playbook will give output like below where we can see that when a condition is true, then accordingly output message is printed. Also, we are using -v to make it to give output in verbose mode.

Ansible Conditional Example

Conclusion

As you can see in this article, Ansible conditionals are very useful in situation-based playbooks. So are our production environments mostly. So having sound knowledge of Ansible conditionals make you competent in writing complex playbooks where we have data dependency on many other conditions. So learn it first and then use it.

Recommended Article

This is a guide to Ansible Conditional. Here we discuss What is Ansible Conditional and its syntax along with examples as well as code implementation. You can also go through our other suggested articles to learn more –

  1. Introduction to Ansible Commands
  2. Terraform vs Ansible – Top Differences
  3. Top 10 Ansible Interview Questions
  4. Ansible Filters | How to Work?

Ansible Training (1 Course)

1 Online Courses

4 Hands-on Projects

8+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

1 Shares
Share
Tweet
Share
Primary Sidebar
Ansible Tutorial
  • Ansible Basics
    • What is Ansible
    • Is Ansible free
    • How to Install Ansible
    • Ansible Versions
    • Ansible Architecture
    • Ansible Commands
    • Ansible ad-hoc Commands
    • Ansible Playbooks
    • Ansible Roles
    • Ansible Tags
    • Ansible Ping
    • Ansible Apt
    • Ansible Facts
    • Ansible Tower
    • Ansible Galaxy
    • Ansible Handlers
    • Ansible Loop
    • Ansible Block
    • Ansible Conditional
    • Ansible YAML
    • Ansible Debug
    • Ansible Synchronize
    • Ansible Template
    • Ansible group_vars
    • Ansible Lookup
    • Ansible File Module
    • Ansible Yum Module
    • Ansible Shell Module
    • Ansible lineinfile
    • Ansible Service Module
    • Ansible User Module
    • Ansible Windows Modules
    • ansible-doc
    • Ansible Filters
    • Ansible Add User to Group
    • Ansible Register
    • Ansible Set Fact
    • Ansible Hosts File
    • Ansible add_host
    • Ansible Collections
    • Ansible with_items
    • Ansible Replace Line in File
    • Ansible inventory_hostname
    • Ansible Dynamic Inventory
    • Ansible local_action
    • Ansible Firewalld
    • Ansible Unarchive
    • Ansible Sudo
    • Ansible Create Directory
    • Ansible Reboot
    • Ansible wait_for
    • Ansible run_once
    • Ansible Authorized_key
    • Ansible Interview Questions

Related Courses

Linux Training Course

Kali Linux Training

Red Hat Training Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Ansible Training (1 Course) Learn More