Hero Vired Logo
Hero Vired Logo
Programs
Stay Ahead of the Curve
Sign up for Our Weekly Newsletter!

Ansible Playbooks: Everything You Need to Know - 2023

26 Jul 2022
9 MIN READ
Last updated on: May 16, 2023
Table of Content What is an Ansible playbook? How do Ansible Playbooks work? In what cases can Ansible playbooks be...
Ansible Playbooks : Everything You Need to Know
Table of Content

Ansible playbooks form a popular and useful DevOps tool that focuses on automation in remote systems. To work with an Ansible playbook, one needs to have the basic knowledge of DevOps. It is nothing but an amalgamation of practices, tools, and philosophies that enhance the efficiency of an organization to make its services and applications work with precision.

DevOps has changed how traditional software works, changing the nature of software development and infrastructure management processes. It is an automation process that reduces the delivery time of applications. 

Many big companies have grown successfully over the years by using DevOps, which plays a significant role in increasing the efficiency of applications. Notably, DevOps engineers deal with the application management process through automation and unification with the help of coding.

Ansible playbook is a perfect example of DevOps that helps the software development process to take place automatically. The collaboration and interaction or communication among the operation professionals, project management, and software development take place through tools like Ansible playbooks.

What is an Ansible playbook? 

Ansible is a reliable automation tool capable of handling intra-service orchestration, application management, and provisioning. It is an open-source automation tool that reduces time consumption and eliminates tasks that require repetition. Ansible playbooks help teams to concentrate on strategic work. 

Ansible playbooks help in the deployment of applications and interservice orchestration. It is an integral part of the Ansible configuration. We can clearly understand the concept of Ansible playbooks once we look into their usage and variables with some examples.

An Ansible playbook is a handy DevOps tool that helps remote systems to work efficiently through automation. It is a file that enables users to write Ansible codes that play a significant role in server configuration. It is a collection of scripts that supports the IT processes in enforcing remote systems. 

Playbooks in Ansible have one or multiple playbooks arranged in a specific order. These ordered sets of tasks function against hosts selected from one's inventory. The most intriguing part is that it works constructively to set the work you need to do in a remote system.

What are the Uses of Ansible Playbooks?

We will be providing you with a few examples to mark using Ansible playbooks to create playbooks that you may need to run regularly. You will need to develop and run them using the control machine.

Example 1:

Create a file on the target machine/server, keeping the inventory file and the web server's group in mind. Use this code on a .yml extension and then run the playbook.

- hosts: webservers
  become: true
  tasks:
  - name: Create a file
    file: path=/home/ansible/niranjan.txt state=touch

In this code, we have used a file module to create a file.

Example 2:

Let's learn how to create and delete a user in the playbook.

---
- hosts: webservers
  become: true
  tasks:
  - name: Create User
    user: name=cynthia password=cynthia groups=ansible shell=/bin/bash

In what cases can Ansible playbooks be used? 

Ansible playbooks have a clear advantage of getting used in many cases. You can use them for the following tasks:

  • Provisioning - When we create a new infrastructure, we call it provisioning. Ansible playbooks allow for various tasks such as deployment, application management, orchestration, and configuration management, to name a few.
  • Application Deployment - Ansible playbooks pave the way for a more straightforward deployment of applications throughout the infrastructure. You can quickly deploy multi-tier applications and change the infrastructure over extended periods.
  • Cloud Computing - Ansible playbooks simplify the process of cloud computing by provisioning instances across every cloud provider. Since it contains multiple modules, it allows the management of enormous cloud infrastructure over hybrid and public-private clouds.
  • Continuous Delivery - Ansible playbooks automatically deploy applications. You can configure every necessary service using a single system. You can also use a continuous integration (CI) tool to run an Ansible playbook which you can then use for testing and automatically deploying the application. It will ensure checking of your production texts.
  • Security and Compliance - Ansible will automate every security policy in your list, which you can use to automate security policy across all machines in the network. You can configure the security roles embedded over every device in your network.

How to write an Ansible Playbook?

An Ansible playbook consists of a set of hosts that participate in the configuration. You will be amazed to know that it also has a list containing the tasks you need to carry out. However, it would help to consider that there is no scope for any play that is standardized, for every play has to be written by an administrator to make the automation happen.

To understand Ansible playbooks, you need to know the types and the ways of using Ansible playbooks. Ansible uses YAML syntax, which gives it the right to seek two types of file extensions, namely .yaml and .yml. YAML is short for another markup language.

Starting with prerequisites, we will be moving forward with installing and more. You can either use Ansible playbooks using a command-line interface or CLI. To run your first command and Ansible playbook, keep a few pointers in mind.

Before starting this journey, we need you to go through the prerequisites. To run your first command, you need to exercise the previously discussed concepts. You can move forward to actual programming by choosing a compatible Ansible. You can begin with Ansible 2.10 or higher versions installed.

After installing the version, you need to find one or more network devices compatible with Ansible. You must acquire basic Linux command-line knowledge and network switch and router configuration.

How do Ansible Playbooks work?

Ansible modules carry out tasks. One or more tasks can be combined to form a play. Two or more plays can be combined to create the Ansible Playbook. Ansible Playbooks are libraries of commands that automatically execute against hosts. The Ansible inventory is made up of host groups. Ansible modules in a Playbook perform a certain task. Each ansible module offers metadata that identifies the when, where, and who performs a task. Check out our Business Analytics and Data Science Course.

Importance of Ansible Playbook in DevOps 

  • Ansible makes DevOps simpler through automating the integration of internally created applications into your production programs. 
  • Ansible is a well-liked DevOps tool for orchestration, automation, configuration, and management of IT infrastructure. 
  • Ansible's benefits in DevOps include its capacity for demand-driven expansion and adaptation. 
  • Faster feedback loop acceleration, reliable installations, coordinated IT architecture, and quicker deployments.

Purpose of Ansible Playbook

To launch complicated applications, Ansible Playbooks provide a repeatable, reusable, easy configuration management and multi-machine deployment mechanism. Learn What Is Data: Definition, Types & Data Management. Explore the Data Warehousing and Data Mining.

How to use Ansible Playbooks? 

  • One can use the ansible run playbook command to run the playbook.
  • When executing your playbook, use the --verbose parameter to see extensive output from both successful and failing modules.
  • The result ought to be the same whether a playbook is used just once or several times. Not all playbooks and modules operate in this manner. Before repeatedly running your playbooks in production, try them in a sandbox setting if you're unsure. Explore more about Data Collection - Methods, Types, Tools, and Techniques.

Step-by-step guide on how to install Ansible

  • Refresh/Update your control node
  • Setup the EPEL Repository
  • Install
  • Making an Ansible User
  • Configure SSH access for the Admin User
  • Make an Inventory
  • Make an Ansible Playbook
  • Run your Ansible Playbook

What are the Variables of Ansible Playbooks?

  • Simple Variable: Simple variables consist of a single value and a variable name.
  • Boolean Variables: Boolean variables can have a wide range of values in Ansible, including true, false, 1/0, yes, no, and so forth.
  • List Variables: A list variable combines the name of the variable with a number of values.
  • Dictionary Variables: Key-value pairs are used to store the data in dictionaries.

How to install Ansible

Once you are confident about your experience, you can start installing Ansible. Follow the steps from here.

  1. Establish a connection to a managed node manually - Connect to a network device through a manual approach and retrieve the configuration. Use your real credentials to replace the device name and the sample user. For instance, a VyOS router would show the following command:
    ssh my_vyos_user@vyos.example.net
    show config
    exit
    

    By establishing a manual connection for the authenticity of the network device, you will be able to move ahead. It works by adding its RSA key fingerprint to the loss of known hosts in your system. If you have already connected to the device in the past, you have successfully established its authenticity.

  2. Run your initial network Ansible command - You can retrieve the network device's configuration by utilizing a single, stripped-down Ansible command. You can do so instead of manually connecting and performing a command on the network device. It will look like this:
    ansible all -i vyos.example.net, -c ansible.netcommon.network_cli -u 
    my_vyos_user -k -m vyos.vyos.vyos_facts -e ansible_network_os=vyos.vyos.vyos

    In this set of seven values, the flags in the command are:

    1. The host group or groups to which command should apply
    2. The inventory marked by (-i) points to an inventory file for the device or devices it targets without the trailing comma
    3. The connection method is denoted by (-c), which means the technique to connect and execute Ansible
    4. (-u) denotes the user and is the username for the SSH connection
    5. (-k) denotes the SSH connection method urging to prompt the password
    6. The module denoted by (-m) implies that the Ansible module is to run using the FQCN or Fully Qualified Collection Name
    7. (-e) stands for an extra variable that sets the network OS value

    Ansible will load them automatically if you have used the SSH agent with SSH keys. As a result, you can omit the (-k) flag. If you decide to run Ansible in an effective environment, you can add this variable:

    ansible_python_interpreter=/path/to/venv/bin/python
  3. After creating, run your Ansible playbook through your device network - The playbook stores several parameters and provides you with flags at the command line. For running the command regularly, you can start by saving it in a playbook and then running it using the Ansible playbook instead of Ansible. It renders an added advantage of lesser typing at the command line. You will require two files - the inventory file and a playbook.
  4. After downloading your first playbook, you will see these commands:
    ---
    - name: Network Getting Started First Playbook
      connection: ansible.netcommon.network_cli
      gather_facts: false
      hosts: all
      tasks:
        - name: Get config for VyOS devices
          vyos.vyos.vyos_facts:
            gather_subset: all
        - name: Display the config
          debug:
            msg: "The hostname is {{ ansible_net_hostname }} and the OS is {{ ansible_net_version }}"
    

    This playbook consists of seven values from the command line: the group, connection method, and module. Once you have the values set in the playbook, you can exclude the command line. You can also add a second task to showcase the dual output. 

  5. Use this playbook to run the command:
    ansible-playbook -i vyos.example.net, -u ansible -k -e ansible_network_os=vyos.vyos.vyos first_playbook.yml
    At this point, your playbook should generate an output like this:
    $ ansible-playbook -i vyos.example.net, -u ansible -k -e ansible_network_os=vyos.vyos.vyos first_playbook.yml
    PLAY [First Playbook]
    ***************************************************************************************************************************
    TASK [Get config for VyOS devices]
    ***************************************************************************************************************************
    ok: [vyos.example.net]
    TASK [Display the config]
    ***************************************************************************************************************************
    ok: [vyos.example.net] => {
        "msg": "The hostname is vyos, and the OS is VyOS 1.1.8"
    }
    
    1. The final step is to update the device configuration with the following commands.
      ---
      - name: Network Getting Started First Playbook Extended
        connection: ansible.netcommon.network_cli
        gather_facts: false
        hosts: all
        tasks:
          - name: Get config for VyOS devices
            vyos.vyos.vyos_facts:
              gather_subset: all
          - name: Display the config
            debug:
              msg: "The hostname is {{ ansible_net_hostname }} and the OS is {{ ansible_net_version }}"
          - name: Update the hostname
            vyos.vyos.vyos_config:
              backup: yes
              lines:
                - set system host-name vyos-changed
          - name: Get changed config for VyOS devices
            vyos.vyos.vyos_facts:
              gather_subset: all
          - name: Display the changed config
            debug:
              msg: "The new hostname is {{ ansible_net_hostname }} and the OS is {{ ansible_net_version }}"
      This extension of the first playbook consists of four tasks in a single play. After you run it using the same command that we have previously used, the output will show this:
      $ ansible-playbook -i vyos.example.net, -u ansible -k -e ansible_network_os=vyos.vyos.vyos first_playbook_ext.yml
      PLAY [First Playbook]
      ************************************************************************************************************************************
      TASK [Get config for VyOS devices]
      **********************************************************************************************************************************
      ok: [vyos.example.net]
      TASK [Display the config]
      *************************************************************************************************************************************
      ok: [vyos.example.net] => {
          "msg": "The hostname is vyos and the OS is VyOS 1.1.8"
      }
      TASK [Update the hostname]
      *************************************************************************************************************************************
      changed: [vyos.example.net]
      TASK [Get changed config for VyOS devices]
      *************************************************************************************************************************************
      ok: [vyos.example.net]
      TASK [Display the changed config]
      *************************************************************************************************************************************
      ok: [vyos.example.net] => {
          "msg": "The new hostname is vyos-changed and the OS is VyOS 1.1.8"
      }
      PLAY RECAP
      ************************************************************************************************************************************
      vyos.example.net : ok=5 changed=1 unreachable=0 failed=0
      
    2. Gather facts through network devices 
       For the last step, you will find the keyword gather_facts. It supports gathering network device facts in standard key pairs now. From here, you can feed the network facts into tasks for further purposes. It will help you in managing the network device.

      Alternatively, you can use the parameter gather_network_resources along with this network module -  *_facts to help you return the device configuration’s subset. You can see it in the following command:

       - hosts: arista
        gather_facts: True
        gather_subset: interfaces
        module_defaults:
          arista.eos.eos_facts:
            gather_network_resources: interfaces
      Congratulations! Your playbook will return the following interface facts:
      "network_resources": {
            "interfaces": [
                {
                    "description": "test-interface",
                    "enabled": true,
                    "mtu": "512",
                    "name": "Ethernet1"
                },
                {
                    "enabled": true,
                    "mtu": "3000",
                    "name": "Ethernet2"
                },
                {
                    "enabled": true,
                    "name": "Ethernet3"
                },
                {
                    "enabled": true,
                    "name": "Ethernet4"
                },
                {
                    "enabled": true,
                    "name": "Ethernet5"
                },
                {
                    "enabled": true,
                    "name": "Ethernet6"
                },
            ]
        }
      

    Finally, you can store the above facts and use them for other tasks.

    DevOps aims to make software operations easier by approaching a faster development method. Ansible playbooks are a handy bunch that can change the way you look at automation systems. These are a complex set of IT actions that, once executed, can be of great use with little human interaction.

    Therefore, new products come to the fore along with the maintenance of the pre-existing deployments. Hence, you can opt for Ansible playbooks at any point in time without giving it a second thought.

    You can learn about Ansible, and other key DevOps tools and technologies, with the Hero Vired Certificate Program in DevOps & Cloud Engineering, offered in partnership with edX and from AWS

    Tips and tricks for debugging Ansible Playbooks

    • To enable or disable the debugger, use the debugger keyword; the value you specify overrides any global option.
    • The debugger can be enabled (or disabled) for a particular play, role, block, or task using the debugger keyword.
    • On new or updated tasks, the debugger can be turned on. If they don't work, you can quickly remedy the problems.

    Conclusion

    Ansible Playbook makes DevOps simpler by automating the integration of internally created applications into your production programmes. Ansible Playbook is one of the most well-liked DevOps tools for orchestration, automation, configuration, and management of IT infrastructure. In order to launch complicated applications, Ansible Playbook provides a repeatable, reusable, easy configuration management and multi-machine deployment mechanism.

FAQ's

How do I use Ansible Playbooks?

To use Ansible Playbooks, your control node's terminal window should be opened. In any directory, create a new playbook file with the name playbook.yaml and update it there.

How can I install Ansible on my system?

You can install Ansible Playbook by following the steps:

  • Refresh/Update your control node
  • Setup the EPEL Repository
  • Install
  • Making an Ansible User
  • Configure SSH access for the Admin User
  • Make an Inventory
  • Make an Ansible Playbook
  • Run your Ansible Playbook

How can I use Ansible Playbooks for application deployment?

To use your Ansible Playbook, run "sudo Ansible-playbook -i inventory. txt main. yml" to access the playbook.

How can I use Ansible Playbooks for infrastructure automation?

Ansible Playbook can be used to provision the underlying infrastructure, install OpenStack services and add a compute host.

Blog related tags
Blog of the week
Related Programs
Certificate program in DevOps and Cloud Engineering

Powered by

Hero Vired

Certificate Program in

DevOps & Cloud Engineering

Part-time

·

7 months

Weekend Classes

Apply by: 

June 11, 2023

Explore Program
CodeAca

Powered by

Hero Vired

Certificate Program in

Full Stack Development with Cloud for Web and Mobile

Part-time

·

10 months

Weekend Classes

Apply by: 

June 11, 2023

Explore Program
chevron-down linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram