Ansible tutorial provides basic and advanced concepts of Ansible. Our Ansible tutorial is designed for beginners and professionals.
Ansible is an open-source IT engine which automates the IT tools such as intra service orchestration, application deployment, cloud provisioning, etc.
In this tutorial, we are going to discuss the following topics:
- What is Ansible?
- Why use Ansible
- Ansible History
- How Ansible Works?
- Terms used in Ansible
- Ansible Installation in Linux
- Ansible Playbooks
- Ansible Tower
- Ansible Roles
- Ansible Variables
- Ansible Modules
- Ansible Tags
- Ansible Galaxy
- Ansible Commands Cheat Sheets
What is Ansible?
Ansible is an open-source IT engine that automates application deployment, cloud provisioning, intra service orchestration, and other IT tools.
Ansible is easy to deploy because it does not use any agents or custom security infrastructure on the client-side, and by pushing modules to the clients. These modules are executed locally on the client-side, and the output is pushed back to the Ansible server.
It can easily connect to clients using SSH-Keys, simplifying though the whole process. Client details, such as hostnames or IP addresses and SSH ports, are stored in the files, which are called inventory files. If you created an inventory file and populated it, then Ansible can use it.
Ansible uses the playbook to describe automation jobs, and playbook, which uses simple language, i.e., YAML. YAML is a human-readable data serialization language & commonly used for configuration files, but it can be used in many applications where data is being stored.
A significant advantage is that even the IT infrastructure support guys can read and understand the playbook and debug if needed.
Ansible is designed for multi-tier deployment. Ansible does not manage one system at a time, and it models IT infrastructure by describing all of your systems are interrelated. Ansible is entirely agentless, which means Ansible works by connecting your nodes through SSH (by default). Ansible gives the option to you if you want another method for the connection like Kerberos.
Ansible pushes small programs after connecting to your nodes which are known as "Ansible Modules". Ansible runs that module on your nodes and removes them when finished. Ansible manages the inventory in simple text files (These are the host's files). Ansible uses the host file where one can group the hosts and can control the actions on a specific group in the playbooks.
Why Use Ansible
Here are some important reasons for using Ansible, such as:
- Ansible is free to use by everyone.
- Ansible is very consistent and lightweight, and no constraints regarding the operating system or underlying hardware are present.
- It is very secure due to its agentless capabilities and open SSH security features.
- Ansible does not need any special system administrator skills to install and use it.
- Ansible has a smooth learning curve determined by the comprehensive documentation and easy to learn structure and configuration.
- Its modularity regarding plugins, inventories, modules, and playbooks make Ansible perfect companion orchestrate large environments.
Here are some essential points from the history of Ansible, such as:
- Michael DeHaan developed Ansible, and the Ansible project began in February 2012.
- The creator of Cobbler and Func is also the controller of the Fedora Unified network.
- RedHat acquired the Ansible tool in 2015.
- Ansible is included as part of the Fedora distribution of the Linux.
- Ansible is also available for RedHat Enterprise Linux, Debian, CentOS, Oracle Linux, and Scientific Linux via Extra Packages for Enterprise Linux (EPEL) and Ubuntu as well as for other operating systems.
How Ansible Works?
Ansible works by connecting to your nodes and pushing out a small program called Ansible modules to them. Then Ansible executed these modules and removed them after finished. The library of modules can reside on any machine, and there are no daemons, servers, or databases required.
In the above image, the Management Node is the controlling node that controls the entire execution of the playbook. The inventory file provides the list of hosts where the Ansible modules need to be run. The Management Node makes an SSH connection and executes the small modules on the host's machine and install the software.
Ansible removes the modules once those are installed so expertly. It connects to the host machine executes the instructions, and if it is successfully installed, then remove that code in which one was copied on the host machine.
Terms used in Ansible
Here are some important terms which are used in Ansible, such as:
|Ansible Server||It is a machine where Ansible is installed and from which all tasks and playbooks will be executed.|
|Modules||The module is a command or set of similar commands which is executed on the client-side.|
|Task||A task is a section which consists of a single procedure to be completed.|
|Role||It is a way of organizing tasks and related files to be later called in a playbook.|
|Fact||The information fetched from the client system from the global variables with the gather facts operation.|
|Inventory||A file containing the data regarding the Ansible client-server.|
|Play||It is the execution of the playbook.|
|Handler||The task is called only if a notifier is present.|
|Notifier||The section attributed to a task which calls a handler if the output is changed.|
|Tag||It is a name set to a task that can be used later on to issue just that specific task or group of jobs.|
Ansible Installation in Linux
When you have compared and weighed your options and decided to go for Ansible. Then installed it on your system. Let's go step by step of the installation in different Linux distributions, such as:
Install Ansible on RedHat/Centos systems
Step 1: Install the EPEL repo
Step 2: Install the Ansible package.
Install Ansible on Debian/Ubuntu systems
Step 1: First perform an update to the packages
Step 2: Then install the software properties common package.
Step 3: And install the Ansible personal package archive.
Step 4: Install the Ansible.
Playbooks are the files where the Ansible code is written. Playbooks are written in YAML format. YAML means "Yet Another Markup Language," so there is not much syntax needed. Playbooks are one of the core features of Ansible and tell Ansible what to execute, and it is used in complex scenarios. They offer increased flexibility.
Playbooks contain the steps which the user wants to execute on a particular machine. And playbooks are run sequentially. Playbooks are the building blocks for all the use cases of Ansible.
Ansible playbooks tend to be more configuration language than a programming language.
Through a playbook, you can designate specific roles to some of the hosts and other roles to other hosts. By doing this, you can orchestrate multiple servers in very different scenarios, all in one playbook.
Each playbook is a collection of one or more plays. Playbooks are structured by using Plays. There can be more than one play inside a playbook.
The function of the play is to map a set of instructions which is defined against a particular host.
There are different YAML editors, but prefer to use a simple editor such as notepad++. First, open the notepad++ and copy-paste the below YAML and change the language to YAML (Language → YAML).
A YAML starts with --- (3 hyphens) always.
Create a Playbook
Let's start by writing an example YAML file. First, we must define a task. These are the interface to ansible modules for roles and playbooks.
One playbook with one play, containing multiple tasks looks like the below example.
Above is a basic syntax of a playbook. Save it in a file as test.yml. A YAML syntax needs to follow the correct indentation.
Here are some YAML tags are given below, such as:
|Name||It specifies the name of the Ansible Playbooks.|
|Hosts||It specifies the lists of the hosts against which you want to run the task. And the host's Tag is mandatory. It tells Ansible that on which hosts to run the listed tasks. These tasks can be run on the same machine or the remote machine. One can run the tasks on the multiple machines, and the host's tag can have a group of host's entry as well.|
|Vars||Vars tag defines the variables which you can use in your playbook. Its usage is similar to the variables in any programming language.|
|Tasks||Tasks are the lists of the actions which need to perform in the playbooks. All the playbooks should contain the tasks to be executed. A task field includes the name of the task. It is not mandatory but useful for debugging the playbook. Internally each task links to a piece of code called a module. A module should be executed, and arguments that are required for the module you want to run.|
Ansible Tower is like Ansible at a more enterprise level. It is a web-based solution for managing your organization with an easy user interface that provides a dashboard with all of the state summaries of all the hosts. And allows quick deployments, and monitors all configurations.
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, is the fix to this problem. Especially those that render better as graphical rather than text-based output, such as real-time node monitoring.
Prerequisites to Install Ansible Tower
There is the following prerequisite to install the Ansible Tower, such as:
- The following operating systems support Ansible Tower
- RedHat Enterprise Linux 6 64-bit
- RedHat Enterprise Linux 7 64-bit
- CentOS 6 64-bit
- CentOS 7 64-bit
- Ubuntu 12.04 LTS 64-bit
- Ubuntu 14.04 LTS 64-bit
- Ubuntu 16.04 LTS 64 bit
- You should have the latest stable release of Ansible.
- It required a 64-bit support kernel, runtime, and 20 GB hard disk.
- Minimum 2 GB RAM (4 GB RAM recommended) is required.
- Minimum 2 GB RAM is recommended for Vagrant trial installations
- And 4 GB RAM is recommended /100 forks
Ansible Tower Features
Here are some features of the Ansible Tower, such as:
1. Ansible Tower Dashboard: It displays everything which is going on in your Ansible environment, such as the inventory status, the recent job activity, the hosts, and so on.
2. Multi-Playbook Workflows: It allows to chain any numbers of playbooks, any way of the usage of different inventories, runs different users, or utilizes various credentials.
3. Real-Time Job Updates: Ansible can automate the complete infrastructure. Also, you can see real-time job updates such as plays and tasks broken down by each machine either been successful or failure. Therefore you can see the status of your automation and know what's next in the queue.
4. Scale Capacity with Cluster: You can connect multiple Ansible Tower nodes into an Ansible Tower cluster as the clusters add redundancy and capacity, which allows scaling Ansible automation across the enterprise.
5. Self-Service: You can launch playbooks with just a single click through this feature.
6. Remote Command Execution: With this command, you can run simple tasks such as restart any malfunctioning service, add users, reset passwords on any host or group of hosts in the inventory.
7. Manage and Track Inventory: It manages your entire infrastructure by pulling inventory from public cloud providers such as Microsoft Azure, amazon web services, etc.
8. Integrated Notification: This notifies you when a job succeeds or fails across the entire organization at once, or customize on a pre-job basis.
9. Schedule Ansible Jobs: It schedule different kinds of jobs such as playbook runs, cloud inventory updates, and source control updates to run according to the need.
10. REST API and Tower CLI Tool: Every feature present in Ansible Tower is available through the Ansible Tower's REST API, which provides the ideal API for the systems management infrastructure. The Ansible Tower's CLI tool is available for launching jobs from CI systems such as Jenkins, or when you need to integrate with other command-line tools.
Roles provide a framework for fully independent or interdependent collections of files, tasks, templates, variables, and modules.
The role is the primary mechanism for breaking a playbook into multiple files. This simplifies writing complex playbooks and makes them easier to reuse. The breaking of the playbook allows you to break the playbook into reusable components.
Each role is limited to a particular functionality or desired output, with all the necessary steps to provide that result either within the same role itself or in other roles listed as dependencies.
Roles are not playbooks. Roles are small functionality that can be used within the playbooks independently. Roles have no specific setting for which hosts the role will apply.
Top-level playbooks are the bridge holding the hosts from your inventory file to roles that should be applied to those hosts.
Creating a Role
The directory structure for roles is essential to creating a new role, such as:
The roles have a structured layout on the file system. You can change the default structured of the roles as well.
For example, let us stick to the default structure of the roles. Each role is a directory tree in itself. So the role name is the directory name within the /roles directory.
- -h: (help) it shows this help message and exit.
- -v: (verbose) Verbose mode (-vvv for more, -vvvv to enable connection debugging).
- --version: it shows program version number and exit.
Roles are stored in separate directories and have a particular directory structure
- The YAML file in the default directory contains a list of default variables that are to be used along with the playbook.
- The handler's directory is used to store handlers.
- The meta-directory is supposed to have information about the author and role dependencies.
- The tasks directory is the main YAML file for the role.
- The tests directory contains a sample YAML playbook file and a sample inventory file and is mostly used for testing purposes before creating the actual role.
- The vars directory contains the YAML file in which all the variables used by the role will be defined. The directory templates and the directory files should contain files and templates that will be used by the tasks in the role.
In playbooks, the variable is very similar to using the variables in a programming language. It helps you to assign a value to a variable and use it anywhere in the playbook. You can put the conditions around the value of the variables and use them in the playbook accordingly.
In the above example, defined a variable name tomcat_port and assigned the value 8080 to the variable and can use it in your playbook wherever required.
The below code is from one of the roles (install-tomcat), such as:
- block: The Ansible syntax to execute a given block.
- name: It is used in logging and helps in debugging which all blocks were successfully executed.
- action: The action is an Ansible keyword used in YAML.
- register: The output of the action tag is registered by using the register keyword.
- always: It is also an Ansible keyword; it says that below will still be executed.
- msg: It displays the message.
Ansible modules are discrete units of code which can be used from the command line or in a playbook task.
The modules also referred to as task plugins or library plugins in the Ansible.
Ansible ships with several modules that are called module library, which can be executed directly or remote hosts through the playbook.
Users can also write their modules. These modules can control like services, system resources, files, or packages, etc. and handle executing system commands.
Let's see how to execute three different modules from the command line.
Each module supports taking arguments. Mainly all modules take key=value arguments, space delimited.
Some module takes no arguments, and the shell/command modules take the string of the command which you want to execute.
From playbook, Ansible modules execute in a very similar way, such as:
Here is another way to pass arguments to a module that is using YAML syntax, and it is also called complex args.
Technically, all modules return JSON format data, though command line or playbooks, you don't need to know much about that. If you're writing your module, it means you do not have to write modules in any particular language which you get to choose.
Modules should be idempotent and avoid making any changes if they detect that the current state matches the desired final state. When using Ansible playbooks, these modules can trigger "change events" in the form of notifying "handlers" to run additional tasks.
Documentation for each module can be accessed from the command line with the Ansible-doc tool:
If you have a large playbook, it becomes useful to be able to run only a specific part of it rather than running everything in the playbook. Ansible supports a tag attribute for this reason.
When you apply tags on things, then you can control whether they are executed by adding command-line options.
When you execute a playbook, you can filter tasks based on the tags in two ways, such as:
- On the command line, with the -tags or -skip-tags options.
- In Ansible configuration settings, with the TAGS_RUN and TAGS_SKIP options.
In Ansible, tags can be applied to many structures, but its simplest use is with individual tasks. Let's see an example that tags two tasks with different tags, such as:
If you want to run the configuration and packages part of a very long playbook, then you can use the -tags option on the command line.
And if you want to run a playbook without certain tagged tasks, then you can use the -skip-tags command-line option.
Ansible Galaxy is a galaxy website where users can share roles and to a command-line tool for installing, creating, and managing roles.
Ansible Galaxy gives greater visibility to one of Ansible's most exciting features, such as application installation or reusable roles for server configuration. Lots of people share roles in the Ansible Galaxy.
Ansible roles consist of many playbooks, which is a way to group multiple tasks into one container to do the automation in a very effective manner with clean, directory structures.
Ansible Galaxy Commands
Here are some helpful Ansible Galaxy commands, such as:
- To display the list of installed roles, with version numbers.
- To remove an installed role.
- To create a role template suitable for submission to Ansible Galaxy.
Ansible Commands Cheat Sheets
Here are some commands which are used in Ansible, such as:
- To install EPEL repo on Centos/RHEL systems.
- To install Ansible package on Centos/RHEL systems.
- To perform an update to the packages on Debian/Ubuntu systems.
- To install the software properties-common-package on Debian/Ubuntu systems.
- To install Ansible personal package archive on Debian/Ubuntu systems.
- To install Ansible on Debian/Ubuntu systems.
- To issue a ping command on all servers defined in the inventory file named hosts.
- To issue a ping command only on hosts2.
- To copy the file "testfile" on all hosts in the inventory file.
- To install ncdu package on all hosts.
- To remove ncdu package on all hosts.
- To build the directory structure for the role named role1.
- To dry-run p4.yml playbook.
- To run a p4.yml playbook with password authentication for all hosts.
To learn Ansible, you have hands-on experience with running commands into a Linux shell. This will help you the Ansible tasks in a better way.
Our Ansible tutorial is designed to help beginners and professionals.
We assure that you will not find any problem in this Ansible tutorial. But if there is any mistake or error, please post the error in the contact form.