Ansible Tutorial

Ansible is a fully accessible IT engine that streamlines IT tools like intra-service orchestration, application deployment, cloud provisioning, and so on. In this ansible tutorial we are going to cover the basic and advanced concepts that benefit both the freshers and experienced ones. Through this content we are going to learn and interpret the concept such as what is ansible, why ansible, history, installation of ansible, ad-hoc commands, ansible playbooks, ansible roles, variables, commands, and YAML, etc.

What is Ansible?

Ansible is an open source configuration, system integration, and software delivery automation and orchestration tool. Ansible can operate and customise Unix-like and Windows devices aim of providing cloud infrastructure. For structure management and integration, it includes its own descriptive computer program.

Ansible is well-known for its easy installation, ease of use in terms of client connectivity, absence of agents for Ansible clients, and wide range of skills. It works by connecting to the clients via SSH, eliminating the need for a special agent on the client side, and by pushing modules to the clients, which are then performed internally on the client side and the output is displayed back to the ansible server.

As it employs SSH, it can connect directly to customers via SSH-Keys, greatly streamlining the process. Inventory files store client information such as hostnames, IP addresses, and SSH ports. Ansible can use an inventory file that you have created and filled out.

Why Ansible?

Ansible is an open source confi

Here are some of the important benefits of using the ansible. They are:

  • Everyone can use Ansible for free.
  • Ansible is very consistent and lightweight, with no restrictions imposed by the operating system or underlying hardware.
  • Because of its agentless capabilities and open SSH security features, it is extremely secure.
  • Ansible requires special system administrator skills to install or use.
  • Ansible has a seamless learning curve due to its extensive documentation and simple structure and configuration.
  • Ansible's modularity in terms of plugins,inventories, modules, and playbooks makes it an ideal companion for orchestrating large environments.

Become a Ansible Certified professional by learning this HKR Ansible Training !

History of Ansible:

Here are some of the important points related to the history of ansible are:

  • Ansible was created by Michael DeHaan, and the Ansible project began in February 2012.
  • Cobbler and Func's creator is also the Fedora Unified network's controller.
  • In 2015, RedHat purchased the Ansible tool.
  • Ansible is included with the Fedora Linux distribution.
  • Ansible is also obtainable for RedHat Enterprise Linux, Debian, CentOS, Oracle Linux, and Scientific Linux through Extra Packages for Enterprise Linux (EPEL) and Ubuntu, among other operating systems.

Workflow of Ansible:

Ansible works by connecting to your nodes and sending them small programs known as modules. In Ansible, modules are used to complete automation tasks.These programs are designed to be resource models of the system's desired state. Ansible then runs these modules and removes them when they are finished.To complete tasks without modules, you would have to rely on ad hoc commands and scripting.

IMAGE 

Ansible is agentless, that also means it does not involve any software to be installed on the nodes it manages.Ansible reads data from your inventory to determine which machines you want to manage. Although Ansible comes with a default inventory file, you can create your own and specify which servers you want Ansible to manage.

Ansible connects to servers and runs tasks using the SSH protocol.Ansible attaches to remote machines using your current user name and SSH keys by default. Root access is not required.Ansible connects to the remote machine(s) and transfers the modules required by your command or playbook for execution.

Ansible employs human-readable YAML templates, allowing users to automate repetitive tasks without having to learn a complex programming language.You can use Ansible's built-in modules to automate tasks, or you can write your own. Ansible components can be written in any language that supports JSON output, such as Ruby,Python, or bash. Powershell is even used to write Windows automation modules.

Ansible Architecture

The Ansible orchestration engine communicates with the user who is writing the Ansible playbook in order to execute the Ansible orchestration and interact with private or public cloud services and a configuration management database. In the below diagram you can explain each and every component in detail.

IMAGE

  • Inventory is a list of nodes or hosts with their IP addresses, databases, servers, and so on that must be managed.
  • APIs are acronyms for Application Programming Interfaces. The Ansible APIs serve as a conduit for public or private cloud services.
  • Ansible modules linked the nodes and distributed the Ansible modules programs. Ansible runs the modules and then removes them. These modules can run on any machine; there is no need for a database or servers. To keep track of the changes in the content, you can use the text editor of choice, a terminal, or a version control system.
  • Plugins A plugin is a piece of code that extends Ansible's core functionality. There are numerous useful plugins available, and you can also create your own.
  • Playbooks are made up of your written code and are written in YAML format, which describes the tasks and runs them through Ansible. You can also use playbooks to launch tasks both synchronously and asynchronously.
  • Hosts: In the Ansible architecture, hosts are the node systems that Ansible automates, as well as any machine such as RedHat, Linux, Windows, and so on.
  • Ansible is used to automate various networks, and it employs a simple, secure, and powerful agentless automation framework for IT operations and development. It employs a data model that is distinct from the Ansible automation engine.
  • A cloud is a network of remote servers where data can be stored, managed, and processed. These servers are hosted on the internet and store data remotely rather than locally on the server. It simply launches the resources and instances on the cloud, connects them to the servers, and you have a good understanding of remotely operating your tasks.
  • A CMDB is a type of repository that serves as a data warehouse.

Related Article:Terraform vs Ansible

Installation of Ansible in Linux environment

When you've compared and weighed your options, and you've decided on Ansible. Then you should install it on your system. Let's walk through the installation process in various Linux distributions, such as:

Basic requirements:

  • PyYAML is a YAML parser and emitter written in Python.
  • Httplib2 is a large HTTP client library.
  • Paramiko is a Python-native SSHv2 protocol library.
  • RHEL/ CentOS/ Debian/ Ubuntu Linux are the available distributions.
  • Jinja2 is a modern and user-friendly Python templating language.
  • sshpass is a non-interactive ssh password authentication utility.

Here we are going to explain  the installation step by step.

Installation on Redhat centos systems:

Step1: Install the EPEL repo

[root@ansible-server ~]# sudo yum install epel-release  

Step2: Install the ansible package

[root@ansible-server ~]# sudo yum install -y ansible  

Installation on Ubuntu systems:

Step1:First, perform a package update.

$ sudo apt update   

Step2: Install the software properties common package

$ sudo apt install software-properties-common  

Step3:Install the ansible personal package archive

$ sudo apt-add-repository ppa:ansible/ansible  

Step4: Install the ansible

$ sudo apt update  

$ sudo apt install ansible  

Install the Ansible using pip:

The pip command is a Python package installation and management tool.

Step1: It wiek son the Linux and Unix systems

$ sudo pip install ansible   

Installing the latest version of ansible:

Using portage:

$ emerge -av app-admin/ansible  

In order to install the latest version, you need to uninstall the ansible package before emerging.

$ echo 'app-admin/ansible' >> /etc/portage/package.accept_keywords  

Using pkg:
Ansible supports both Python 2 and Python 3, and FreeBSD has different packages for each python version. To install, follow these steps:

$ sudo pkg install py27-ansible  

You can install from ports as well.

$ sudo make -C /usr/ports/sysutils/ansible install  

Using OpenCSW:

Ansible is available as a SysV package from openCSW for Solaris:

  1. # pkgadd -d http://get.opencsw.org/now  
  2. # /opt/csw/bin/pkgutil -i ansible 

Using pacman:

Ansible is available in the community repository.

  • $ pacman -S ansible  

Installing using yum:

On fedora:

  • $ sudo dnf install python-argcomplete  

On RHEL and centos:

  • $ sudo yum install epel-release  
  • $ sudo yum install python-argcomplete  

By using apt:

  • $ sudo apt install python-argcomplete  

By using pip

  • $ pip install argcomplete  

Ansible Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Ad-hoc commands:

Ad-hoc commands serve as the easiest way to use the Ansible. They are advantageous when using commands on the multiple servers. By using these ad-hoc commands you can interact very easily with the servers. All the ad-hoc commands use the /usr/bin/ansible command line tool in order to automate a single task on multiple or single nodes. They are very quick and easy and are not preferred for re-use. These commands help in explaining the perfectness of the Ansible.

Syntax: ansible  [-m ] -a <"arguments"> -u  [--become]  
  • Hosts:In the inventory for indicating the hosts we use all or “*”.
  • Module_name:It serves as an optional parameter, by default it is a command and also there are several modules such as yum, apt, file, shell, etc.
  • Arguments:In this section we are going to pass the values that are required by the specific module.
  • Username:It is the command execution environment 
  • Become:It is an optional parameter and we use it when there is need to perform operations that require sudo privilege and by default it is set to false.

Top 30 frequently asked Ansible Interview Questions !

The different types of Ad-hoc commands are

  • Parallelism and shell commands

By setting up the SSH agent you can reboot your company server in 12 parallel  times at the same time. 

$ ssh-agent bash  

$ ssh-add ~/.ssh/id_rsa  

To perform a reboot for all your company servers in 12 times as group you need to use the following option.

$ ansible abc -a "/sbin/reboot" -f 12  

By default all the commands run from the current username account, if you want to change to another username the following option is required.

$ ansible abc -a "/sbin/reboot" -f 12 -u username  

  • File Transfer

By using the ad-hoc commands you can securely transfer files from one machine to another.For transferring files from one machine to server we use the following option.

$ ansible abc -m copy -a "src = /etc/yum.conf dest = /tmp/yum.conf"  

In order to create a new directory we use:

$ ansible abc -m file -a "dest = /path/user1/new mode = 888 owner = user1 group = user1 state = directory"   

And for deleting all the directories and files we use the following option as follows:

$ ansible abc -m file -a "dest = /path/user1/new state = absent"  

  • Managing packages

Ad-hoc commands are primarily used for yum and apt modules. In order to check whether the yum package is installed or not the following options are required.

To Check whether the yum is installed we use:

$ ansible abc -m yum -a "name = demo-tomcat-1 state = present"  

To check whether the yum package is not installed we use:

$ ansible abc -m yum -a "name = demo-tomcat-1 state = absent"   

In order to check whether the latest version is installed or not we use:

$ ansible abc -m yum -a "name = demo-tomcat-1 state = latest"   

Managing users and groups
In order to create, remove or manage the user account on the managed nodes  we use the following commands:

$ ansible all -m user -a "name=foo password="  

$ ansible all -m user -a "name=foo state=absent"  

  • Gathering facts:

In order to known the discovered variable about the system we use:

$ ansible all -m setup  

  • Managing services

Ensuring whether the service is started on the webs servers we use:

$ ansible webservers -m service -a "name=httpd state=started"  

Restart a web service on all the web servers we use:

$ ansible webservers -m service -a "name=httpd state=restarted"  

In order to stop the service we use:

$ ansible webservers -m service -a "name=httpd state=stopped"  

Related Article:Ansible sheell vs command !

Ansible playbooks:

Playbooks are the files that contain the Ansible code. Playbooks are written in the YAML language. Because YAML stands for "Yet Another Markup Language," there isn't much syntax required. Playbooks are one of Ansible's core features; they tell Ansible what to execute and are used in complex scenarios. They provide greater adaptability.

Playbooks comprise the steps that the user wants to run on a specific machine. And playbooks are executed in a sequential order. Playbooks serve as the foundation for all Ansible use cases. Ansible playbooks are more akin to configuration languages than programming languages.You can assign specific roles to some of the hosts and other roles to other hosts using a playbook. You can assign particular roles to some of the hosts and other roles to other hosts using a playbook. This allows you to organise virtual computers in very various outcomes in a single playbook.

Playbook structure:

Each playbook is made up of one or more plays. Plays are used to structure playbooks. A playbook may contain more than one play.

IMAGE

The play's function is to track a structured set of instructions against some specific host. There are various YAML authors available,but I chose to use a straightforward editor such as notepad++. To begin, open notepad++ and copy-paste the following YAML, then change the language to YAML. A YAML starts with 3 hyphens --- always.


In order to create the playbook the following basic syntax and save it as test.yml


---  

   name: install and configure DB  

   hosts: testServer  

   become: yes  

   vars:   

      oracle_db_port_value : 1521  

  tasks:  

   -name: Install the Oracle DB  

      yum:   

  -name: Ensure the installed service is enabled and running  

   service:  

      name:  

Ansible roles:

Roles provide a structure for completely self-contained or interdependent collections of files, tasks, templates, variables, and modules.The primary mechanism for dividing a playbook into multiple files is the role. This simplifies the creation of complex playbooks and makes them more reusable. The playbook can be broken down into reusable components thanks to the playbook breaking.

Each role is restricted to a single functionality or desired output, with all of the steps required to achieve that result occurring either within the same role or in other roles listed as dependencies.Playbooks do not exist for roles. Roles are small pieces of functionality that can be used independently within the playbooks. Roles do not have a specific setting that determines which hosts the role will apply to.

Top-level playbooks serve as a link between the hosts in your inventory file and the roles that should be assigned to those hosts.

Creating a role:

Role structure is required to create the new role such as:role structure, usage and options.

Role structure: The riles had a saturated layout on the system and the default role structure is:

$ ansible-galaxy -h   

Subscribe to our youtube channel to get new updates..!

Usage:

ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ...   

Options:

  • -h it shows help mode.
  • -v verbose mode.
  • --v it shows program version number and exit status.

Ansible variables:

The variable in a playbook is very similar to the variable in a programming language. It allows you to give a variable a value and use it anywhere in the playbook. You can use the variables in the playbook by putting conditions around their values.

Creation of valid variable names:

You need to create the valid variable names for using the variables.And variables should be letters, numbers and underscores. Foo_port is a valid variable name and Foo-port is an invalid variable name.

YAMl supports the libraries that map keys to values such as:

Foo:

Field1:one

Field2:two

Then you can reference to a specific field as follows:

foo[‘Field’]

Foo.field1

Ansible tags:

When you have a large playbook, it is useful to be able to run only a portion of it rather than the entire playbook. For this reason, Ansible includes a tag attribute.When you implement tags to items, you can control whether or not they are executed by including command-line options.

When you run a playbook, you can exhaust tasks based on tags in two ways, for example:

  • Using the -tags or -skip-tags options on the command line.
  • With the TAGS RUN and TAGS SKIP options in Ansible configuration settings.

Ansible command cheat sheet:

The commands used in ansible are:

  • To install EPEL repo on Centos/RHEL systems.

[root@ansible-server ~]# sudo yum install epel-release  

  • To install Ansible packages on Centos/RHEL systems.

[root@ansible-server ~]# sudo  yum install -y ansible  

  • To perform an update to the packages on Debian/Ubuntu systems.

$ sudo apt update  

  • To install the software properties-common-package on Debian/Ubuntu systems.

$ sudo apt install software-properties-common  

  • To install Ansible personal package archive on Debian/Ubuntu systems.

$ sudo apt-add-repository ppa:ansible/ansible  

  • To install Ansible on Debian/Ubuntu systems.

$ sudo apt update  

$ sudo apt install ansible  

  • To issue a ping command on all servers defined in the inventory file named hosts.

[root@ansible-server test_ansible]# ansible -i hosts all -m ping  

  • To issue a ping command only on hosts2.            

[root@ansible-server test_ansible]# ansible -i hosts all -m ping --limit host2  

  • To copy the file "testfile" on all hosts in the inventory file.

[root@ansible-server test_ansible]# ansible -i hosts all -m copy -a "src=/root/test_ansible/testfile dest=/tmp/testfile"  

  • To install the ncdu package on all hosts.

[root@ansible-server test_ansible]# ansible -i hosts all -m yum -a 'name=ncdu state=present'  

  • To remove the ncdu package on all hosts.

[root@ansible-server test_ansible]# ansible -i hosts all -m yum -a 'name=ncdu state=absent'  

  • To build the directory structure for the role named role1.

[root@ansible-server test2]# ansible-galaxy init role1  

To dry-run p4.yml playbook.

[root@ansible-server test_ansible]# ansible-playbook -i hosts p4.yml --check  

  • To run a p4.yml playbook with password authentication for all hosts.

[root@ansible-server test_ansible]# ansible-playbook -i hosts p4.yml -k  

Ansible modules

Ansible modules are discrete units of code that can be used from the command line or as part of a playbook task.In Ansible, modules are also known as task plugins or library plugins.Ansible comes with a set of modules known as the module library, which can be executed directly or remotely via the playbook.

Modules can also be written by users. These modules can control things like services, system resources, files, and packages, as well as handle system command execution.

Let's take a look at how to run three different modules from the command line.

  • ansible webservers -m service -a "name=httpd state=started"  
  • ansible webservers -m ping  
  • ansible webservers -m command -a "/sbin/reboot -t now"  

Taking arguments is supported by all modules. Generally, all modules accept key=value arguments that are separated by spaces.Some modules require no arguments, while shell/command modules require the command string to be executed.

Ansible modules execute in a manner very similar to that of a playbook, such as:
- name: reboot the servers  

command: /sbin/reboot -t now  

Another method for passing arguments to a module that uses YAML syntax is known as complex args.


- name: restart webserver  

  service:  

    name: httpd  

    state: restarted  


Technically, all modules return JSON format data, but you don't need to know much about that if you're using command line or playbooks. If you're writing your module, it means you don't have to write modules in any language other than the one you choose. 

Modules should be invertible, meaning they should not make changes if the current state matches the desired final state. When using Ansible playbooks, these modules can cause "change events" by informing "handlers" to perform additional tasks.The Ansible-doc tool can be used from the command line to access documentation for each module:

ansible-doc yum  

Ansible Templates:

A template is a document that stores all of your configuration parameters, but the flexible values are specified in Ansible as variables. The variables will be supplemented with the influencing factors mostly during playbook execution, depending on the severity including which cluster you are using.

With the Jinja2 templating engine, you can do more than just replace variables. Loops, conditional statements, macros, filters for data transformation, arithmetic calculations, and so on are all possible.

Typically, template files can have the.j2 extension, which signifies the use of the Jinja2 templating engine.

The variables in a template file will be denoted by double curly braces, '{{variables}}'.

While using the Ansible Template module, we need two parameters, such as:

  • src: The template file's source. It can take both a relative and an absolute path.
  • dest: The remote server's destination path is denoted by dest.

The template module attributes are force, mode,backup and group.
Ansible YAML:
YAML is used to identify setup, which has grown in popularity in recent years thanks to the use of Ansible and SaltStack.In contrast to other regular data formats such as XML or JSON, YAML is easier for humans to read and write. Most programming languages include libraries for working with YAML.
Every YAML file in Ansible begins with a list. Each item in the list is a collection of key-value pairs, also known as a "hash" or "dictionary." As a result, we must understand how to write lists and dictionaries in YAML.YAML has another minor quirk. All YAML files can preferably begin and end with ---. This is part of the YAML format and represents the beginning and end of a document.
A list's members are all lines that begin at the same indentation level, beginning with a "-" (a dash and space):


Example:


---  
# A list of flowers  

- Rose

- Lilly 

- Jasmine  

- Lotus  

---

Ansible Training

Weekday / Weekend Batches

Ansible Commands:

The Ansible command module is often used to execute any commands or scripts on a remote target machine. Alternatively, it can be used to execute commands on a remote node.The command module is used to execute simple Linux commands on a remote node or server that is a member of the host group or a standalone server that is mentioned in the host group.

The shell module should be used when we need to run a command in a remote server's shell of your choice. By default, the commands are executed through the /bin/sh shell. You can use various operations such as '|', ", '>', and so on, as well as environmental variables such as $HOME.

Ansible inventory:

The inventory is a list or group of lists that Ansible uses to work against multiple managed hosts in your infrastructure at the same time.Once an inventory has been defined, you can use patterns to select which hosts or groups to run Ansible against.

The inventory file's default location is /etc/ansible/hosts. You can also use the -i path> option to specify a different inventory file at the command line. The inventory file can be retrieved from dynamic or cloud sources, or in a variety of formats (YAML, ini). Ansible has inventory plugins that allow it to be flexible and customizable.

Ansible debug:

Ansible includes a debug module that makes tasks easier to manage. It is a useful tool for determining any problem areas.Ansible version 2.1 added a verbosity parameter to the debug module, converting it from a print line.
Example:


--  

- name: Debug Example - Hello World  

hosts: localhost  

tasks:  

- name: Print debug message  

debug:  


Ansible file:
The Ansible file module has been used to create and delete files or folders on a remote server. You can also create and delete directories, as well as change the data's permissions.You can also make and delete soft links (symlinks) and hard links. You can change the permissions of files using the Ansible file module.
For creating and deleting the file in the remote server we mainly use two parameters such as path and state. Path is nothing but the path of the file in the remote server and state parameter mention the touch.
Ansible Vault:
The Ansible Vault feature enables users to encrypt values and data structures within Ansible projects. This allows you to secure any secrets or sensitive data that is required to run Ansible plays but should not be publicly visible, such as private keys or passwords. When the key is provided, Ansible automatically decrypts the vault-encrypted content at runtime.
To incorporate these secrets with regular Ansible data, both the Ansible and Ansible-playbook commands, which are used to execute ad hoc tasks and structured playbooks, have support for decrypting vault-encrypted content at runtime. Ansible Vault is built with file-level granularity, which means that files are either completely encrypted or unencrypted. It employs the AES256 algorithm to provide symmetric encryption.
Comparing with other tools:

Ansible vs chef vs puppet
Definition:

  • Ansible:Ansible is a free and open-source IT engine for automating application deployment, cloud provisioning, intra-service orchestration, and other IT tools.
  • Chef:The chef is a robust automation platform that converts infrastructure into code. Whether you are running on-premises, in the cloud, or in a hybrid environment.
  • Puppet:Puppet is a server configuration management tool that can be used to configure, deploy, and manage servers.

Setting up:

  • Ansible is only running a master on the server machine, but no agents are running on the client machine. It logs in to client systems or the nodes you want to configure via an SSH connection. Client machine virtualization does not necessitate any special configuration. That is why it is quicker to set up!
  • Chef's architecture is based on a master-agent model. Chef server is installed on the master machine, and Chef client is installed on each client machine as an agent. There is also an additional component known as workstation, which contains all of the tested configurations and is then pushed to the central chef server. That is why it is not so simple.
  • Puppet has a master-agent architecture as well. Puppet server is installed on the master machine, and Puppet clients are installed on the client machine as an agent. Following that, a certificate signing occurs between the agent and the master. That is why it is difficult to set up.

Interoperability:

  • The Ansible server must be installed on a Linux/Unix machine. Ansible also works on Windows machines.
  • Puppet Master is only available for Linux/Unix, but Puppet Agent is also available for Windows.
  • Chef Server is only available on Linux/Unix, but Chef Client and Workstation are also available on Windows.

Configuration Language:

  • Ansible makes use of YAML (Python). It is simple to learn and geared toward administrators.Python is built into the majority of Unix and Linux deployments, making it easier to get the tool up and running.
  • Chef employs the Ruby Domain Specific Language (Ruby DSL). It has a steep learning curve and is geared toward developers.
  • Puppet employs a puppet Domain Specific Language (Puppet DSL). It is difficult to learn and is geared toward system administrators.
Conclusion

In the above ansible tutorial all the concepts are covered in depth. This tutorial will help learners and professionals as well in order to get deep insights of the ansible platform at a glance. Moreover if you find any information or topic not covered in the tutorial please drop a message in the comments section, we will definitely consider them. 

Find our upcoming Ansible Training Online Classes

  • Batch starts on 22nd May 2021, Weekend batch

  • Batch starts on 26th May 2021, Weekday batch

  • Batch starts on 30th May 2021, Weekend batch

Global Promotional Image
 

Categories

Request for more information

Webinar

Python tutorial for beginners

5th April | 08:00 AM

150 Registered

Srivalli
Srivalli
Research Analyst
As a senior technical content writer for HRK tainings, srivalli patchava has a greater understanding of today's data-driven environment, which includes key aspects of data management and IT organizations. She manages the task of creating great content in the areas of software testing, DevOps, Robotic process automation. Connects with her on Linkedin and Twitter.