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.
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.
Ansible is an open source confi
Here are some of the important benefits of using the ansible. They are:
Become a Ansible Certified professional by learning this HKR Ansible Training !
Here are some of the important points related to the history of ansible are:
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.
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.
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.
Related Article:Terraform vs Ansible
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:
Here we are going to explain the installation step by step.
Installation on Redhat centos systems:
Step1: Install the EPEL repo
[[email protected] ~]# sudo yum install epel-release
Step2: Install the ansible package
[[email protected] ~]# 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:
Using pacman:
Ansible is available in the community repository.
Installing using yum:
On fedora:
On RHEL and centos:
By using apt:
By using pip
[ Related Article : ansible training ]
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]
Top 30 frequently asked Ansible Interview Questions !
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
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"
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"
In order to known the discovered variable about the system we use:
$ ansible all -m setup
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 !
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.
Each playbook is made up of one or more plays. Plays are used to structure playbooks. A playbook may contain more than one play.
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:
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.
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
Usage:
ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ...
Options:
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.
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
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:
The commands used in ansible are:
[[email protected] ~]# sudo yum install epel-release
[[email protected] ~]# sudo yum install -y ansible
$ sudo apt update
$ sudo apt install software-properties-common
$ sudo apt-add-repository ppa:ansible/ansible
$ sudo apt update
$ sudo apt install ansible
[[email protected] test_ansible]# ansible -i hosts all -m ping
[[email protected] test_ansible]# ansible -i hosts all -m ping --limit host2
[[email protected] test_ansible]# ansible -i hosts all -m copy -a "src=/root/test_ansible/testfile dest=/tmp/testfile"
[[email protected] test_ansible]# ansible -i hosts all -m yum -a 'name=ncdu state=present'
[[email protected] test_ansible]# ansible -i hosts all -m yum -a 'name=ncdu state=absent'
[[email protected] test2]# ansible-galaxy init role1
To dry-run p4.yml playbook.
[[email protected] test_ansible]# ansible-playbook -i hosts p4.yml --check
[[email protected] test_ansible]# ansible-playbook -i hosts p4.yml -k
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.
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
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:
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
---
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.
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 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:
Setting up:
Interoperability:
Configuration Language:
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.
Batch starts on 7th Jun 2023, Weekday batch
Batch starts on 11th Jun 2023, Weekend batch
Batch starts on 15th Jun 2023, Weekday batch