Skip to main content

Defining Tasks in Ansible

Introduction

Tasks in Ansible are like instructions that you give to your system. They define the work that gets executed on each machine when you run your playbook. In this article, we will explore how to define tasks in Ansible, their structure, and some of the most common modules used within tasks.

Ansible Tasks Structure

In Ansible, tasks are defined inside a playbook, which is a YAML file. The basic structure of a task is as follows:

tasks:
- name: This is a task
module:
key: value

The 'name' is optional, but it's a good practice to include it as it makes your code more readable. The 'module' is the operation you want to perform, and the 'key: value' pairs are the arguments to the module.

Defining a Task

Let's define a simple task that installs the 'httpd' package on a CentOS operating system.

tasks:
- name: Install httpd
yum:
name: httpd
state: present

In this example, yum is the module used to manage packages in CentOS. We are telling Ansible to ensure that the 'httpd' package is present on the system.

Common Modules in Ansible

There are many modules available in Ansible, and you can even write your own. Some of the most common ones include:

  • command and shell: These modules allow you to execute commands in the target machine.
  • copy: This module allows you to copy files from the local machine to the target machine.
  • file: This module is used to manage file properties like permissions, ownership, and links.
  • apt and yum: These modules are used to manage packages in Debian and CentOS respectively.

Here is an example of using the 'file' module to create a directory:

tasks:
- name: Create a directory
file:
path: /path/to/directory
state: directory

Task Control

Ansible also allows you to control the execution of tasks using conditional statements, loops, and handlers.

  • when: This keyword allows you to execute a task based on a condition.
tasks:
- name: Install httpd
yum:
name: httpd
state: present
when: ansible_os_family == "CentOS"
  • loop: This keyword allows you to execute a task multiple times.
tasks:
- name: Install multiple packages
yum:
name: "{{ item }}"
state: present
loop:
- httpd
- vim
  • notify and handlers: These keywords allow you to trigger tasks based on the result of a task.
tasks:
- name: Install httpd
yum:
name: httpd
state: present
notify: Restart httpd

handlers:
- name: Restart httpd
service:
name: httpd
state: restarted

Conclusion

Defining tasks is a fundamental part of writing Ansible playbooks. This guide has covered the basic structure of a task, some common modules, and task control keywords. Practice defining your own tasks and using different modules to become more comfortable with Ansible.