Skip to main content

Task Control

In Ansible, tasks are the fundamental building blocks of playbooks. They are simple, declarative instructions that tell Ansible what to do. In this article, we'll delve into task control in Ansible. We'll cover conditional statements, loops, and error handling - elements that will give you a greater degree of control over how your tasks are executed.

Conditional Statements in Ansible

Often, we need tasks to be executed only when certain conditions are met. In Ansible, we use conditional statements to control the execution of tasks.

The 'when' Statement

The 'when' statement is used to define the condition under which a task will run. If the condition is met (returns true), the task will execute. Here is an example:

- name: Check if file exists
ansible.builtin.stat:
path: /etc/foo.conf
register: result

- name: Display message if file exists
ansible.builtin.debug:
msg: "/etc/foo.conf exists"
when: result.stat.exists

In the above example, the 'debug' task will only run when the file '/etc/foo.conf' exists.

Looping in Ansible

Looping is used to execute a task multiple times. Ansible offers several ways to use loops, but the simplest is the 'loop' keyword.

The 'loop' Keyword

Here's how to use 'loop' in a task:

- name: Create multiple users
ansible.builtin.user:
name: "{{ item }}"
state: present
loop:
- "user1"
- "user2"
- "user3"

In this example, the 'user' task will run three times, each time with a different value for 'name'.

Error Handling in Ansible

Ansible tasks stop execution and fail by default when errors occur. However, Ansible provides several ways to handle errors.

The 'ignore_errors' Keyword

If you want your playbook to continue executing even when a task fails, use the 'ignore_errors' keyword:

- name: This might fail
ansible.builtin.command: /bin/false
ignore_errors: yes

In this example, the playbook will continue to run even if the 'command' task fails.

Conclusion

Task control in Ansible is all about conditionally executing tasks, iterating over sequences of values with loops, and managing errors. Mastering these aspects of Ansible can help you create more flexible and resilient playbooks.

Remember, the best way to understand these concepts is by using them. So go ahead, start writing your tasks and playbooks, and see these principles in action!