0% found this document useful (0 votes)
647 views32 pages

Red Hat Enterprise Linux Automation With Ansible

This document discusses installing and configuring Ansible on CentOS 8 or RHEL 8. It provides steps to install Python, Ansible, and configure passwordless SSH access between the control node and managed hosts. It also covers configuring sudo access for the Ansible and DevOps users. Ansible is an open source automation tool that can be used to deploy applications, configure systems, automate workflows, and manage networks through human-readable YAML playbooks. It is agentless and connects to managed hosts using SSH to run modules and ensure infrastructure is in the desired state.

Uploaded by

Piya Choudhury
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
647 views32 pages

Red Hat Enterprise Linux Automation With Ansible

This document discusses installing and configuring Ansible on CentOS 8 or RHEL 8. It provides steps to install Python, Ansible, and configure passwordless SSH access between the control node and managed hosts. It also covers configuring sudo access for the Ansible and DevOps users. Ansible is an open source automation tool that can be used to deploy applications, configure systems, automate workflows, and manage networks through human-readable YAML playbooks. It is agentless and connects to managed hosts using SSH to run modules and ensure infrastructure is in the desired state.

Uploaded by

Piya Choudhury
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Red Hat Enterprise Linux Automation with Ansible (RH294)

Install and Configure Ansible on CentOS 8 / RHEL 8 using the steps below.

Step 1: Install Python on RHEL 8 / CentOS 8


Install and Set your default Python on RHEL 8

Step 2: Install Ansible on RHEL 8 / CentOS 8


Add EPEL repository to your CentOS 8 / RHEL 8 system.
dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm
Step 3: Enable EPEL playground repository and install Ansible on CentOS 8 /
RHEL 8 from it.
dnf install --enablerepo epel-playground ansible

Setup password-less SSH authentication between control node and managed


hosts
 Generate a key pair (Private key and Public key)
ssh-keygen
.ssh/id_rsa ⇒ Private Key
.ssh/id_rsa.pub ⇒ Public Key
 Copy the public key file from the control node to all managed hosts
ssh-copy-id username@Node_IP
 Test the connectivity
ssh -i privatekey user@node_IP [ should login without any password
]

Configure sudo access for ansible and devops user


cd /etc/sudoers.d
vim devops
devops ALL=(ALL) NOPASSWD: ALL

Official Documentation ⇒ https://docs.ansible.com

Overview
Automation is one of the most critical areas of improvement in most organizations.
Today, most companies are in the process of re-inventing themselves in one way or
another to add software development capabilities and as such, take full advantage of
the digitization of everything. Software development release cycles are changing in
order to release faster. Continuous delivery, where every change is potentially it’s
own release is becoming the new standard. Infrastructure is following suit, after all,
continuous delivery is not about just software changes but all changes and
infrastructure plays a key role. For any of this to work of course, 100% automation is
required. To achieve that goal, an automation language that is easy and applicable
to development and operations is needed. Ansible is that language and if you are not
on-board yet, now is your chance not to miss the train because it is leaving the
station. Ansible is easy, Ansible is powerful and Ansible is flexible.
Infrastructure as Code (IAC)
1. A good automation system allows you to implement Infrastructure as Code
practices.
2. IAC means that you can use a machine-readable automation language to
define and describe the state you want your IT infrastructure to be in.
3. If the automation language is represented as simple text files, it can easily be
managed in a version control system like software code.
4. The advantage of this is that every change can be checked into the version
control system.
5. If you want to revert to an earlier known-good configuration, you simply can
check out that version of the code and apply it to your infrastructure.
6. This builds a foundation to help you follow best practices in DevOps.
7. Developers can define their desired configuration in the automation language.
Operators can review those changes more easily to provide feedback, and
use that automation to reproducibly ensure that systems are in the state
expected by the developers.

What is Ansible?
1. Ansible is an open source automation platform.
2. It is a simple automation language
3. It is also an automation engine that runs Ansible Playbooks.
4. It is a deployer tool
5. It is an orchestration tool
6. It is a configuration management tool
7. Architecture is agentless
8. It uses push based mechanism
9. Ansible is idempotent

Ansible Is Simple
1. Ansible Playbooks provide human-readable automation.
2. No special coding skills are required to write Playbooks

Ansible Is Powerful
1. You can use Ansible to deploy applications, for configuration management, for
workflow
automation, and for network automation.
2. Ansible can be used to orchestrate the entire application life cycle.

Ansible Is Agentless
1. Ansible is built around an agentless architecture. Typically, Ansible connects
to the target hosts it manages using OpenSSH or WinRM and runs tasks, by
pushing out small programs called Ansible modules to those hosts.
2. Any modules that are pushed are removed when Ansible is finished with its
tasks.
3. We can start using Ansible almost immediately because no special agents
need to be
deployed to the managed hosts.

Ansible has a number of important strengths:


 Cross platform support: Ansible provides agentless support for Linux,
Windows, UNIX, and network devices, in physical, virtual, cloud, and
container environments.
 Human-readable automation: Ansible Playbooks, written as YAML text files,
are easy to read and help ensure that everyone understands what they will
do.
 Perfect description of applications: Every change can be made by Ansible
Playbooks, and every aspect of your application environment can be
described and documented.
 Easy to manage in version control: Ansible Playbooks and projects are plain
text. They can be treated like source code and placed in your existing version
control system.
 Support for dynamic inventories: The list of machines that Ansible manages
can be dynamically updated from external sources in order to capture the
correct, current list of all managed servers all the time, regardless of
infrastructure or location.
 Orchestration : that integrates easily with other systems: HP SA, Puppet,
Jenkins, Red Hat Satellite, and other systems that exist in your environment
can be leveraged and integrated into your Ansible workflow.

Ansible Concepts & Architecture


 There are two types of machines in the Ansible architecture: control nodes
and managed hosts.
 Ansible is installed and run from a control node, and this machine also has
copies of your Ansible project files.
 Managed hosts are listed in an inventory, which also organizes those systems
into groups for easier collective management.
 The inventory can be defined in a static text file, or dynamically determined by
scripts that get information from external sources.
 Playbook : is a collection of plays(tasks). One playbook may consist of a
single play or multiple plays. Playbooks are written using YAML (Yet Another
Markup Language)
 A play performs a series of tasks on the hosts, in the order specified by the
play. A play may have a single task or multiple tasks.
 Each task runs a module, a small piece of code (written in Python,
PowerShell, or some other language), with specific arguments.
 Ansible ships with hundreds of useful modules that can perform a wide variety
of automation tasks.
 Tasks, plays, and playbooks are designed to be idempotent. This means that
you can safely run a playbook on the same hosts multiple times.
 When your systems are in the correct state, the playbook makes no changes
when you run it.
 Ansible also uses plug-ins. Plug-ins are code that you can add to Ansible to
extend it and adapt it to new uses and platforms.
 Red Hat Ansible Tower is an enterprise framework to help you control,
secure, and manage your Ansible automation at scale. It provides a web-
based user interface (web UI) and a RESTful API. It is not a core part of
Ansible, but a separate product that helps you use Ansible more effectively
with a team or at a large scale.
SUMMARY
In this chapter, you learned:
 Automation is a key tool to mitigate human error and quickly ensure
that your IT infrastructure is in a consistent, correct state.
 Ansible is an open source automation platform that can adapt to many
different workflows and environments.
 Ansible can be used to manage many different types of systems,
including servers running Linux, Microsoft Windows, or UNIX, and
network devices.
 Ansible Playbooks are human-readable text files that describe the
desired state of an IT infrastructure.
 Ansible is built around an agentless architecture in which Ansible is
installed on a control node and clients do not need any special agent
software.
 Ansible connects to managed hosts using standard network protocols
such as SSH, and runs code or commands on the managed hosts to
ensure that they are in the state specified by Ansible.

Managing Ansible Configuration Files


Ansible chooses its configuration file from one of several locations on the control
node -
1. /etc/ansible/ansible.cfg ⇒ the base configuration file provided by ansible
package
2. ~/.ansible.cfg
3. ./ansible.cfg
4. Using ANSIBLE_CONFIG environment variable

Configuration File Precedence ⇒


ANSIBLE_CONFIG⇒ ansible.cfg in current working directory==>ansible.cfg in
home directory⇒ the default /etc/ansible/ansible.cfg

Managing Settings in the Ansible Configuration File ⇒


The ansible configuration file consists of several sections, with each section
containing settings defined as key-value pairs.

 [defaults] ⇒ sets the defaults for Ansible operation


 [privilege_escalation] ⇒ configures how Ansible performs privilege escalation
on managed hosts
ansible --help
Privilege Escalation Options:
control how and which user you become as on target hosts

--become-method BECOME_METHOD
privilege escalation method to use (default=sudo), use
`ansible-doc -t become -l` to list valid choices.
--become-user BECOME_USER
run operations as this user (default=root)
-K, --ask-become-pass
ask for privilege escalation password
-b, --become run operations with become (does not imply password prompting)

Configuring Connections ⇒
 Ansible needs to know how to communicate with its Managed Hosts
 By default, Ansible connects to managed hosts using SSH protocol.

Non-SSH Connections ⇒
 The protocol used by Ansible to connect to Managed hosts is set by default to
smart, which determines the most efficient way to use SSH.
 If we do not have localhost in the inventory file, Ansible sets up an implicit
localhost entry to allow us to run ad hoc commands and playbooks that target
localhost.
[ansible@control rh294]$ ansible localhost --list-hosts
hosts (1):
localhost
Here, instead of using the smart SSH connection type, Ansible connects to the
localhost
using the special local connection type by default.
 The local connection type ignores the remote_user parameter setting and runs
commands directly on the local system.

Configuring File Comments ⇒


There are 2 comment characters allowed by Ansible configuration files → The
hash(#) and the semicolon(;)

Running AD HOC Command ⇒


Syntax :
ansible host-pattern -m module -a module_arguments
Examples :
1. To ping all hosts ⇒ ansible all -m ping
2. To display the content of /etc/redhat-release file ⇒ ansible all -m command -a
‘cat /etc/redhat-release’
3. To create a user named bob on the host(s) within the host group called web
ansible web -m user -a ‘name=bob state=present’
ansible web -m command -a ‘id bob’
ansible-doc module_name ⇒ will display module arguments
ansible-doc -l ⇒ lists all modules installed on a system
Note : If we do not specify a particular module name in the ansible command,
ansible will by default use the command module as configured in
/etc/ansible/ansible.cfg file

Difference between command and shell module ⇒


1. If you want to run a command through the shell (say you are using `<', `>', `|',
etc), you actually want the [shell] module instead.
2. If you try to execute the built-in bash command set with command and shell
module, it only succeeds with the shell module.
ansible localhost -m command -a set ⇒ fails
ansible localhost -m shell -a set ⇒ succeeds

SUMMARY
In this chapter, you learned:
 Any system upon which Ansible is installed and which has access to the
required configuration files and playbooks to manage remote systems
(managed hosts) is called a control node.
 Managed hosts are defined in the inventory. Host patterns are used to
reference managed hosts defined in an inventory.
 Inventories can be static files or dynamically generated by a program from an
external source, such as a directory service or cloud management system.
 Ansible looks for its configuration file in a number of places in order of
precedence. The first configuration file found is used; all others are ignored.
 The ansible command is used to perform ad hoc commands on managed
hosts.
 Ad hoc commands determine the operation to perform through the use of
modules and their arguments, and can make use of Ansible's privilege
escalation features.

Assignments
==========
Task 1 :
1. Setup Ansible Lab using 1 Control Node and 2 Managed Hosts.
2. Register control node with redhat.com and subscribe to the proper channel
for installing Ansible.
3. Install Ansible on the Control Node.
4. Install Python on Control node and Managed hosts.
5. Setup Password-less ssh authentication from control node to managed hosts.
6. Login to control node as ansible user and create a directory called rh294
7. Create an Ansible configuration file within rh294 directory as per the following
specifications -
a. Set the inventory file as /home/ansible/rh294/inventory
b. Remote user should be set to devops [ sudo should have
already been configured ]
c. Configure privilege escalation for the devops user so that he can
perform administrative tasks.
8. Create a custom static inventory file called /home/ansible/inventory as per
the
following specifications :
a. Information about your 2 managed hosts is listed in the following table.
You will
assign each host to multiple groups for management purposes based
on the
purpose of the host,the city where it is located, and the deployment
environment to
which it belongs to.

In addition, groups for US cities (Raleigh and Mountain View) must be


set up as
children of the group us so that hosts in the United States can be
managed as a
group.
9. Use the ansible all -i inventory --list-hosts command to list all managed
hosts.
10. Use the ansible ungrouped -i inventory --list-hosts command to list all
managed hosts
listed in the inventory file but are not part of a group.
11. Use the ansible development -i inventory --list-hosts command to list all
managed
hosts listed in the development group.
12. Use the ansible testing -i inventory --list-hosts command to list all
managed hosts
listed in the testing group.
13. Use the ansible us -i inventory --list-hosts command to list all managed
hosts listed in
the us group.

Task 2 :
1. Execute an ad hoc command on control node to display the content of
/etc/redhat-release file from node1
2. Execute an ad hoc command on control node to create a group on node1 as
per the following specifications :
a. Group Name ⇒ dba
b. GID ⇒ 10001
3. Execute an ad hoc command on control node to create a user on node1 as
per the following specifications :
. User Name ⇒ bob
a. UID ⇒ 5001
b. Login Shell ⇒ /bin/sh
c. Group(Secondary) ⇒ dba
d. Gecos Field ⇒ Devops Operator
4. Using the copy module, execute an ad hoc command on node1 to change the
contents of the /etc/motd file so that it consists of the string "Managed by
Ansible"
followed by a newline.
Clear the content of /etc/motd file using shell module.
Task 3: Write an ad-hoc command to copy the /etc/hosts file from control node
node1 as per
the following specifications.
a. Destination Directory : /tmp
b. File Owner : devops
c. Group Owner : devops
d. Permission : 0640

Implementing Playbooks
 Ad hoc commands can run a single, simple task against a set of targeted
hosts as a one-time command.
 The real power of Ansible, however, is in learning how to use playbooks to run
multiple,
complex tasks against a set of targeted hosts in an easily repeatable manner.
 A play is an ordered set of tasks run against hosts selected from your
inventory.
 A playbook is a text file containing a list of one or more plays to run in a
specific order.
 A playbook is a text file written in YAML format, and is normally saved with the
extension yml
 The playbook uses indentation with space characters to indicate the structure
of its data.
 YAML does not place strict requirements on how many spaces are used for
the indentation, but there are two basic rules -
a. Data elements at the same level in the hierarchy (such as items
in the same list) must have the same indentation.
b. Items that are children of another item must be indented more
than their parents.
 A playbook begins with a line consisting of three dashes (---) as a start of
document marker.
 It may end with three dots (...) as an end of document marker.
 An item in a YAML list starts with a single dash followed by a space.
 The play itself is a collection of key-value pairs. Keys in the same play should
have the same indentation.
 The following example shows a YAML snippet with three keys. The first two
keys have
simple values. The third has a list of 3 items as a value.
name: just an example
hosts: webservers
tasks:
- first
- second
- third
The original example play has three keys, name, hosts, and tasks, because
these keys all have the same indentation.

 The first line of the example play starts with a dash and a space (indicating
the play is the first item of a list), and then the first key, the name attribute.
 The name key associates an arbitrary string with the play as a label. This
identifies what the play is for.
 The name key is optional, but is recommended because it helps to document
your playbook. This is especially useful when a playbook contains multiple
plays.
 The second key in the play is a hosts attribute, which specifies the hosts
against which the play's tasks are run.
 hosts attribute takes a host pattern as a value, such as the names of
managed hosts or groups in the inventory.
 The last key in the play is the tasks attribute, whose value specifies a list of
tasks to run for this play.
Example : Play with a single task
tasks:
- name: alex exists with UID 5000
user:
name: alex
uid: 4000
state: present

Example : Play with multiple tasks


tasks:
- name: web server is enabled
service:
name: httpd
enabled: true
- name: NTP server is enabled
service:
name: chronyd
enabled: true

Running Playbooks
The ansible-playbook command is used to run playbooks.
ansible-playbook example.yml

 Note that the value of the name key for each play and task is displayed when
the playbook is run.
 The Gathering Facts task is a special task that the setup module usually runs
automatically at the start of a play.

Syntax Verification
The ansible-playbook command offers a --syntax-check option that you can
use to verify the syntax of a playbook.
ansible-playbook --syntax-check example.yml

Executing a Dry Run


You can use the -C option to perform a dry run of the playbook execution.
This causes Ansible to report what changes would have occurred if the
playbook were executed, but does not make any actual changes to managed
hosts.
ansible-playbook -C webserver.yml

Implementing Multiple Plays


 A playbook is a YAML file containing a list of one or more plays.
 This can be very useful when orchestrating a complex deployment
which may involve different tasks on different hosts.
 You can write a playbook that runs one play against one set of hosts,
and when that finishes runs another play against another set of hosts.
 Each play in the playbook is written as a top-level list item in the
playbook.
Example
---
# This is a simple playbook with two plays
- name: first play
hosts: web.example.com
tasks:
- name: first task
yum:
name: httpd
status: present
- name: second play
hosts: database.example.com
tasks:
- name: first task
service:
name: mariadb
enabled: true

Task : Write an Ansible Playbook to perform the following tasks -


1. The playbook name is web.yml.
2. Plays should get executed on web hostgroup.
3. The httpd package should be present on target hosts.
4. The local files/index.html file is copied to /var/www/html on all hosts
inside the web host group.
5. The httpd service is started and enabled using the service module.

PLAYBOOK SYNTAX VARIATIONS

 YAML Comments : Comments can also be used to aid readability. In YAML,


everything to the right of the number or hash symbol (#) is a comment.
eg. # This is a YAML comment

 YAML Strings : Strings in YAML do not normally need to be put in quotation


marks even if there are spaces contained in the string.
eg. this is a string
‘this is another string’
“this is yet another string”
 YAML Dictionaries : collections of key-value pairs written as an indented
block, as follows:
name: svcrole
svcservice: httpd
svcport: 80
Dictionaries can also be written in an inline block format enclosed in curly
braces, as
follows:
{name: svcrole, svcservice: httpd, svcport: 80}

 YAML Lists : lists written with the normal single-dash syntax:


hosts:
- servera
- serverb
- serverc
Lists also have an inline format enclosed in square braces, as follows:
hosts: [servera, serverb, serverc]

Task : Implementing Multiple Plays


Write a Playbook called intranet.yml to perform the following tasks -
 Install the latest versions of httpd,firewalld,mariadb-server and php
packages
 Ensure that a custom index.html file is in place with the following
content -
"Welcome to the example.com intranet!\n"
 Start and enable firewalld service
 Ensure that firewalld service permits http connections from remote
systems.
 Start and enable httpd and mariadb services
 The web page should be accessible from remote systems

# Deploy intranet configuration


---
- name: Enable intranet services
hosts: node1
tasks:
- name: latest version of httpd, mariadb-server, firewalld
& php
installed
yum:
name:
- httpd
- mariadb-server
- firewalld
- php
state: latest
- name: Push the index.html page
copy:
content: "Welcome to example.com intranet!\n"
dest: /var/www/html/index.html

- name: firewalld is started & enabled


service:
name: firewalld
enabled: true
state: started

- name: firewalld permits access to httpd service


firewalld:
service: http
permanent: true
state: enabled

Managing Variables and Facts

Ansible Variables
 Ansible supports variables that can be used to store values.
 Variables provide a convenient way to manage dynamic values for a given
environment in your ansible project.
 Examples of values that variables might include :
a. Users to create
b. Packages to install
c. Services to start
d. Files to remove
e. Partitions to create

Naming Variables
 Variable names must start with a letter, and they can only contain letters,
numbers, and
underscores.
Defining Variables
 Variables can be defined in a variety of places in an Ansible project.
 It can be simplified to three basic scope levels:
• Global scope: Variables set from the command line or Ansible configuration.
• Play scope: Variables set in the play.
• Host scope: Variables set on host groups and individual hosts by the
inventory.

Using Variables in Playbooks


 After variables have been declared, administrators can use the
variables in tasks.
 Variables are referenced by placing the variable name in double curly
braces ({{ }}). Ansible substitutes the variable with its value when the
task is executed.

Host Variables and Group Variables


 Inventory variables that apply directly to hosts fall into two broad
categories:
host variables ⇒ apply to a specific host
group variables⇒ apply to all hosts in a host group
 One way to define host variables and group variables is to do it directly
in the inventory file. This is an older approach and not preferred, but
you may still encounter it.
1. Defining the ansible_user host variable for demo.example.com:

2. Defining the user group variable for the servers host


group.

3. Defining the user group variable for the servers group,


which consists of two host groups each with two servers.

Some disadvantages of this approach are that it makes the inventory file more
difficult to work
with, it mixes information about hosts and variables in the same file, and uses an
obsolete syntax.
Using Directories to Populate Host and Group Variables
 The preferred approach to defining variables for hosts and host groups is to
create two directories, group_vars and host_vars, in the same working
directory as the inventory file or directory.
 These directories contain files defining group variables and host variables,
respectively.

Consider a scenario where there are two data centers to manage and the data
center hosts are defined in the ~/project/inventory inventory file:

 If you need to define a general value for all servers in both data centers, set a
group variable for the datacenters host group:

 If the value to define varies for each data center, set a group variable for each
data center host
group:

 If the value to be defined varies for each host in every data center, then define
the variables in
separate host variable files:
 The directory structure for the example project, project, if it contained all the
example files above, would appear as follows:

Capturing command output ⇒ with registered variables


 register statement is used to capture the output of a command
 The output is saved into a temporary variable that can be used later in
the playbook for debugging purpose

vim register.yml
---
- name: Installs a package and prints the result
hosts: web
tasks:
- name: Install a package
yum:
name: httpd
state: installed
register: install_result

- debug: var=install_result

When we run the playbook, the debug module is used to dump the value of the
install_result registered variable to the terminal.
Task : Write a Playbook to perform the following tasks -
a. Install the packages - httpd, firewalld
b. Declare respective variables for packages / services / rules
c. Start and Enable httpd and firewalld services
d. Permit http via firewalld
e. Create an index.html file inside files directory
f. Ensure the index.html file is in webcontent directory on the target
host(s)
g. Check whether the web server is accessible from the control node
using curl
command.

web_pkg: httpd
firewalld_pkg: firewalld
web_service: httpd
firewall_service: firewalld
rule: http

yum:
name:
- “{{ web_pkg }}”
- “{{ firewall_pkg }}”

service:
name: “{{ web_service }}”
state: started
enabled: true

Managing Secrets
 Ansible may need access to sensitive data such as passwords or API keys in
order to configure managed hosts.
 Normally, this information might be stored as plain text in inventory variables
or other Ansible files.
 In that case, however, any user with access to the Ansible files or a version
control system which stores the Ansible files would have access to this
sensitive data. This poses an obvious security risk.
 Ansible Vault, which is included with Ansible, can be used to encrypt and
decrypt any structured data file used by Ansible .
 To use Ansible Vault, a command-line tool named ansible-vault is used to
create, edit, encrypt,decrypt, and view files.

Creating an encrypted File


Instead of entering the vault password through standard input, you can use a vault
password file to store the vault password.

The cipher used to protect files is AES256 in recent versions of Ansible, but files
encrypted with
older versions may still use 128-bit AES.

Viewing an Encrypted File

Editing an existing Encrypted File

Encrypting an existing File

Decrypting an existing Encrypted File

Changing the Password of an Encrypted File

Playbooks and Ansible Vault


To run a playbook that accesses files encrypted with Ansible Vault, you need to
provide the
encryption password to the ansible-playbook command. If you do not provide the
password,
the playbook returns an error:
Task : Write a Playbook to use an external variable file. The variable file should
be vault encrypted. Also rekey the file to set up a new vault password.

Managing Facts
 Ansible facts are variables that are automatically discovered by Ansible on a
managed host.
 Facts contain host-specific information that can be used just like regular
variables in plays, conditionals,loops, or any other statement that depends on
a value collected from a managed host.
 Some of the facts gathered for a managed host might include:

. The host name


• The kernel version
• The network interfaces
• The IP addresses
• The version of the operating system
• Various environment variables
• The number of CPUs
• The available or free memory
• The available disk space
 Facts are a convenient way to retrieve the state of a managed host and to
determine what action to take based on that state.
 Normally, every play runs the setup module automatically before the first task
in order to gather facts.
 One way to see what facts are gathered for your managed hosts is to run a
short playbook that gathers facts and uses the debug module to print the
value of the ansible_facts variable.

 The playbook displays the content of the ansible_facts variable in JSON


format as a hash/dictionary of variables.
When a fact is used in a playbook, Ansible dynamically substitutes the
variable name for the fact with the corresponding value:
Turning off facts gathering

Creating Custom Facts


 Administrators can create custom facts which are stored locally on
each managed host.
 These facts are integrated into the list of standard facts gathered by the
setup module when it runs on the managed host.
 Custom facts can be defined in a static file, formatted as an INI file or
using JSON.
 Custom facts allow administrators to define certain values for managed
hosts, where plays might be used to populate configuration files or
conditionally run tasks.
 By default, the setup module loads custom facts from files and scripts
in each managed host's /etc/ansible/facts.d directory.
 The name of each file or script must end in .fact in order to be used.
 This is an example of a static custom facts file written in INI format.

 The same facts could be provided in JSON format.

Guided Exercise on Custom Facts :

1. Gather facts from a host.


2. Create tasks that use the gathered facts.
3. Create a fact file named /home/student/data-facts/custom.fact. The fact
file defines the package to install and the service to start on Managed
Hosts. The file should read as follows:

4. Create the setup_facts.yml playbook to make the


/etc/ansible/facts.d remote directory and to save the custom.fact file to
that directory.
5. Run an ad hoc command with the setup module. Search for the
ansible_local section in the output. There should not be any custom
facts at this point.
6. Run the setup_facts.yml playbook.
7. Create the main playbook playbook.yml with the following

DEPLOYING CUSTOM FILES WITH JINJA2 TEMPLATES


 Ansible uses the Jinja2 templating system for template files. Ansible also uses
Jinja2 syntax to reference variables in playbooks.
 Variables and logic expressions are placed between tags, or delimiters. For
example, Jinja2 templates use {% EXPR %} for expressions or logic (for
example, loops), while
{{ EXPR }} are used for outputting the results of an expression or a variable
to the end user.
 Use {# COMMENT #} syntax to enclose comments that should not appear in
the final file.
 In the following example, the first line includes a comment that will not be
included in the final file. The variable references in the second line are
replaced with the values of the system facts being referenced.

Deploying Jinja2 Template


Jinja2 templates are a powerful tool to customize configuration files to be
deployed on the
managed hosts. When the Jinja2 template for a configuration file has been
created, it can
be deployed to the managed hosts using the template module, which supports
the transfer
of a local file on the control node to the managed hosts.

To use the template module, use the following syntax. The value associated with the
src key
specifies the source Jinja2 template, and the value associated with the dest key
specifies the file to be created on the destination hosts.

Using Loops
Jinja2 uses the for statement to provide looping functionality. In the following
example, the user
variable is replaced with all the values included in the users variable, one value per
line.

{% for user in users %}


{{ user }}
{% endfor %}

Task : Generate an /etc/hosts file from the hosts facts dynamically.


1. Create a Jinja2 template file called hosts.j2
2. Create a play which will use the hosts.j2 file using the template module.

Task : Create a template file that your playbook will use to install a customized
Message Of the Day file(/etc/motd) on each Managed Host.

Implementing Task Control : Loops and Conditional Tasks


 Ansible supports iterating a task over a set of items using the loop keyword.
 A simple loop iterates a task over a list of items.
 The loop keyword is added to the task, and takes as a value the list of items
over which the task should be iterated.
 The loop variable item holds the value used during each iteration.

Loops over a List of Hashes or Dictionaries


 The loop list does not need to be a list of simple values. In the following
example, each item in the list is actually a hash or a dictionary.
 Each hash or dictionary in the example has two keys, name and groups, and
the value of each key in the current item loop variable can be retrieved with
the
item.name and item.groups variables, respectively.
Running Tasks Conditionally
 Ansible can use conditionals to execute tasks or plays when certain
conditions are met.
 The when statement is used to run a task conditionally.
 It takes as a value the condition to test. If the condition is met, the task runs. If
the condition is not met, the task is skipped.
 One of the simplest conditions that can be tested is whether a Boolean
variable is true or false.
 The when statement in the following example causes the task to run only if
run_my_task is true:

The following example tests whether the my_service variable has a value. If it does,
the value of my_service is used as the name of the package to install. If the
my_service variable is not defined, then the task is skipped without an error.
Testing Multiple Conditions
when: ansible_distribution == “Redhat” or ansible_distribution == “Fedora”
when: ansible_distribution_version == “7.6” and ansible_kernel == “3.10.0-
327.el7.x86_64”

when:
 ansible_distribution_version == “7.6”
 ansible_kernel == “3.10.0-327.el7.x86_64”
COMBINING LOOPS AND CONDITIONAL TASKS
In the following example, the mariadb-server package is installed by the yum module
if there is
a file system mounted on / with more than 300 MB free.
 The ansible_mounts fact is a list of dictionaries, each one representing facts
about one mounted file system.

The following playbook restarts the httpd service only if the postfix service is running:

Task 1:
 Implement Ansible conditionals using when keyword.
 Implement task iteration using the loop keyword in conjunction with
conditionals
Create a playbook called playbook.yml which contains a play with 2 tasks. The first
task installs the MariaDB required packages and the second task ensures that
MariaDB service is running.
Update the first task in such a way so that the package gets installed only if the
managed host is having the operating system as Redhat Enterprise Linux
Implementing Handlers
 Ansible modules are designed to be idempotent
 Sometimes when a task does make a change to the system, a further task
may need to
 be run.For example, a change to a service's configuration file
(httpd.conf) may then require that the service be reloaded so that the
changed configuration takes effect.
 Handlers are tasks that respond to a notification triggered by other tasks
 Tasks only notify their handlers when the task changes something on a
managed host.
 Each handler has a globally unique name and is triggered at the end of a
block of tasks in a playbook.
 If no task notifies the handler by name then the handler will not run.
 If one or more tasks notify the handler, the handler will run exactly once after
all other tasks in the play have completed.
 Handlers can be considered as inactive tasks that only get triggered when
explicitly invoked using a notify statement.
 Handlers always run in the order specified by the handlers section of the play.
They do not run in the order in which they are listed by notify statements in a
task, or in the order in which tasks notify them.
 Handlers normally run after all other tasks in the play complete. A handler
called by a task in the tasks part of the playbook will not run until all tasks
under tasks have been processed.

Automating Linux Administration Tasks

Subscribing a Linux Server ⇒ redhat_subscription


subscription-manager register –username=<username> –password=<password>
subscription-manager attach –pool=poolID
-name: Register and subscribe the system
redhat_subscription:
username: <username>
password: <password>
pool_ids: poolID
state: present [ indicates to register & subscribe the system ]

Package Management ⇒ yum


Configuring a Yum Repository ⇒ yum_repository
cd /etc/yum.repos.d
vim rhel8.repo
[example-internal]
name=This is an internal repository
baseurl=http://materials.example.com/rhel8/dvd
enabled=1
gpgcheck=0

 name: Configure the internal repo file


yum_repository:
name: example-repo
file: example
description: This is an internal repository
baseurl: http://materials.example.com/rhel8/dvd
enabled: yes
gpgcheck: no

User and Group Administration ⇒ user and group


Task Scheduling ⇒ at and cron
Define a task that uses the cron module to schedule a recurring cron job that will run
in every 2 minutes between 09:00 and 16:59 on Monday through Friday
tasks:
 name: Crontab file exist
cron:
name: Add data and time to a file
minute: “*/2”
hour: 9-16
weekday: 1-5
job: date >> /home/devops/my_date_time_cron_job
Managing Storage
Task Linux Command Ansible Module
Disk Partition ⇒ fdisk // parted parted
Volume Group ⇒ vgcreate lvg
Logical Volume ⇒ lvcreate lvol
Create Filesystem ⇒ mkfs filesystem
Mount the filesystem ⇒ mount mount

mkfs.xfs /dev/vg1/lv1
mount -t xfs /dev/vg1/lv1 /data

Ansible Roles
Automating Linux Administration Tasks using Ansible

Exam Study Points for EX294


========================
Exam Code : EX294
Duration : 4 Hrs.
Total Marks : 300
Pass Marks : 210

1. Install & Configure Ansible on control node. Create ansible.cfg and inventory
file.
2. Ad Hoc command ⇒ Create repository
3. Install package and package group
4. Install role using Ansible Galaxy
5. Create and use a role
6. Manage LVM
7. Modify file content
8. Manage web content
9. Manage Ansible Vault
10. User and Group Management
11. Jinja2 template

You might also like