Day58:Ansible Playbooks

Day58:Ansible Playbooks

Ansible playbooks are YAML (YAML Ain't Markup Language) files that specify a set of actions that Ansible, an open-source automation tool, is to take.

Ansible playbooks are used to automate processes like setting up software, deploying apps, provisioning servers, and coordinating intricate operations among many systems.

In Ansible, playbooks offer a simple approach to automating repetitive tasks through reusable and uniform configuration files. Rather than manually executing the same action on countless similar technologies within IT environments, executing a playbook automatically completes the same action for the specified type of inventory. Playbooks can also be utilized as starting templates or as ad hoc frameworks of prewritten code for developers.

Features of Ansible Playbooks

Ansible playbooks are YAML-formatted scripts that define a set of actions, configurations, and automation procedures that will run on the target systems. Here are some key features of Ansible playbooks:

  1. Declarative Syntax: Ansible playbooks use declarative syntax, making them easy to read, write, and understand. They describe the desired state of the system rather than focusing on the steps needed to achieve that state.

  2. Modularity: Playbooks are modular, allowing you to break down complex tasks into smaller, reusable components called roles. Roles can be shared and reused across different playbooks and projects, promoting code reusability and maintainability.

  3. Task-Based Execution: Playbooks consist of a series of tasks, each representing an individual action to be performed on the target systems. Tasks can include executing commands, copying files, managing services, installing packages, and more.

  4. Idempotence: Ansible tasks are idempotent, meaning that running the same playbook multiple times results in the same desired state, regardless of the initial state of the system. This ensures predictable and consistent outcomes, even in dynamic environments.

  5. Variables and Templating: Playbooks support the use of variables and Jinja2 templating, allowing you to parameterize your configurations and make them more flexible and dynamic. Variables can be defined at various levels, including playbook, inventory, and role level.

  6. Conditionals and Loops: Ansible playbooks support conditional statements and loops, enabling you to perform tasks conditionally based on certain criteria or iterate over a list of items.

  7. Handlers: Handlers are special tasks that are only executed when triggered by other tasks. They are commonly used to restart services or perform other actions that should be triggered as a result of changes made during the playbook execution.

  8. Roles: Roles provide a way to organize and encapsulate related tasks, variables, and files into reusable units. They help in structuring playbooks and promoting code reuse across different projects and environments.

  9. Error Handling: Ansible playbooks include error handling mechanisms such as ignore_errors andfailed_when, allowing you to control how Ansible reacts to errors during playbook execution.

  10. Integration with Version Control: Playbooks can be managed and version-controlled using Git or other version control systems, facilitating collaboration, code review, and tracking changes over time.

How do Ansible Playbooks work?

An Ansible Playbook defines a system's desired state and then runs a sequence of activities to achieve it. The playbook is comprised of one or more plays. Each play is structured with a set of tasks that are carried out consecutively on the target machines. The playbook is complete when all of the tasks and plays in it have been done.

Playbooks use modules to execute operations on target hosts. Modules are programs that provide functionality such as file management, package installation, and configuration manipulation. A module contains metadata that specifies when and where a job is conducted, as well as who does it. There are hundreds of ansible modules that execute numerous IT jobs.

Components of Ansible Playbooks:

Ansible playbooks have the ability to get pretty massive and sophisticated. But, whether you’re writing a short and sweet playbook or a massive epic, here’s how you do it.

Every playbook is divided into the following components:

Playbooks are composed of several key components:

  1. Hosts: This section specifies the target hosts or groups of hosts on which the tasks defined in the playbook will be executed. Hosts can be specified using inventory files or directly within the playbook.


     hosts: web_servers
  2. Variables: Playbooks can define variables at different levels, including playbook-level variables, inventory-level variables, group variables, or host variables. These variables can be used to parameterize tasks and make playbooks more flexible and reusable.


       http_port: 80
  3. Tasks: Tasks are the core component of a playbook, representing the actions to be performed on the target hosts. Each task typically includes a module and its parameters, defining what Ansible should do on the target systems.


       - name: Ensure Apache is installed
           name: apache2
           state: present
  4. Handlers: Special tasks called handlers are initiated by other activities within the playbook. Usually, they are utilized to carry out operations like reloading configurations or restarting services in reaction to modifications made during playbook execution.


       - name: Restart Apache
           name: apache2
           state: restarted
  5. Roles: Playbooks can organize tasks, variables, and files into reusable units called roles. Roles provide a way to encapsulate common functionalities and promote code reuse across different playbooks and projects.


       - web_server
  6. Conditionals and Loops: Ansible playbooks support conditional statements and loop constructs, allowing you to perform tasks conditionally based on certain criteria or iterate over lists of items.


       - name: Create multiple users
           name: "{{ item }}"
           state: present
           - user1
           - user2

    How do I write an Ansible Playbook?

    Now that you understand the fundamentals of an Ansible Playbook, let us develop one that installs and runs Apache servers.


    Ansible is required to write and run a playbook, so make sure it is installed on your system. I am running Ansible 2.14.5 on Ubuntu 22.04.

    Using Ansible Playbook

    Let's get started. Open a terminal and run the command below to check Ansible's version.

     ansible --version

    Below is the output we get after executing the command:

Defining Tasks in Ansible Playbooks:

Now, create a playbook definition file called demo.yml. The file will include a list of all of the actions needed to install and start the Apache service on the target host specified in the inventory file.

- name: Install and Start Apache
hosts: clients
become: true
- name: Update package cache
update_cache: yes
- name: Install Apache
name: apache2
state: present
- name: Start Apache service
name: apache2
state: started
enabled: true

In this example playbook:

  • name field provides a description of the playbook.

  • hosts field specifies the target hosts or groups of hosts on which the tasks will be executed. In this case, the tasks will run on hosts belonging to the web_servers group.

  • become field indicates that the tasks will be executed with administrative privileges, typically usingsudo.

  • tasks section contains a list of tasks to be executed sequentially.

  • Each task has aname field that describes the task.

  • The task is defined using a module (e.g., apt, service, copy) followed by the module's parameters.

  • In this example, the tasks are to install the Apache web server, start the service, and copy an index.html file to the appropriate location.

To run this playbook, you would use the ansible-playbook command:

ansible-playbook demo.yml

This playbook would install the Apache web server on all of the hosts listed in the hosts variable, and then configure it to start automatically when the system boots. It would also copy the index.html file to the web root.

The hosts variable specifies the hosts that the playbook will run on. In this case, the playbook will run on all of the hosts in the inventory file.

The tasks section of the playbook specifies the tasks that will be executed. Each task is a single instruction that Ansible can execute.

In this example, there are three tasks:

  • The first task installs the Apache web server using the apt module.

  • The second task configures the Apache web server using the service module.

  • The third task copies the index.html file to the web root using the copy module.

Task 1:

Write an ansible playbook to create a file on a different server

Step 1: Login to the AWS Console and connect your EC2 instance using SSH.

Step 2: Add all the server details to the inventory file on the master server.

sudo vim /etc/ansible/hosts
server1 ansible_host=<Server1_IPv4_Addr>
server2 ansible_host=<Server2_IPv4_Addr>
server3 ansible_host=<Server3_IPv4_Addr>

Step 3: Create an Ansible playbook on Master to create a file on different servers( Node-1, Node-2, and Node-3).

sudo vim playbook.yml
- name: A playbook to create a file 
  hosts: all
  become: true
  - name: Create a file
     path: /home/ubuntu/testfile.txt
     state: touch

Step 4: Now to run this playbook use the command ansible-playbook including the filename.

ansible-playbook playbook.yml

  • In this playbook, we define a single task that uses the file module to create the file

  • Path parameter specifies the full path to the file we want to create

  • State parameter set to touch which will create the file if it doesn't exist and do nothing if it does exist.

Step 5: Once the execution is finished, verify that the file has been created on different servers using the following command:.

ansible all -a "ls /home/ubuntu"

  • TASK 2:

    User Creation Ansible Playbook

    Step 1: Create an Ansible playbook for creating a new user on a different server.

- name: A playbook to create a new user
  hosts: all
  become: true
  - name: to create a user named <user_name>
    user: name=<user_name>

Step 2: Run the playbook using the ansible-playbook command

ansible-playbook create_user.yml

Step 3: Once the execution is finished, to check if the user has been created, look for the user’s name in the /etc/passwd file where all the user and system file details are stored on servers.

ansible server1 -a "cat /etc/passwd"


Docker Installation Ansible Playbook

Step 1: Create an Ansible playbook to install docker on a different server.

sudo vim install_docker.yml
- name: A Playbook to Install Docker
  hosts: my-servers
  become: yes
    - name: Add Docker GPG apt Key
        state: present
    - name: Add Docker Repository
        repo: deb focal stable
        state: present
    - name: Update apt and install docker-ce
        name: docker-ce
        state: latest
        update_cache: true

Step 2: Run the playbook using the ansible-playbook command.

ansible-playbook install_docker.yml

Step 3: Verify that Docker has been installed on multiple servers using the following command.

ansible all -a "docker --version"

Step 4: To get the Docker status of all the servers, use the following command:

ansible all -a "sudo systemctl status docker"


🍀 Ansible Playbooks offer a clear and concise syntax that allows users to define a series of steps or tasks in a YAML format. The playbook structure promotes reusability and modularity, enabling users to organize their automation code into logical sections and easily maintain and update it over time.

🍀 One of the key advantages of Ansible Playbooks is their agentless nature. They utilize SSH to connect to remote servers, eliminating the need for installing and managing any additional software on the target systems. This simplifies the setup process and reduces potential security risks.

🍀 Furthermore, Ansible Playbooks integrate well with existing infrastructure and can be seamlessly integrated into Continuous Integration and Continuous Deployment (CI/CD) pipelines. They can be version-controlled, shared, and collaborated on using popular version control systems like Git, enabling teams to work together efficiently.

🍀 Overall, Ansible Playbooks offer a flexible and efficient approach to automating infrastructure management, making it easier to maintain consistency, reduce errors, and streamline the deployment process. By leveraging the power of Ansible Playbooks, organizations can achieve greater operational efficiency, scalability, and standardization in their IT environments.

Thank you for 📖reading my blog, 👍Like it and share it 🔄 with your friends.

Happy learning😊😊