Ansible Playbook How to Create and Configure Playbooks


If you are a system administrator or a DevOps engineer, you know how important automation is in your daily operations. One of most popular tools for automation is Ansible, a configuration management tool that simplifies management of servers, network devices, and other IT infrastructure. In this article, we will dive into Ansible playbooks, a powerful feature of Ansible that allows you to automate complex tasks and configurations.

What is an Ansible Playbook?

An Ansible playbook is a YAML file that describes a set of tasks to be executed on one or more hosts. Playbooks are heart of Ansible automation, providing a structured way to define and execute tasks in a specific order. Playbooks are written in YAML, a human-readable data serialization language, and they can be version controlled like any other text file. Playbooks are easy to read, write, and understand, even for non-programmers.

The Anatomy of an Ansible Playbook

An Ansible playbook is composed of four main components −

  • Hosts − target hosts on which tasks will be executed. Hosts can be defined using IP addresses, hostnames, or patterns that match groups of hosts.

  • Variables − Variables define data used by tasks in a playbook. Variables can be defined at playbook level or at task level. They can also be set as defaults or overridden on a per-host or per-group basis.

  • Tasks − Tasks define actions to be executed on target hosts. Tasks can be composed of modules, which are pre-built Ansible scripts that perform specific functions such as managing files, installing packages, or restarting services.

  • Handlers − Handlers define actions to be executed in response to events triggered by tasks. Handlers are similar to tasks but are only executed if they are notified by a task. Handlers can be used, for example, to restart a service only if it has been changed by a task.

Creating an Ansible Playbook

Creating an Ansible playbook is a straightforward process. First, you need to create a YAML file and define hosts, variables, tasks, and handlers. Here is an example of a simple playbook that installs a package on a group of hosts −

---
- hosts: webservers
	become: yes
	tasks:
	- name: Install Apache2
	apt:
		name: apache2
		state: latest
	handlers:
	- name: Restart Apache2
	service:
		name: apache2
		state: restarted

In this example, we define a group of hosts called "webservers" and indicate that we want to run tasks as root user (using "become: yes"). We define a task called "Install Apache2" that uses apt module to install latest version of Apache2 web server. Finally, we define a handler called "Restart Apache2" that uses service module to restart Apache2 service if it has been changed by task.

Executing an Ansible Playbook

Once you have created your playbook, you can execute it using "ansible-playbook" command. Here is an example of how to execute playbook we created earlier −

ansible-playbook playbook.yml

This command will execute playbook on all hosts defined in "webservers" group. Ansible will connect to each host over SSH and execute tasks in order defined in playbook. Ansible will also collect and display output from each task and handler.

Advanced Features of Ansible Playbooks

Ansible playbooks provide many advanced features that allow you to automate complex tasks and configurations. Here are a few examples −

Loops

Loops allow you to repeat a task for each item in a list. This can be useful, for example, when installing multiple packages or creating multiple files. Here is an example of a playbook that installs multiple packages using a loop −

---
- hosts: webservers
  become: yes
  vars:
	packages:
	- apache2
	- mysql-server
	- php
  tasks:
  - name: Install packages
	apt:
		name: "{{ item }}"
		state: latest
	loop: "{{ packages }}"

In this example, we define a variable called "packages" that contains a list of package names. We then use a loop to iterate over list and install each package using apt module.

Conditionals

Conditionals allow you to execute tasks based on certain conditions. This can be useful, for example, when installing a package only if it is not already installed. Here is an example of a playbook that installs a package only if it is not already installed −

---
- hosts: webservers
  become: yes
  vars:
    package: apache2
  tasks:
  - name: Check if package is installed
    command: "dpkg -s {{ package }}"
    register: result
    ignore_errors: true
  - name: Install package
    apt:
      name: "{{ package }}"
      state: latest
    when: result.rc != 0

In this example, we define a variable called "package" that contains name of package to be installed. We use "command" module to check if package is already installed and register result in a variable called "result". We then use a conditional to install package only if command returns a non-zero status code, indicating that package is not already installed.

Roles

Roles allow you to organize your playbooks into reusable units of work. Roles contain tasks, handlers, variables, and files that are specific to a particular function or application. Roles can be shared and reused across multiple playbooks. Here is an example of a simple role that installs a package −

---
- name: Install Apache2
  become: yes
  apt:
    name: apache2
    state: latest

In this example, we define a role called "apache2" that installs Apache2 package using apt module. We can then include this role in a playbook using "include_role" module −

---
- hosts: webservers
  become: yes
  tasks:
  - name: Install Apache2
    include_role:
      name: apache2

In this example, we include "apache2" role in our playbook using "include_role" module. Ansible will automatically execute tasks defined in role.

Here are a few more advanced features of Ansible playbooks that you can use to automate your infrastructure −

Variables and Templates

Ansible playbooks allow you to use variables to pass values between tasks, define default values, and override values for specific hosts or groups. You can also use templates to dynamically generate configuration files based on variables. Here is an example of a playbook that uses variables and templates −

---
- hosts: webservers
  become: yes
  vars:
    server_name: example.com
    document_root: /var/www/html
  tasks:
  - name: Create virtual host file
    template:
      src: virtualhost.j2
      dest: /etc/apache2/sites-available/{{ server_name }}
  - name: Enable virtual host
    command: "a2ensite {{ server_name }}"
  - name: Create document root
    file:
      path: "{{ document_root }}"
      state: directory

In this example, we define variables for server name and document root directory. We then use template module to generate a virtual host configuration file based on a Jinja2 template called "virtualhost.j2". We use "command" module to enable virtual host and "file" module to create document root directory.

Tags

Ansible playbooks allow you to assign tags to tasks, allowing you to selectively execute tasks based on their tags. This can be useful when debugging or testing playbooks. Here is an example of a playbook that uses tags −

---
- hosts: webservers
  become: yes
  tasks:
  - name: Install Apache2
    apt:
      name: apache2
      state: latest
    tags: apache
  - name: Install MySQL
    apt:
      name: mysql-server
      state: latest
    tags: mysql

In this example, we assign tags to two tasks, "apache" and "mysql". We can then execute only tasks with a specific tag using "ansible-playbook" command −

ansible-playbook playbook.yml --tags apache

This command will execute only task with "apache" tag.

Vault

Ansible playbooks allow you to encrypt sensitive data using Ansible Vault. Vault provides a way to store and manage sensitive data such as passwords, API keys, and SSH keys in an encrypted format. Here is an example of a playbook that uses Ansible Vault −

---
- hosts: webservers
  become: yes
  vars:
    db_password: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          61646566336461333462323466633435386366663433663237663731346662336434303863316535
  tasks:
  - name: Create database user
    mysql_user:
      name: dbuser
      password: "{{ db_password }}"
      priv: '*.*:ALL,GRANT'

In this example, we define a variable called "db_password" that is encrypted using Ansible Vault. We then use "mysql_user" module to create a database user and pass encrypted password using "{{ }}" syntax.

Conclusion

Ansible playbooks are a powerful tool for automating IT infrastructure. Playbooks provide a structured way to define and execute tasks in a specific order, making it easy to automate complex configurations. Playbooks are easy to read, write, and understand, even for non-programmers. Ansible provides many advanced features such as loops, conditionals, and roles that allow you to automate complex tasks and configurations with ease. If you are not using Ansible playbooks already, it's time to start!

Updated on: 02-May-2023

510 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements