How To Define Tasks in Ansible Playbooks

Configuration ManagementAnsible
Part of the Series: How To Write Ansible Playbooks

Ansible is a modern configuration management tool that doesn’t require the use of an agent software on remote nodes, using only SSH and Python to communicate and execute commands on managed servers. This series will walk you through the main Ansible features that you can use to write playbooks for server automation. At the end, we’ll see a practical example of how to create a playbook to automate setting up a remote Nginx web server and deploy a static HTML website to it.

A task is the smallest unit of action you can automate using an Ansible playbook. Playbooks typically contain a series of tasks that serve a goal, such as to set up a web server, or to deploy an application to remote environments.

Ansible executes tasks in the same order they are defined inside a playbook. Before automating a procedure such as setting up a LEMP server, you’ll need to assess which manual steps are necessary and the order in which they must be completed to get everything done. Then, you’ll be able to determine which tasks you’ll need and which modules you can use to reach your goals in less steps.

Modules offer shortcuts to execute operations that you would otherwise have to run as raw bash commands. These are also often used to abstract commands across different operating systems.

When you created your first playbook in a previous part of this guide, you defined a single task that outputs a message using debug. Let’s have a look at that playbook once again. You can use the cat command to print the contents of that file for examination:

  • cat ~/ansible-practice/playbook-01.yml

This playbook contains a single task that prints a message in the output of a play:

- hosts: all
    - name: Print message
        msg: Hello Ansible World

Tasks are defined as a list under the name tasks inside a play, at the same level as the hosts directive that defines the targets for that play. The name property defines the output that will be printed out when that task is about to be executed.

The example task invokes the debug module, which allows you to display messages in a play. These messages can be used to show debug information such as the contents of a variable or the output message returned by a command, for instance.

Each module has its own set of options and properties. The debug module expects a property named msg containing the message to be printed out. Pay special attention to the indentation (2 spaces), since msg must be a property inside debug.

Creative Commons License