Ansible

Ansible Tutorial for Beginners

“Ansible is an open-source IT engine that optimizes the deployment of IT technologies, including intra-service orchestration, cloud provisioning, as well as application deployment. Because Ansible pushes modules toward clients rather than using any client-side agents or customized security architecture, it is simple to implement. The output of such modules was sent back to that same Ansible server once they had been run locally on that client side.

It can quickly establish SSH-Key connections with clients, streamlining the entire procedure. The files, which are sometimes called inventory folders, include the client data. Ansible may utilize an inventory file that you’ve produced but also filled up.

Ansible employs the playbook that utilizes plain language, i.e., YAML, to specify automation jobs. Although YAML is frequently used only for configuration files, it may be utilized in a wide variety of applications whereby data is already saved. The fact that any of the IT infrastructure support staff can understand and read the playbook but also troubleshoot if necessary is a huge advantage.

Ansible was developed with multi-tier deployment in mind. Ansible models IT infrastructure by detailing the way each of the systems is interconnected while it does not manage a single individual system at a time. Because Ansible is completely agentless, it connects your nodes via SSH to function (by default). You have the choice to use Kerberos or perhaps another connection technique with Ansible.

Upon connecting with your nodes, Ansible pushes “Ansible Modules,” which seem to be brief scripts. When the module has completed running on all nodes, Ansible disables the nodes. Simple text files (the host’s files) are used by Ansible to maintain the inventory. Ansible makes use of a host file whereby users may organize hosts and then use playbooks to govern certain groups’ operations.”

Why Use Ansible?

Following are some crucial justifications for utilizing Ansible, including:

  • Ansible has no restrictions mostly on the operating system but rather underlying hardware, in addition to being incredibly lightweight as well as consistent.
  • It is extremely secure because of its microservices characteristics as well as transparent SSH security topographies.
  • Ansible may be installed and used without the requirement for specialized system administrator expertise.
  • Because of its thorough documentation and simple structure, as well as setup, Ansible seems to have an easy learning curve.
  • About plugins, inventories, and modules, including playbooks, Ansible is the ideal partner for orchestrating big environments due to its modularity.

Ansible Installation

On Windows by Ubuntu

Configure the Ansible Control Node, Host, as well as SSH Key Pair

Make very sure a few things are set up before installing Ansible on Ubuntu. Ansible control nodes and/or hosts are needed for the configuration.

Putting the Ansible Control Node in Place

Log in as the root user to configure the Ansible control node. After establishing a second, non-root user with administrative rights, add an SSH key pair for that user.

Create a control node administrator-level user as root. Put the adduser command to use:

# adduser [username]

Set a secure account password but also, if necessary, respond to a series of questions.


To skip any fields you do not need to fill out right now, press Enter.

A valid account has been created. Give the account administrative access right away. The command that follows grants superuser rights, enabling the account to utilize the sudo command:


The new person is now able to carry out administrative functions thanks to the sudo command. When you wish to utilize the Ansible control node, sign in to the new user account.

Establishing an SSH Key Pair

Type the upcoming command into the terminal of the Ansible control node:

$ ssh-keygen

Pressing Enter results in the output seen below:

Only when you have an existing SSH key pair configured the system outputs the information shown below. Decide if the present SSH key pair needs to be replaced.

Finally, the passphrase is requested from you. To prevent future security concerns, we strongly advise adding a secure passphrase:

We acquire this outcome. The output, in this case, shows that the command was effectively executed.

Setting up an Ansible Host

Remote servers that have been watched and managed mostly by Ansible control nodes are known as Ansible hosts. The authorized keys directory for the system user must contain the SSH key for the control node upon every host.

Step 1

To make use of the ssh-copy-id instruction to copy an ssh public key is the simplest way to put it. This output demonstrates that the command was successfully executed.

Enter yes, then press Enter to proceed. The utility now looks for the public half of such key pair that was created in the prior phase. Enter your remote host account password after it has been located. Remote host password; type it in. Entering the password confirms it. The tool adds the remote host’s account with the public key.

Step 2: Install Ansible

Verify that the package index on your system is current. Use the command to update the package index:

Next, use the following command to install Ansible on Ubuntu. This result shows that the command was performed effectively.

This installation then asks you to hit enter to agree, after which the next steps will be carried out automatically. That Ansible control node may handle the remote hosts after it has been deployed.

Step 3: Establishing the Inventory File

To allow Ansible to connect with distant hosts, established an inventory file on those servers. In the terminal of the control node, enter the following command to view the inventory file:

The Ansible inventory file’s usual location is /etc/ansible/hosts; however, you can specify a different location by employing the -i parameter:

You can now start introducing remote hosts, which your control node can administer while the inventory file is open. Beginning with broad guidelines and illustrations for creating a list of remote hosts, the default Ansible inventory file reads as follows:

To add more hosts as well as group them into the categories, scroll to that same file’s bottom. Use this format while adding hosts as well as categories:

Using the server’s IP address, we created a remote host therefore and then categorized it under “servers”:

After you have finished adding items into Ansible’s inventory, use Ctrl+X to save your inventory file but then just press Y to open it.

You may always double-check the inventory file once you’ve put it up by using it. The output in this indicates that the command was effectively achieved.

You have to make sure that the Ansible control node can connect and execute instructions on the remote systems.

Installation on Linux Mint 20

Non-root individuals can use sudo without a password, as shown:

Installing Ansible from the official package repository is simple. Open the terminal on the Ansible controller, then log in. For the installation, you have to update your system.

You will run the following command for the installation. Here, the results revealed that the command was performed effectively.

By examining the installed version, you can confirm the Ansible installation.

Making an SSH Key

SSH keys are used by the Ansible controller node to connect to host nodes as well as execute instructions. SSH key generation, as well as public key copying to the hosts’ permitted keys file.

Ansible Host Node Configuration Instructions

To ssh with the controller, the host nodes must hold the public key. Transfer the key towards the host nodes from the controller node.

Make sure ssh is active on the host nodes as well. SSH should be let via the firewall if there is one active. The following commands should be used to install then start ssh on your host nodes:

Now enter the instructions below into the Linux Mint shell.

To acquire the state of ssh, you have to run this command. This output verifies that the command was done successfully.

For the update of rules, execute this command:

To enable the Firewall to run the succeeding command:

By running the above-mentioned commands, you can check if the controller can connect to the host nodes.

Ansible History

The following are some key details from Ansible’s past, including:

Ansible was created by Michael DeHaan, and also the Ansible project started in February 2012. This same Fedora Unified network is administered by the same person that created Cobbler as well as Func. After these happenings, Red Hat purchased it back in 2015. A component of either the Linux operating system Fedora was Ansible. Through Extra Packages in Enterprise Linux (EPEL) but also Ubuntu, Ansible is accessible for additional operating systems, including RedHat Enterprise Linux, Debian, CentOS, Oracle Linux, as well as Scientific Linux.

Ansible Workflow

Ansible operates via connecting with your nodes and then sending them little programs known as Ansible modules. When these modules had completed running, Ansible deleted them. There are not any daemons, servers, as well as databases necessary; an entire library containing modules may be installed on almost any computer.

The playbook’s full execution is managed by the control of such a management node. A list of hosts in which the Ansible modules must be launched is provided in the inventory file.

When these modules have been so carefully installed, Ansible removes them. When it connects to the host system, it performs the instructions, and when the installation is successful, it removes the copied code from the host machine.

Terms Used in Ansible

There have been a few keywords that are utilized in Ansible, including:

Ansible Server: Most operations, as well as playbooks, will indeed be run from this computer, which has Ansible installed.

Modules: A command and otherwise group of related instructions that are performed here on the client side is referred to as a module.

Task: The task seems to be a portion with only one process left to finish.

Role: It is just a method of grouping jobs as well as associated files so they may be invoked later in a playbook.

Fact: The information was retrieved by using the gather facts procedure first from global variables, mostly on the client system.

Inventory: A file that contains information about the Ansible client server.

Play: This is executing out just the playbook.

Handler: Whenever we want to call a task, a notifier or handler must be specified already.

Notifier: The portion of a task that, if somehow the output is altered, invokes a handler

Tag: It is indeed a name assigned to such a task that may be used in the future to issue only that particular task or combination of tasks.

Ansible Architecture

To perform the Ansible orchestration as well as communicate with both the services of an internal or external cloud with a configuration management database, the Ansible orchestration engine communicates with only a user who is creating the Ansible playbook. You might display information like:

Inventory:

Lists of nodes or hosts with associated IP addresses, databases, servers, etc., that have to be handled are referred to as inventory.

API’s:

Both public and private cloud services are transported via the Ansible APIs.

Modules:

Ansible distributed the Ansible module programs and linked the nodes. Ansible executes the modules, and once they are finished, it deletes them. Such modules can reside on any system; no database nor servers are required. To take note of the content changes, you can use the word processor you choose, a terminal, or perhaps a version control system.

Plugins:

A code piece called a plugin extends Ansible’s fundamental features. Additionally, there are many useful custom plugins that you could make.

Playbooks:

Your written code is included in playbooks, which are expressed in YAML format, as well as specifies the tasks to be carried out by Ansible. Additionally, playbooks allow you to run tasks both synchronously but also asynchronously.

Hosts:

The node systems, which Ansible automates, and therefore any computer like RedHat, Linux, Windows, etc., are hosted in the Ansible architecture.

Networking:

Ansible employs a straightforward, safe, yet potent agentless automation platform for IT development and its operations to automate various networks. It makes use of a particular data model that is independent of either the Ansible automation engine and can be readily extended to work with other hardware.

Cloud:

A cloud seems to be a system of distant servers where data may be managed, processed, as well as stored. Several servers were typically hosted online in addition to being local servers that housed the data. You only need to launch the resources as well as instances in the cloud and link these to such servers, so you’ll be able to manage your work from a distance.

CMDB:

A sort of repository called a CMDB serves as an IT installation’s data warehouse.

Ansible ad-hoc Commands

Inside Ansible, one of the easiest things you can find to perform is its ad-hoc commands. When you wish to give commands to either a server or a group of servers, you utilize these. Although the ad-hoc instructions are not saved for later use, they offer a quick approach to communicating with the required servers.

Although the Ad-hoc instructions are quick and simple, they cannot be reused. The Ad-hoc commands serve as a showcase for Ansible’s ease of use and strength.

Syntax:

$ ansible <hosts> [-m <module_name>] -a <"arguments"> -u <username> [--become] 

Explanation

Hosts: It may represent a record inside the inventory file. Utilize all or “*” to indicate every host inside the inventory.

module_name: It is a choice-based parameter. Ansible provides a broad range of modules, including shell, yum, apt, file, as well as copy. It is also a command by nature.

Arguments: Values that the module requires should be supplied. Based mostly on the module being included, it could change.

Username: The user account that Ansible might use to carry out commands is specified.

Become: If we wish to do activities that would need us to privilege, we may use this optional argument.

Parallelism and Shell Commands

Your company’s server may be rebooted simultaneously in 12 parallel forks. You must configure your SSHagent for connection to do this.

$ ssh-agent bash

$ ssh-add ~/.ssh/id_rsa

12 parallel branches of the reboot will be executed for each of your company’s servers within the “abc” group.:

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

The ad hoc instructions listed above will be executed using Ansible by default from the active user account. Enter the username in the following ad-hoc command if you want to alter it.:

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

File Transfer

For SCP (secure copy protocol), which transfers several files simultaneously across many servers or workstations, you can utilize ad-hoc instructions.

Sending files across several computers or servers

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

Establishing a new directory

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

Trying to delete every file as well as directory

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

Managing Packages

For apt as well as yum modules, ad-hoc commands were also available. The following ad-hoc yum commands are listed below.

The command does not update the yum package; it only checks to see whether it is installed.

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

The command verifies that the package is still not installed.

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

The command verifies that the most recent version of the package was installed.

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

Managing Users and Groups

Ad-hoc commands let us manage, add, but also delete user accounts on any managed nodes.

Managing Services

Verify that the service remains active across every remote server.

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

Importantly, most webservers can support continued services:

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

Double-check that perhaps the connection has been entirely disconnected:

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

Gathering Facts

The fact seems to be the system’s variables that have been identified. The facts can then be used to perform conditional task execution, and they can also be utilized to gather ad hoc system information.

$ ansible all -m setup 

Ansible Playbooks

The Ansible code is created in files called playbooks. The format used to write playbooks is YAML. Since YAML stands for “Still another Markup Language,” little syntax is required. One of Ansible’s key components, playbooks, instruct the software on what to do and are employed in challenging situations. They provide more versatility.

The steps that a user wishes to carry out on a specific system are contained in playbooks. Playbooks are also executed in order. The foundation of every Ansible use case is a playbook.

Playbooks for Ansible are, more often than not, configuration languages rather than programming languages.

You can assign particular responsibilities using a playbook to some hosts as well as different roles to other hosts. As more than just a result, you may manage several servers just by using one playbook in several such scenarios.

Playbook Structure

Every playbook contains one or even more plays. Plays are used to arrange playbooks. Inside the playbook, there may be multiple plays.

The play’s purpose seems to be to map a defined set of instructions against a certain host.

Although there are other YAML editors, notepad++ or another straightforward editor is preferred. Then, set the language as YAML (Language YAML) and paste the following YAML into notepad++.

A YAML always begins by — (3 hyphens)

Create a Playbook

As a first step, let’s create a sample YAML file. We should establish a task initially. These serve as the interface for the roles as well as playbook modules for Ansible.

YAML Tags

The following list of YAML tags includes items like:

Name: It details the Ansible Playbooks’ names.

Hosts: The lists of hosts beyond which you wish to perform the job are specified. A host’s Tag is also required. It instructs Ansible to execute the provided tasks upon the appropriate hosts. Either the local machine or, indeed, the distant machine could do all those tasks. Multiple computers can be used to perform tasks, as well as a set of hosts can be listed within one host tag.

Vars: The variables that you should utilize in your playbook are defined by the Vars tag.

Tasks: Tasks are listings of such actions that must be carried out according to the playbooks. The actions that must be taken should indeed be listed in every playbook. The task name is included in a task field. Although not required, it is helpful for the playbook’s debugging. Each job has an internal connection to such a module of code. You should launch a module together with any parameters that perhaps the module you wish to run needs.

Ansible Tower

A more enterprise-level version of Ansible offers Ansible Tower. This is a web-based management tool with an intuitive user interface that gives you a dashboard that includes all of the host state summaries. It permits speedy deployments while keeping an eye on all configurations.

The tower logs every operation, manages inventories graphically, as well as syncs these with just a broad range of cloud providers. It also enables us to exchange SSH passwords without disclosing them.

The solution to this issue was previously found in Ansible Tower, also known as the AWX project. Particularly those that, like real-time node monitoring, produce superior results as graphics rather than text-based output.

Ansible Tower Features

Ansible Tower Dashboard

It shows all of the current information in the Ansible environment, including hosts, inventory status, as well as recent job activity.

Multi-Playbook Workflows

It allows you to link any number of playbooks, use multiple inventories in any fashion, run different users, and use different credentials.

Real-Time Job Updates

The entire infrastructure may be automated with Ansible. Additionally, you may view real-time work updates, including tasks and plays that are split down according to each machine’s outcome. As a result, you can view the automation’s status as well as know what’s coming up somewhere in the queue.

Scale Capacity With Cluster

The ability to scale Ansible automation throughout the organization is made possible via Ansible Tower clusters, which may be created by joining numerous Ansible Tower nodes together.

Self-Service

Through this functionality, playbooks may be launched with only one click.

Remote Command Execution

This command enables you to perform basic operations on any server or collection of hosts inside the inventory, including adding users, resetting passwords, as well as restarting any malfunctioning services.

Manage and Track Inventory

Retrieving inventory via public providers of cloud services like Microsoft Azure and Amazon Web Services, as well as others, maintains your complete infrastructure.

Integrated Notification

This may be customized before a task to notify you whenever a work succeeds or fails throughout the whole enterprise.

Schedule Ansible Jobs

It schedules many tasks, including source control updates, playbook runs, as well as cloud inventory updates, to execute as needed.

REST API and Tower CLI Tool

The REST API within Ansible Tower, which offers the best API for such systems management architecture, makes every capability available. If you require to incorporate certain other command-line tools or launch tasks from CI systems like Jenkins, you may use the Ansible Tower’s CLI tool.

Ansible Roles

A foundation for completely independent or interconnected sets of documents, tasks, templates, variables, as well as modules is provided by roles.

The role is perhaps the main tool for splitting a playbook into different files. This makes it simpler to write intricate playbooks but also facilitates their reuse. By breaking down the playbook, you may separate it into reusable parts. Each role is restricted to a certain feature or intended outcome, and all the processes required to provide that result are either included together in the same role themselves or are stated as dependents in other roles.

Roles do not resemble playbooks. Roles are auxiliary features that may be utilized on their own within playbooks. The hosts to whom a role will apply are not specified in the job itself.

Creating a Role

Making a new role requires knowledge of either the directory structure for roles, such as:

Role Structure

Mostly on the file system, the roles are organized systematically. The roles’ default structure can also be altered.

Let’s keep with the roles’ default structure as an example. Each role functions as its directory tree. The role name inside the /roles directory is, therefore, indeed the title of the directory.

$ ansible-galaxy -h   

Ansible Variables

The use of variables within playbooks is nearly identical to utilizing them in a programming language. You may utilize a variable anywhere else in the playbook by giving it just a value. You can utilize the variables inside the playbook by the conditions you set around their value.

Creating Valid Variable Names

Knowing what acceptable variable names are is essential before utilizing variables. Letters, digits, as well as underscores should all be used in variable names. Preferably start every variable with either a letter. Foo-port, foo port, foo.port, as well as 10foo are all incorrect variable names, although foo port and foo2 are both proper and legal variable names.

Dictionaries that convert keys into values are supported by YAML. For illustration:

foo:

field1: one

field2: two

Furthermore, you can use bracket notation and otherwise dot notation to describe a particular dictionary field:

foo['field1']

foo.field1 

They both refer to the same value, “one.” If you do decide to utilize dot notation, keep in mind that some keys may create issues since they conflict with the properties but also operations of Python dictionaries. If you utilize keys that begin as well as finish with two underscores or with any of the well-known public attributes, you should write them using bracket notation rather than dot notation:

Ansible Tags

It is advantageous to be able to execute only a portion of a huge playbook instead of the entire thing when you have one. For such a reason, Ansible offers a tag attribute.

By using command-line arguments, you can decide whether tags applied to items are performed.

You have two methods for filtering tasks during playbook execution based upon tags: Also on the command line, using the -tags and otherwise -skip-tags parameters.

The TAGS RUN, as well as TAGS and SKIP parameters, are included in the Ansible setup settings.

The simplest application of tags in Ansible seems to be with individual jobs; however, they may be applied to numerous different structures.

Tag Reuse

The same tag can be used for several tasks. The “—tags” command line argument will execute all jobs that have the specified tag name. We can utilize the tag “ntp” for several activities.

Special Tags

The special tag “always” ensures that a job is always executed unless it is expressly skipped (—skip-tags always).

Here are three other unique tags’ keywords:

tagged” which always executes tagged,

untagged” that only operates untagged,

all” that also executes each task separately.

Ansible operates by default like somehow “—tags” each had been supplied.

Ansible Galaxy

Users can exchange roles on the Ansible Galaxy website, which also links to a command-line utility for installing, generating, as well as maintaining roles.

Among Ansible’s most intriguing aspects, like application installation but rather reusable roles with server setup, is made more visible via Ansible Galaxy. Several people perform a variety of roles inside the Ansible Galaxy.

Ansible roles are made up of several playbooks, which are a means to consolidate several activities within one container for clean, organized automation.

Ansible Galaxy Commands

The following list of useful Ansible Galaxy commands includes:

ansible-galaxy list 

To somehow get rid of such an installed role.

ansible-galaxy remove [role] 

Create Roles With Ansible Galaxy

There are several jobs in Ansible Galaxy which are constantly expanding but also changing.

Git may be used to provide more role sources, like GitHub, to the Galaxy. In fact, this ansible-galaxy install title of <role> command may be used to deploy a role directly either through the Ansible galaxy role store or by utilizing the ansible-galaxy init command to create a new galaxy role.

To create an Ansible role utilizing Ansible Galaxy, one must utilize the ansible-galaxy tool and any related templates. Roles must first be downloaded before being used in the playbooks. They are placed in the standard location, which is /etc/ansible/roles.

Create Collections

You will undoubtedly notice modifications and otherwise additions within Ansible Galaxy, a platform for establishing and managing roles across each Ansible iteration. You receive the functionality of the special collection with Ansible version 2.8.

The publishing format of Ansible material is collections. They may be utilized to package as well as distribute plugins, playbooks, and modules, including roles.

The following commands are implemented mostly by the ansible-galaxy-collection command. Some instructions are the same as those used with ansible-galaxy.

init: Relying upon this default template provided with Ansible or a customized template, it produces a simple collection Skeleton.

Build: The collection artifact is produced that might be posted to your particular repository or, indeed, the galaxy.

Publish: It likewise offers an artifact of built-in connectivity to the galaxy.

Install: One maybe more connections are installed.

Ansible Modules

A playbook job or perhaps the command line may employ Ansible modules, which are independent bits of code. These modules are, however, referred to as task plugins throughout Ansible; however, they are library plugins. Ansible includes several modules under the name module library that may be run on local hosts or distant hosts using playbooks.

Users can create their modules as well. These modules manage to carry out system instructions and also can control things, including services, operating systems, files, or packages.

Let’s run three distinct modules through the command line.

Receiving arguments is supported by every module. Almost all modules accept space-delimited key=value parameters. Most shell/command modules take a text of such a command you wish to run, whereas some modules don’t require any parameters. Ansible modules operate very similarly to playbook actions, for example:

Although you are not required to be very familiar with command lines or playbooks, practically all modules provide data in JSON format. Since you’re developing your module, that implies you have a choice of languages and are not required to use them.

If modules see that the present state resembles the planned final state, they should just be idempotent as well as refrain from making further modifications. These modules can cause “change events” in the form of alerting “handlers” to do extra activities while using Ansible playbooks.

The Ansible-doc program may be used out from the command line to get documentation to every module:

$ ansible-doc yum 

Ansible Templates

Web servers, as well as environments, may be configured with Ansible. For every cluster and a remote server, these configuration files might, however, be different. But other than a few settings, everything else will remain the same.

It is inefficient to create static files for each one of these setups. It will take quite a long time, and you will be required to add more files each time a brand-new cluster is created. If there was any useful method for managing such dynamic values, that would be helpful. Ansible template modules are useful in this situation. All of your configuration settings are contained in a template file; however, the dynamic values were provided in Ansible-like variables. These variables will indeed be changed with the appropriate values depending on the circumstances, like the cluster you are just using, throughout the playbook execution.

With the aid of the Jinj2 templating engine, you may perform tasks beyond simply changing the variables. You may use filters to change the data, loops, conditional statements, macros, arithmetic computations, etc. The Jinja2 templating system is often indicated by the template files.j2 suffix.

The variables in such a template file will be indicated by the double curly brackets, “{{variables}}”

When utilizing the Ansible Template module, we require two arguments, such as:

src: where the template file came from. It can follow an absolute or relative course.

dest: The destination route upon that remote server is called Dest.

Template Module Attributes

The following additional options can be utilized to modify the template module’s default operations:

Force: The Force option will determine if it is necessary to replace the target file if one already exists. Yes seems to be the default value.

Mode: The destination file’s permissions can be specifically configured using this argument.

Backup: Set a backup parameter’s value as yes if you would like a backup file to somehow be produced in the target directory. No seems to be the value by default. And that each time the target directory changes, a backup file will indeed be generated.

Ansible YAML

With the aid of SaltStack as well as Ansible in recent years, the adoption of YAML to describe configuration has grown.

Compared to other common data formats like XML or JSON, YAML is easier for people to understand and create. The majority of programming languages provide libraries that allow for interaction with YAML. Every YAML file of Ansible starts with a list. Thus, every item inside the list seems to be a key-value dictionary and otherwise a hash that is a list containing key-value pairs. Therefore, we need to be able to use YAML to build lists but also dictionaries.

YAML has one more minor oddness. No matter whether they are connected to Ansible or not, all YAML files may optionally start and conclude with —-. This denotes the beginning and end of a document and serves as a component of the YAML format.

A list’s members all seem to be lines that start with a “-” (a dash and space) and therefore are indented to the same degree. We may display YAML data in a variety of ways, including:

Key-value Pair

The data is represented as a Key-Value pair using YAML. The key:value pair also contains a description of the dictionary.

Ansible Inventory

Ansible uses an inventory, which is a list and otherwise collection of lists, to operate simultaneously against numerous maintained hosts within your system. After an inventory has been established, you may use patterns to pick the hosts but rather groups that Ansible should execute against.

Inventory is stored by default inside a file named /etc/ansible/hosts. Using the -i path> option, you may also provide an alternative inventory file somewhere at the command line. An inventory file can indeed be accessed from dynamic sources, clouds, and perhaps other places (YAML, init). Ansible offers plugins for its inventory to add flexibility as well as customization.

Hosts and Group

The hosts are in an INI-like format in the /etc/ansible/ directory.

You may include the port number well after the hostname first with a colon when you have hosts that utilize an alternate SSH port. Ports that can be utilized with an OpenSSH connection instead of a Paramiko connection are included in the SSH configuration file.

If something isn’t operating on the default ports, it’s advised that you configure them to make things clear:

badwolf.example.com:5309 

If you’ve got static IPs, you might wish to create some aliases that reside inside your host file or just use tunnels to connect. Additionally, you may use the example further to explain the hosts:

Jumper ansible_port=5555 ansible_host=192.0.2.50 

An attempt to use Ansible even against the host alias “jumper” in the example above will connect to 192.0.2.50 at port 5555. The inventory file’s characteristics are being used to define the unique variables.

Hosts Variables:

Any hosts which will be utilized in playbooks can be given variables, such as:

[atlanta]

host1 http_port=80 maxRequestsPerChild=808

host2 http_port=303 maxRequestsPerChild=909 

Group Variables:

A whole group can indeed be affected by the variables at once, for example:

[atlanta]

host1

host2

 

[atlanta:vars]

ntp_server=ntp.atlanta.example.com

proxy=proxy.atlanta.example.com 

Ansible Debug

Ansible offers another debug module feature that simplifies the chores. With the addition of a verbosity option in Ansible version 2.1, the debug module was upgraded.

Host information is helpful while troubleshooting Ansible playbooks. The Ansible debug module may be used to output a statement from the Ansible playbook in addition to the value of a variable. Utilizing the debug module found inside Ansible is also simple and one of the easiest tasks.

Using the Debugger Keyword

Any block with a name attribute, like a role, block, task, and play, can utilize the debugger keyword. The debugger keyword will accept a variety of values, including:

Always: regardless of the result, always launches the debugger.

Never: Regardless of the result, never use the debugger.

On_failed: The debugger is only called when a task fails.

On_unreachable: The debugger is only called if the host cannot be reached.

On_skipped: The debugger is only called if the job is skipped.

Whatever global configuration to activate and disable the debugger is overridden by these parameters.

Conclusion

We provide a beginner-friendly introduction to Ansible in this article so that anybody can understand what it is, how and when to use it, along with some historical context. Some individuals find that installing Ansible is a difficult task, but we’ve got you covered with our thorough explanation and images, which will undoubtedly assist you in installing Ansible whether you’re operating Windows and otherwise Linux Mint. Almost all of the terminology, architecture, and workflow found in Ansible were also covered.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content