Ansible Playbooks: How to Create and Manage Playbooks

Ansible Playbooks: How to Create and Manage Playbooks. In this guide, we introduce Ansible playbooks, its major features then show you how to create and use Ansible playbooks.

With IT environments becoming more and more complex, system administrators and developers are searching for new and better technologies for quick results. An automation tool like Ansible makes complex tasks simpler. The powerful open-source automation tool comprises various features that eliminate repetitive tasks and time consumption. As a result, DevOps teams are able to focus on other areas that require more time and attention.

What is Ansible Playbooks?

Every Ansible configuration starts with a playbook, which is a crucial aspect of Ansible. In simple terms, an Ansible playbook is a structured collection of scripts used for outlining the steps necessary to manage a system configuration.

One or more plays, each of which is made up of modules, make up Ansible playbooks. Ansible plays are flexible because of modules, which are PowerShell or Python that address specific areas of the target managed servers. The open source community that utilizes and promotes Ansible as it offers a wide variety of modules. The modules are basically for user administration and program installation.

Ansible Playbooks are usually written in YAML and designed by administrators with specifications tailored to the target machines’ environments. They are used for task automation, application deployment as well as managing configuration. It is simpler to manage complicated IT infrastructure and repetitive operations when using Ansible. It allows you to manage and automate many remote hosts or servers from a central control node.

Features of Ansible Playbooks

System administrators and DevOps teams may automate different elements of server management and application deployment with Ansible Playbooks, making it a highly useful tool in the market. Here are a few key features of Ansible Playbook:

1. Offers Variable Support – Playbooks facilitate the usage of variables, enabling you to specify data dynamically and increase the flexibility and reusability of your configurations.

2. Simple Syntax – You may specify the intended state of your systems with Ansible Playbooks thanks to their YAML syntax. Playbooks are simple to read and comprehend because you indicate what needs to be done instead of writing code that explains how to achieve it.

3. Versatile – Playbooks may be used for many different activities, ranging from basic configuration management to intricate application deployments and orchestration, making Ansible a flexible tool for different automation requirements.

4. Scalable – In terms of scalability, Ansible performs better than other IT automation technologies. Ansible can work on a bigger scale than other IT Automation solutions, and it  easily handles a larger infrastructure. It even has the ability to manage node fluctuations at ease, unlike other automation technologies.

5. Integration support – Ansible Playbooks’ functionality and connectivity with current workflows can be expanded by integrating with a variety of external tools and services, including cloud providers, monitoring tools, and various version control systems.

6. Agentless Architecture – Another key feature of Ansible is it requires no agents or daemon installations on remote hosts. To connect to and control the target systems, it employs SSH, which eases setup and lowers security concerns.

7. Community Support – Ansible may have a small support community, but it holds yearly events and conducts speedy troubleshooting of online resources. In fact, the enterprise version features a team that offers qualified assistance.

We are at the main part of Ansible Playbooks: How to Create and Manage Playbooks. Let’s try.

Ansible Playbooks: How to Create and Manage Playbooks

In this section, we show you how to manage and control remote nodes using the Ansible playbook.

Create a Basic Ansible Playbook

To understand the Ansible playbook, let’s create a basic Ansible playbook that prints the message “Hello This is Basic Ansible Playbook!”.

				
					nano playbook.yml
				
			

Add the following lines:

				
					- name: A basic playbook file
  hosts: web-server
  tasks:
    - name: Print message
      debug:
        msg: Hello This is Basic Ansible Playbook!

				
			

Save and close the file when you are finished.

A brief explanation of each directive is shown below.

  • hosts: Specify the list of all remote hosts.
  • tasks: Used to define the list of the tasks executed on the target servers.
  • debug: It is an Ansible module that prints specified statements during Playbook runtime.
  • msg: Define the message to be printed to stdout.

Next, create an inventory file to specify remote hosts:

				
					nano inventory
				
			

Add your remote hosts information:

				
					[web-server]
192.168.100.10

				
			

Save and close the file then run the playbook with the following command.

				
					ansible-playbook playbook.yml -i inventory file
				
			

If everything is fine, you see the following screen.

Install and Remove a Package Using Playbook

Ansible provides package management modules such as, apt, dnf, pacman and zypper for all major Linux distributions. Use them to install and remove software packages to your target servers.

Let’s create a playbook file to install the Nginx package on the target server.

				
					nano playbook.yml
				
			

Add the following configurations.

				
					- name: Ansible apt module
  hosts: web-server
  tasks:
    - name: Install Nginx Package
      apt:
       name: nginx
       state: present

				
			

Save and close the file then run the playbook using the following command.

				
					ansible-playbook playbook.yml -i inventory
				
			

After the successful playbook execution, you see the following screen.

Use the state=absent with the apt module to remove a package from the target server.

				
					nano playbook.yml
				
			

Add the following lines:

				
					- name: Ansible apt module
  hosts: web-server
  tasks:
    - name: Remove Nginx Package
      apt:
       name: nginx
       state: absent

				
			

Save and close the file then run the Ansible playbook to remove an Nginx package from the target server.

				
					ansible-playbook playbook.yml -i inventory
				
			

You see the following screen:

Start and Stop Service Using Playbook

Ansible offers a service module to start and stop services using the playbook. Let’s create a playbook file to start the Nginx service on the target server.

				
					nano playbook.yml
				
			

Add the following lines:

				
					- name: Ansible service module
  hosts: web-server
  tasks:
    - name: Start Nginx Service
      ansible.builtin.service:
       name: nginx
       state: started

				
			

Save and close the file then run the playbook to start the Nginx service.

				
					ansible-playbook playbook.yml -i inventory
				
			

You will see the following screen.

If you want to stop the Nginx service then use the state=stopped with Ansible service module.

				
					- name: Ansible service module
  hosts: web-server
  tasks:
    - name: Stop Nginx Service
      ansible.builtin.service:
       name: nginx
       state: stopped

				
			

Run the playbook to stop the Nginx service on the target server.

				
					ansible-playbook playbook.yml -i inventory
				
			

You see the following screen.

To restart multiple services on the target servers, use the loop and {{ item }} parameter in the playbook file.

				
					- name: Ansible service module
  hosts: web-server
  tasks:
    - name: Restart Multiple Services
      ansible.builtin.service:
       name: "{{ item }}"
       state: started
      loop:
       - nginx
       - mariadb

				
			

Save and close the file then run the playbook to restart Nginx and MariaDB services.

				
					ansible-playbook playbook.yml -i inventory
				
			

You will see the following screen.

Copy Files Using Playbook

Ansible provides a copy module that allows you to copy files from the Ansible controller machine to remote machines. It also allows you to assigned the owner and group ownership to the specific files.

Let’s create a playbook file to copy a file.txt from the control node to the remote node.

				
					nano playbook.yml
				
			

Add the following lines:

				
					- name: Ansible copy module example
  hosts: web-server
  tasks:
    - name: Copy files from control node to remote node
      ansible.builtin.copy:
        src: /home/vyom/Documents/file.txt
        dest: /tmp/

				
			

Save and close the file then execute the playbook to perform the copy operation.

				
					ansible-playbook playbook.yml -i inventory
				
			

You will see the following screen.

You can use the copy module with the remote_src option to copy files within the remote node. Let’s create a playbook file to create a backup copy of nginx.conf configuration file.

				
					nano playbook.yml
				
			

Add the following lines:

				
					- name: Ansible copy module example
  hosts: web-server
  tasks:
    - name: Copy files within the remote node
      ansible.builtin.copy:
        src: /etc/nginx/nginx.conf
        dest: /etc/nginx/nginx.conf.bak
        remote_src: yes

				
			

Save and close the file then execute the playbook to perform the copy operation.

				
					ansible-playbook playbook.yml -i inventory
				
			

You will see the following screen.

Modify Files Using Playbook

You can use the lineinfile Ansible module to modify, replace or add a single line to a file. It is specifically used to configure remote servers.

Let’s create a playbook file to modify the SSH service configuration. We change the line “PermitRootLogin yes” to “PermitRootLogin no” and change the line “PubkeyAuthentication yes” to “PubkeyAuthentication no”.

				
					nano playbook.yml
				
			

Add the following configuration.

				
					- name: Configure SSH
  hosts: web-server
  tasks:
    - name: Disable SSH root login
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^PermitRootLogin"
        line: PermitRootLogin=no
    - name: Disable SSH public key authentication
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^PubkeyAuthentication"
        line: PubkeyAuthentication=no
				
			

Save and close the file then run the playbook with the following command.

				
					ansible-playbook playbook.yml -i inventory
				
			

You will see the following screen.

Execute Commands Using Playbook

In this section, we use the Ansible command module to execute specific commands on the target node and print the resulting output on the screen.

Let’s create a playbook to run the “df” and “uptime” commands on the remote node.

				
					nano playbook.yml
				
			

Add the following lines.

				
					- name: Execute commands on remote nodes
  hosts: web-server
  tasks:
    - name: Execute the uptime command
      shell: "uptime"
      register: uptime_var

    - debug:
       msg: "{{uptime_var.stdout}}"

    - name: Execute the df command
      shell: "df"
      register: df_var

    - debug:
       msg: "{{df_var.stdout}}"

				
			

Save the file then run the playbook with the following command.

				
					ansible-playbook playbook.yml -i inventory
				
			

You will see the executed commands output on the following screen.

Ansible Playbooks: How to Create and Manage Playbooks: Conclusion

Ansible is becoming a popular configuration management tool used by many DevOps engineers and IT professionals who require efficient and effective results. It provides a number of features that can assist with some of your incredibly complex IT procedures. Playbooks can be executed faster by using Ansible’s parallel task execution capabilities across many hosts. In fact, it can even be used to simplify and streamline the configuration infrastructure management process.

Avatar for Hitesh Jethva
Hitesh Jethva

I am a fan of open source technology and have more than 10 years of experience working with Linux and Open Source technologies. I am one of the Linux technical writers for Cloud Infrastructure Services.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x