Home Technical Implementing DevOps with Ansible

Implementing DevOps with Ansible

by Rahul Jain

Beginners, in particular, try to seek assistance from the basics. Thus, this blog talks about implementing DevOps with Ansible.

This blog talks about processes and DevOps tools for automation.

To understand automation in a better way here we have what the dictionary defines automation as “the technique of making an apparatus, a process, or a system operate automatically.” We define automation as “the creation and application of technology to monitor and control the production and delivery of products and services.”

DevOps Tools with Ansible

The tools that help in the process of automation are the DevOps tool. DevOps tool emphasizes communication, a collaboration between product management, software development, and operation officials.

Among many popular tools here we will be talking about implementing DevOps with Ansible specifically, Ansible is one tool that is gaining importance every passing day. Ansible is an open-source automation tool that is really easy to set up and use. You can do configuration management, application deployment, and task automation using Ansible.

You will learn how to implement DevOps with Ansible in a detailed module. Also to note, you will not require any security or push agents to work on SSH ports. It is used for push mechanism unlike other tools of the same kind.

Ansible also maintains consistency in its working and supports heterogeneous environment support.  

COURSE OUTLINE

In this course, you will learn about implementing DevOps with Ansible, it’s working and the results it generates under the following subheadings.

Introduction to implementing DevOps with Ansible

Ansible is a tool that helps you manage multiple facets of Information Technology which is why it is important to understand its working. In the very first course of this module, you will study the generic concepts of implementing DevOps with Ansible. While eventually, you will be able to learn the advanced stages wherein you will then feel comfortable in automating tasks with Ansible.

Ansible Terminology and Architecture

It is a helpful tool that allows you to create groups of machines, and make them function as per the need. I have mentioned some important terms below for the reference.

  • Controller Machine:

It is the machine where you install Ansible.

  • Inventory:

An initialization file that contains information about the servers.

  • Playbook:

Playbook is the entry point for Ansible provisioning. You define the complete automation in playbook.

  • Task:

Task is a type of block that defines a single procedure for execution. For example, installing a package.

  • Module:

A module typically abstracts a system task, like dealing with packages or creating and changing files. There are multitude of built-in modules in Ansible, but you can also create custom ones for the purpose of your ease.

  • Role:

It is a pre-defined way for organizing playbooks and other files in order to facilitate sharing and reusing portions of provisioning.

  • Play:

Play is a sort of provisioning for execution from start to finish .

  • Facts:

Global variables containing information about the system, like network interfaces or operating system.

  • Handlers:

Used to trigger service status changes, like restarting or stopping a service.

>>Information Source

  • Ansible Architecture

The Ansible orchestration engine interacts with a user who is writing the playbook to execute the Ansible orchestration and interact along with the services of private or public cloud and configuration management database. We can understand it better with the help of the diagram given below:

implementing devops with ansible

About the diagram

  • Inventory

Inventory is lists of nodes or hosts having their IP addresses, databases, servers, etc. which are need to be managed.

  • API’s

The Ansible API’s works as the transport for the public or private cloud services.

  • Modules

Ansible connected the nodes and spread out the Ansible modules programs. Ansible executes the modules and removes after finishing. These modules can reside on any machine and require no database or servers.

Application = package +configuration file + services  == module

  • Plugins

Plugins is a piece of code that expands the core functionality of Ansible. 

  •  Playbooks

Playbooks consist of written codes in YAML format, which describe the tasks and executes them through the Ansible. Also, you can launch the tasks synchronously and asynchronously with playbooks.

Playbooks with YAML format have to follow the rules specified below:

  • Rule1 :

For indentation, we don’t use tabs but 2 spaces in layered structure

  • Rule 2 :

For module we use colon ,not = sign  , key: value

User :

  Name:yogesh

  shell:/bin/sh

  Password: @##$$

  State: present

Inside user module attributes above begin with2 spaces

  • Rule 3 :

Use dashes(-) for start of task : –

–  name: this is my package

   Package :

     Name: ntp

     State: present

–  name : starting my services

   Service:

     Name: ntpd

     State: running

Creation of a playbook

### basic (selection of host/group of host,users(by default remote user is root))–tells about inventory

–  hosts: “*”  or “yogeshclient” “webservers”

    Remote_user : root , yourname

   Become : yes

   Become_method : su

   Become_user : postgres

For a group of servers to run playbook for you need to follow the steps mentioned below: –

Hosts : (mention group name here as mentioned in /etc/ansible/hosts file)

Ansible-playbook -i usertest.yml –ask-pass (-i will include inventory file)

Ansible-playbook usertest.yml –ask-pass –list-hosts …shows list of hosts applied on

The directory consists of file. You can only run the Playbook from the same directory.

Because of this we create play book dir /etc/ansible/playbook

implementing devops with ansible
  • Hosts

Hosts are the node systems, which are automated by Ansible, and any operating system such as RedHat, Linux, Windows, etc.

  • Networking

Ansible automates different networks, and it uses a simple, secure, and powerful agentless automation framework for IT operations and development. It uses a type of data model which separated from the Ansible automation engine that spans the different hardware quite easily.

  • Cloud

A cloud is a network of remote servers on which you can store, manage, and process the data. These servers store the data remotely rather than on the local server. 

It launches the resources and instances on the cloud, connect them to the servers, and you are then good to go.

  • CMDB

CMDB is a type of repository which acts as a data warehouse for IT installations.

implementing devops with ansible

Ansible setup and configuration

Implementing DevOps with Ansible are written in python and is supported on both mac and windows except AIX. 

We only need to tell modules where PKG is present & ansible will self install it then.

Attributes & modules will be using & converting our logical thinking into configuration

In this guide, we’ll discuss how to install Ansible on an Ubuntu 20.04 server and go over some basics of how to use this software.

Configuration management is used in server hardening, patching, and keeping infra consistent.

Default config file : /etc/ansible/ansible.cfg

                          : /etc/ansible/hosts

Prerequisites

To follow this tutorial, you will need to have  python version 2.7 prerequisite for ansible master along with things things mentioned below:

Step 1 — Installing Ansible

To begin using Ansible as a means of managing your server infrastructure, you need to install the Ansible software on the machine that will serve as the Ansible control node. We’ll use the default Ubuntu repositories for that.

Step 2 — Setting Up the Inventory File

The inventory file contains information about the hosts you’ll manage with Ansible. You can include anywhere from one to several hundred servers in your inventory file, and hosts can be organized into groups and subgroups. The inventory file is also often used to set variables that will be valid only for specific hosts or groups, in order to be used within playbooks and templates. 

  • Note:

Although Ansible typically creates a default inventory file at etc/ansible/hosts, you are free to create inventory files in any location that better suits your needs. In this case, you’ll need to provide the path to your custom inventory file with the -i parameter when running Ansible commands and playbooks. 

The default inventory file provided by the Ansible installation contains a number of examples that you can use as references for setting up your inventory. The following example defines a group named [servers] with three different servers in it, each identified by a custom alias: server1, server2, and server3. Be sure to replace the highlighted IPs with the IP addresses of your Ansible hosts.

Step 3 — Testing Connection with Ansible as DevOps

After setting up the inventory file to include your servers, it’s time to check if Ansible is able to connect to these servers and run commands via SSH.

For this guide, we’ll be using the Ubuntu root account because that’s typically the only account available by default on newly created servers. If your Ansible hosts already have a regular sudo user created, you are encouraged to use that account instead.

If this is the first time you’re connecting to these servers via SSH, you’ll be asked to confirm the authenticity of the hosts you’re connecting to via Ansible. When prompted, type yes and then hit ENTER to confirm.

Once you get a “pong” reply back from a host, it means you’re ready to run Ansible commands and playbooks on that server.

  • Note:

If you are unable to get a successful response back from your servers, check our Ansible Cheat Sheet Guide for more information on how to run Ansible commands with different connection options.

Step 4 — Running Ad-Hoc Commands with Ansible (Optional)

After confirming that your Ansible control node is able to communicate with your hosts, you can start running ad-hoc commands and playbooks on your servers.

Any command that you would normally execute on a remote server over SSH can be run with Ansible on the servers specified in your inventory file. 

Ansible Communication

Ansible is an agentless automation tool; means no need to install any agent on the nodes which Ansible manages. Instead, Ansible control machine communicates to the nodes via SSH.

 We have to enable SSH communication between control machines and nodes before executing any playbook.

There are 2 ways SSH communication can be setup:

  • Create a ssh key from control machine and propogate to the nodes
  • Pass the credentials via inventory file

We will setup both ways now.

Via inventory file

In the inventory file, pass ansible_ssh_user and ansible_ssh_pass along with the node’s IP address or FQDN as below.

[node1]

210.0.0.2 ansible_ssh_user=root ansible_ssh_pass=password

Via SSH key

  1. Generate a SSH key in the control machine as below

1$ ssh-keygen -t rsa -b 4096

keygen

2. Copy the ssh key that is created to the node using the following command

1$ ssh-copy-id [email protected]

3. Verify connection once

1$ ssh [email protected]

Now that ssh connection is successfully established

Test the communication

Now we can test the communication between the control machine and the node using few ansible modules as below and therefore confer to implementing DevOps with Ansible efficiently.

  • Ping the node machine

1$ ansible -m ping node1

ping
  • Find node machine’s uptime

1$ ansible -m command -a uptime node1

up

SSH Connection established successfully !!!! Now the Control machine can communicate to the node.

Ansible Inventory

Ansible works against multiple managed nodes or “hosts” in your infrastructure at the same time, using a list or group of lists known as inventory. 

Once your inventory is defined, you use patterns to select the hosts or groups you want Ansible to run against.

The default location for inventory is a file called /etc/ansible/hosts. You can specify a different inventory file at the command line using the -i <path> option. You can also use multiple inventory files at the same time, and/or pull inventory from dynamic or cloud sources or different formats.

implementing devops with ansible

Ansible ad hoc execution

Ad hoc commands are commands which can be run individually to perform quick functions. These commands need not be performed later.

For example, you have to reboot all your company servers. For this, you will run the Adhoc commands from ‘/usr/bin/ansible’.

These ad-hoc commands are not used for configuration management and deployment, because these commands are of one time usage.

Ansible playbook

Playbooks are the files where Ansible code is written. Playbooks are written in YAML format. 

Ansible YAML Structure

YAML stands for Yet Another Markup Language. Playbooks are one of the core features of Ansible and tell Ansible what to execute. They are like a to-do list for Ansible that contains a list of tasks. Playbooks contain the steps which the user wants to execute on a particular machine.

The Ansible structure is agentless, and configurations are set up as playbooks written in YAML. The tool uses Secure Socket Shell (SSH) rather than agents, which are the structural connections for many other configuration management tools.

Ansible Tower

Ansible Tower is like Ansible at a more enterprise level. It is a web-based solution for managing our organization with an easy user interface that provides a dashboard with all of the state summaries of all the hosts.

The tower allows us to share the SSH credentials without exposing them, logs all the jobs, manage inventories graphically, and syncs them with a wide variety of cloud providers.

Previously, Ansible Tower, called the AWX project, was the fix to this problem. Especially those that render better as graphical rather than text-based output, such as real-time node monitoring.

Ansible Galaxy

Galaxy provides pre-packaged units of work known to Ansible as roles and collections. Content from roles and collections can be referenced in Ansible PlayBooks and immediately put to work. You’ll find content for provisioning infrastructure, deploying applications, and all of the tasks you do everyday.

Why configuration Management?

implementing devops with ansible

Some of the key benefits of Configuration Management include:

plutora.com

  • Increased efficiency with a defined configuration process that provides control and improves visibility with tracking.
  • Cost reduction by having detailed knowledge of all the elements of the configuration which allows for unnecessary…
  • Your business will have greater agility and faster problem resolution, giving a better quality of service for your…
  • Enhanced system and process reliability through more rapid detection and correction of improper.

Ansible Modules – shell vs. command

implementing devops with ansible

Command module will be executed without passing through the shell while the shell module will be executed but affected by environment variables.

Passing Variables On The Command Line

In addition to vars_prompt and vars_files, it is possible to send variables over the Ansible command line. This is particularly useful when writing a generic release playbook where you may want to pass in the version of the application to deploy:

This is useful, for, among other things, setting the hosts group or the user for the playbook.

Example:

– hosts: ‘{{ hosts }}

  remote_user: ‘{{ user }}

  tasks:

  – …

ansible-playbook release.yml –extra-vars “hosts=vipers user=starbuck”

As of Ansible 1.2, you can also pass in extra vars as quoted JSON, like so:

–extra-vars ‘{“pacman”:”mrs”,”ghosts”:[“inky”,”pinky”,”clyde”,”sue”]}’

The key=value form is obviously simpler, but it’s there if you need it!

  • Note

Values passed in using the key=value syntax are interpreted as strings. Use the JSON format if you need to pass in anything that shouldn’t be a string (Booleans, integers, floats, lists etc).

As of Ansible 1.3, extra vars can be loaded from a JSON file with the @ syntax:

–extra-vars “@some_file.json”

Also as of Ansible 1.3, extra vars can be formatted as YAML, either on the command line or in a file as above.

Variable Precedence: Where Should I Put A Variable?

A lot of people may ask about how variables override one another. Ultimately it’s Ansible’s philosophy that it’s better you know where to put a variable, and then you have to think about it a lot less.

Avoid defining the variable in many places instead ask the question “which variable is being used”. However, let’s go ahead and get precedence out of the way! It exists. It’s a real thing, and you might have a use for it.

If multiple variables of the same name are defined in different places, they get overwritten in a certain order which would then make the variables complicated.

Conclusion

To not make processes and configurations complicated it is therefore suggested that Ansible must be used. However, other tools are great to go with but for the learning phase implementing DevOps with Ansible is considerable and a wise choice to make. Therefore it is reviewed that Ansible is one of the best automation tool one can choose from. Hope that the course insight was worthwhile for you as a reader and learner and would have made you extract the most from it. Happy learning!

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Please wait while we load…

Need Help? Chat with us
Please accept our privacy policy first to start a conversation.