Hero Vired Logo
Programs
Get the latest update delivered right to your inbox. Subscribe to our newsletter

Ansible Playbooks: Everything You Need to Know

26 Jul 2022
7 MIN READ
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 […]
Ansible Playbooks : Everything You Need to Know

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.

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

  • 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.

  • 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

  • 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.

1. 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. 

2. 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"

}

3. 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

  • 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.

Blog related tags
Read More
Blogs from other domain
Carefully gathered content to add value to and expand your knowledge horizons
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram