Ansible Playbook: How to Create and Configure Playbooks

Introduction

Ansible is an Infrastructure as Code tool that lets you manage and monitor a number of remote servers by using a single control node.

With Ansible, you can manage remote servers by using playbooks. These playbooks relay instructions to remote servers and allow them to execute predefined tasks.

In this tutorial, we will go over what Ansible playbooks are, how they work, and how you can create and execute them.

Ansible playbook: how to create and configure playbooks

Prerequisites

  • A Linux system (we are using Ubuntu 20.04)
  • Access to the command line / terminal window
  • Ansible installed and configured

What is an Ansible Playbook?

An Ansible playbook is a list of instructions for jobs that are automatically executed by remote computers in an Ansible network.

Note: If you don’t already have Ansible installed, check our guides on installing Ansible on Ubuntu and Windows.

An Ansible playbook consists of plays. Plays are orchestrated set of tasks that are completed once a playbook is executed. You can add multiple plays to one playbook.

Plays use modules to define which changes need to be made to complete a task. Each module provides a framework for a certain category of jobs and can be customized using arguments and variables.

Ansible playbooks are saved as .yaml files, which makes them flexible and easy to use.

Playbooks are mostly used for:

  • Declaring configurations.
  • Automating certain repeatable tasks that would take too long to do manually.
  • Launching tasks synchronously or asynchronously.

Ansible Playbook Variables

Ansible playbooks use variables to provide flexibility and ease of use. Variables can be built-in (such as system information) or user-defined.

Note: All variable names in Ansible must start with a letter or underscore and cannot contain any spaces. Numbers are permitted.

In an Ansible playbook, variables are defined by using the vars keyword:

Using the vars keyword to define variables

In the example above, we define the greeting variable with the assigned value of Hello World!.

To access the value, put the variable name greeting in double curly brackets:

Accessing the value of a variable

Once executed, the playbook prints out the message Hello World!

Executing the playbook with a variable

Aside from variables with a single value, there are several other types of Ansible variables. Using variables with arrays, assign multiple values to one variable with the following syntax:

vars:
  array_name:
    - value1
    - value2
    …
    - valueN

Access a specific value by using {{ array_name[value number] }}, for instance:

Accessing values of a variable with array

Important: Array values are numbered starting with zero, so always choose one number lower than the one you want to access.

Variables with dictionaries combine multiple arrays of values into a single variable:

vars:
  array_name:
    dictionary_name1:
      item1: value1
      item2: value2
    dictionary_name2:
      item1: value1
      item2: value2

Finally, special variables are predefined by Ansible and can’t be set by users. Use the following command to get a list of special variables:

ansible -m setup hostname

How to Write an Ansible Playbook?

Create an Ansible playbook by using any text editor available on your system. For instance, create a playbook with Nano:

sudo nano /path/to/playbook/directory/playbook_name.yaml

Ansible playbooks follow basic YAML syntax rules.

A playbook begins with three n-dashes (---), which is followed by the playbook name, the name of the remote hosts group that executes the playbook, and additional parameters such as become (execute the playbook as the admin).

The next section contains all user-defined variables. It starts with the vars tag in the same indentation level as the previous section, followed by a list of variables in the next indentation.

Note: Pressing the space button twice is enough to create a new indentation level.

Finally, the task list starts with the tasks tag, with the indentation level depending on the type of task and the parameters used.

The YAML syntax allows you to use three periods () to end the playbook. Though most playbooks end this way, it is not necessary for the playbook to work properly.

Ansible Playbook Syntax

Some important elements of the YAML syntax to keep in mind when writing Ansible playbooks:

  • When composing lists, use a space between the dash (-) and the list entry.
  • When using the key: value form, the colon must be followed by a space.
  • Boolean values can use both yes and no, as well as true and false.
  • Use space followed by # to indicate a comment.

Ansible Playbook Example

For this example, we will create a playbook in the Ansible installation folder:

sudo nano /etc/ansible/example_playbook.yaml
Ansible playbook example

This playbook contains the following elements:

  • ---: Signals the start of the playbook.
  • name: Defines the name for the Ansible playbook.
  • hosts: Defines which hosts execute the playbook. In the example above, the playbook executes on all hosts included in the inventory file.
  • become: Instructs the remote host to execute the playbook as admin. Using this tag requires you to enter the admin password for the remote host when executing the playbook.
  • vars: Defines variables – in our case, a variable named greeting with the value Hello World!.
  • tasks: The list of tasks for the playbook to execute. In the example above, the first task creates a directory called example_playbook on the remote host. The second task creates a new text file in that directory and places the value of the greeting variable as the content.
  • ...: Signals the end of the playbook.

How is a Playbook Executed?

Ansible playbooks are executed in order, from top to bottom. This is true for both individual plays and tasks listed in those plays.

In the example above, the playbook does the following actions, in order:

  1. Defines a list of variables.
  2. Creates a new folder on the remote host.
  3. Creates a text file in the new folder.
  4. Adds the value of the variable as file content.

How to Run an Ansible Playbook

To execute an Ansible playbook, use:

ansible-playbook /path/to/playbook/directory/playbook_name.yaml

For the purposes of this article, we will use example_playbook.yaml with the -K argument, which lets us enter the root user password for the remote host and execute the playbook as admin:

ansible-playbook /etc/ansible/example_playbook.yaml -K
Running the example playbook

How to Verify Playbooks

Run a playbook in check mode using the --check flag to verify it. This allows you to see the changes your playbook would make, without actually making them:

ansible-playbook /path/to/playbook/directory/playbook_name.yaml --check

For a more detailed overview of potential changes, use the combination of --check and --diff flags:

ansible-playbook /path/to/playbook/directory/playbook_name.yaml --check --diff

Useful Ansible Playbook Tips

There are several ways to make Ansible playbooks easier to read and use:

Always Name Plays and Tasks

Use the name keyword to define names for plays and tasks. Adding short and straightforward names makes it much easier to know what each play or task does at a glance.

Use Comments

Make sure you add plenty of comments, especially when defining variables and tasks.

Detailed comments help make the playbook even more clear and easy to understand. They also help anyone else using your playbooks.

Format the Playbook for Ease of Use

While you need to follow the rules of indentation for the playbook to work, you can still use whitespace (such as blank lines between tasks) to make a playbook easier to read.

Conclusion

After following this tutorial, you should now have a working knowledge of Ansible playbooks, including how to create and execute one. Playbooks can be used to define a variety of tasks for the remote hosts to perform, including checking if files and folders exist.

If you are considering Ansible alternatives, see how they stack up against each other in our Ansible vs Terraform vs Puppet article.

原创文章,作者:1402239773,如若转载,请注明出处:https://blog.ytso.com/223889.html

(0)
上一篇 2022年1月7日
下一篇 2022年1月7日

相关推荐

发表回复

登录后才能评论