0% found this document useful (0 votes)
8 views

Unit 4 - DO Notes

The document provides a comprehensive overview of Ansible, an open-source automation tool used for configuration management, application deployment, and orchestration. It covers installation procedures, the architecture of Ansible with control and managed nodes, and the creation of an inventory file for managing nodes. Additionally, it details the steps for setting up Ansible on AWS cloud services, including creating EC2 instances and configuring SSH access.

Uploaded by

gowthamj22it
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)
8 views

Unit 4 - DO Notes

The document provides a comprehensive overview of Ansible, an open-source automation tool used for configuration management, application deployment, and orchestration. It covers installation procedures, the architecture of Ansible with control and managed nodes, and the creation of an inventory file for managing nodes. Additionally, it details the steps for setting up Ansible on AWS cloud services, including creating EC2 instances and configuring SSH access.

Uploaded by

gowthamj22it
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/ 31

PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY, DINDIGUL – 624622.

(An Autonomous Institution Affiliated to Anna University, Chennai)


CCS342 – DEVOPS
UNIT 4 – CONFIGURATION MANAGEMENT USING ANSIBLE

CO4: Perform configuration management using Ansible.


S. No Topics
1 Ansible Introduction
2 Installation
3 Ansible master / slave configuration, YAML basics
4 Ansible modules, Ansible Inventory files
5 Ansible playbooks, Ansible Roles
7 Adhoc commands in ansible

INTRODUCTION TO ANSIBLE:
 Ansible is an open source automation tool and it was written by Michael DeHaan
and acquired by Red Hat in 2015.
 It is used to perform the tasks such as configuration management, application
deployment, intra-service orchestration (meaning automated configuring,
coordinating and managing of computer systems and software) and provisioning.
 Ansible can perform nearly anything a systems administrator does on a weekly or
daily basis.
 Ansible doesn‟t depend on agent software and has no additional security
infrastructure, so it‟s easy to deploy.
 Ansible is agentless, temporarily connecting remotely via SSH (Secure shell network
protocol) or Windows.
Advantages of Ansible:
 Free: Ansible is an open source tool. Hence it can-be freely downloaded and
installed.
 Simple to learn: No special coding skills are required for ansible to use. Instructions
written in Ansible are Human - readable hence to use ansible it requires no
programming
 skills.
 Flexible: Ansible can be used to automate a wide range of IT tasks, from simple
configuration changes to complex application deployments.
 Security: Ansible is a secure tool that can be used to automate the tasks without
compromising the security of our IT infrastructure.
 Scalability: Ansible is used to automate the configuration and management of large
IT infrastructure. It can be used to automate the tasks across thousands of servers
and devices.
 Powerful: Ansible allows us to model high complex IT infrastructure.
Features of Ansible:
1. Configuration management:
 In Ansible we can perform the configuration management using playbook file.
 The ansible can perform the configuration management tasks such as -
 Installing the software on servers in designated IT infrastructure.
 Configuring the services
 Managing users and groups
 Backing up data
 Updating system files
 Copying the desired files at desired computer
2. Application deployment:
 The application deployment feature of ansible involves using ansible to automate
the process of deploying and managing applications on target servers or
infrastructure.
 The ansible playbook can be written to perform following tasks.
 Configuring services
 Deploying files and directories
 Creating users and groups
 Managing databases
 Scaling applications
3. Orchestration:
 Ansible orchestration is a process of automating the tasks such as deployment,
configuration and management of IT systems and applications.
 Ansible orchestration can be used to automate tasks across a wide range of
platforms, including Linux, Windows and macOS.
 It can also be used to automate tasks across a wide range of infrastructure,
including servers, networks and storage.
4. Cloud provisioning:
 Ansible cloud provisioning is the process of automating the creation and
configuration of cloud resources, such as virtual machines, storage and
networks.
 The ansible is used to perform following tasks under cloud provisioning -
 Creating virtual machines
 Attaching storage
 Configuring networking
 Deploying applications.
ANSIBLE MASTER/SLAVE CONFIGURATION:
 In ansible, there are two categories of computers:
 The control node and managed nodes.
Fig: Ansible architecture
Control node:
 The control node is a computer on which the ansible is installed. There must be at
least one control node.
 From the control node the IT infrastructure is managed.
 It serves as a central point for executing the ansible commands and playbook.
 The control node contains an inventory file that contains the list of slave nodes that
a
 master node can control.
Managed node:
 The managed nodes are basically the servers or systems that we want to manage
using
 ansible.
 The Ansible connects to these nodes and runs the tasks on it using the control node.
The only requirement for this interaction is that your ansible control node has login
access to the managed nodes.
 The ssh keys are the most common way to provide access, but other forms of
authentication are also supported.
 It is not necessary to install ansible on managed nodes.
 These nodes only require ssh access and required software can be installed.
Ansible Inventory Files:
 The inventory file is also called as host file.
 It is a text file that contains the list of managed nodes. These nodes can be arranged
in different host groups. This can be useful for organizing your hosts and for running
tasks on specific groups of hosts.
 For example, we can create a group called “webserver” that contains all of our web
servers. We can then run a playbook that only affects the web servers by targeting
the “webserver” group.
 The inventory file is an essential component of ansible architecture.
 In the inventory file the IP address of each node is specified.
 For example -
[webserver]
192.168.1.23
web host1
[dev]
192.168.1.01
192.168.1.02
[prod]
192.168.1.111
192.168.1.112
 The inventory file is used by ansible to determine which hosts to run tasks on.
 When ansible runs a playbook, it will first look for the inventory file in the current
working directory. If the inventory file is not found, ansible will look for it in the
default location, which is /etc/ansible/hosts. We can modify this file to meet our
needs.
INSTALLATION PROCESS:
 Ansible can run on various operating systems, including Linux, macOS and
Windows.
 However, it‟s most commonly used on Linux. So, we will make use of Linux operating
system to install Linux on it.
 Ansible is written in Python, so we need to have Python installed on our computer.
Prerequisites:
The prerequisites for installing ansible on control node are -
1. A Linux or Unix operating system
2. Python 3.9 or later
3. PuTTy and PuTTyGen
4. SSH access to manage the nodes
The prerequisites for installing ansible on the managed nodes are -
1. Python 2.7 or later
2. Putty to display commands
3. A user account that can connect to control node via SSH
 If the ansible is to be installed using Windows control node then we need Windows
subsystem for Linux (WSL).
Creation of Account on AWS Cloud Service:
 We will install Ansible on Linux machine.
 For that purpose, we will not use the local Linux machine.
 In-fact we will use AWS cloud, create our account over there and we will use the
Linux machine present on the cloud.
 Following are the steps that demonstrate how to create a free account for using AWS
cloud services -
Step 1: Open the web page for aws.com for creating a free account. Click on Create a
Free Account.
Step 2: Enter the necessary details for creating an account such as email-id and user
name.

Click on Verify email address. It will send some verification code to your email account
which you have mentioned. Open your email, get the verification code and enter it.
Step 3: Set the password for your account.
Step 4: Then on next subsequent pop - up windows enter the personal details such as
your address, phone number, country etc.
Step 5: Then on the next screen enter debit or credit card details and PAN number.
Don‟t worry, your bank account will be secure, it wont withdraw any amount from your
account if you are using the free tier services. It is completely safe to share debit card
details.
It will send an OTP on your phone to get-verified. Enter the OTP and proceed.
Finally, on completion of sign up process following window will appear:

Steps for Installation of Ansible:


 The Linux virtual machine on cloud can be created by using the EC2 instance
service of AWS.
Step 1: Launch an AWS EC2 instance
 Log in to AWS cloud services. If you have not created an account in AWS cloud.
 On logging in, click in Launch Instance. Select number of instances as 3. As we are
planning to create one control node and two managed nodes.
 Give the name as ControlNode (You can give any suitable name).
 Select the software Image as Amazon Linux 2 AMI. Note that this must be under
Free Tier eligible.

 Select the Instance Type as t2.micron. (Free tier eligible)


 Now create a keypair for login by clicking on Create new key pair.
Give the name to the key pair and click on Create key pair. The key will be downloaded
automatically.
 Now edit the Network Settings. Select the Create Security group option. Give some
suitable name to security group. I have given the name as AnsibleDemoSG.
 Add two security group rules one for ssh and another for http and for both the
rules add the “Source Type” as Anywhere. It is as shown below -
 Keep the storage as it is. By default it is of 8 GB.
 Under Advanced Details under User data Give following command.
 Click on Launch Instances. It will start creating three instances with the same
name.
 Then click on View All Instances. All the instances with same name ControlNode
will be displayed. Just edit the names of last two nodes. I have edited and changed
their names as ManagedNode1 and ManagedNode2.

Thus three Linux Machine instances - One is control node and other two are the
managed nodes are created.
We can get the public ip and private ip of each instance by selecting that instance.
Following screenshot illustrates how to get the public or private ip of each node -

Step 2: Connect to EC2 instance


 Imagine you have a computer at home, and you want to talk to another computer far
away, then PuTTY lets you have a chat with that far away computer, just like texting
your friend.
 PuTTY is a free and open-source terminal emulator, serial console and network file
transfer application. It supports several network protocols, including SSH, Telnet,
rlogin and raw socket connection. It can also connect to a serial port.
Step 2 (a): Install PuTTY and PuTTYgen from the web site https://www.puttygen.com/.
Now, open Pu TTY gen
Click on Load and select the key file which we have downloaded while generating the
EC2 instances in previous step. I have created a key file by the name mykey so I will
select it and then click on OK.
Then save it as Save Private Key.
Save it by name some suitable name. I have saved it as ansiblekey (Note that the
extension of this file is .ppk). So it is ansiblekey.ppk file.
Step 2 (b): Now open PuTTY. On the other hand, copy the Public IP of your ControlNode
instance from EC2 instances -
paste this key in the PuTTY.

Now click on SSH->Auth->Credentials. Select the path of the key which we have
generated above in step 2(a).In my case the key is ansiblekey.ppk. Click Open. Then
click on the warning which appears.
The PuTTY then opens a terminal as follows -

Then login as ec2-user.


Repeat the Step 2 (b) for remaining two EC2 instances i.e. ManagedNode1 and
ManagedNode2 by copying the public IP of each node and pasting it in PuTTY and
setting up the ansiblekey.ppk key. Thus we have the setup as follows -

Step 3: Update system


Now open the terminal of ControlNode and type the command sudo su to change the
login to root user.
Step 4: Install EPEL
The EPEL stands for Extra Package for Enterprise Linux. This allows to install extra
packages for Linux.
In order to install EPEL package the command is,
wget https://dl fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm.
Thus the epel package gets downloaded. Now we will install it using the command,
[root@ip-172-31-43-225 ec2-user]# yum install epel-release-latest-7.noarch.rpm
Thus the package gets installed. The issue the command,
[root@ip-172-31-43-225 ec2-user]# yum update -y
By this the software packages get updated.
Step 5: Install ansible and other required software
Now we will install some required packages and ansible. For that purpose we issue
following command at the command prompt,
[root@i p-172-31-43-225 ec2-user]# yum install git python python-level python-pip
openssl ansible -y
We can check the installation of ansible by issuing the command,
[root@ip-172-31-43-225 ec2-user]# ansible --version
Just note that above screen-shot it is displaying that the ansible of version 2.9.27 is
installed on your virtual machine (i.e. EC2-instance).
Step 6: Create an Inventory file
In order to open the Inventory file issue following command at command prompt-
[root@ip-172-31-43-225 ec2-user]# vi /etc/ansibl e/hosts
The hosts file gets opened up then create a group by some name. I have created a group
by the name dev. Under this group just copied the private IPs.
Then save the above file by typing: wq keys.
Step 7: Setup ansible configuration
Open the ansible configuration file using the command,
[root@ip-172-31-43-225 ec2-user]#vi /etc/ansible /ansible.cfg
Inside this file uncomment inventory and sudo_user

Step 8: Create ansible user for all the nodes


Create user for ansible with all the privileges. Hence the command is adduser
<user_name> also set the password using passwd <user_name>. You can set user name
and password of your choice.
Create the same username and passwords at both the terminals i.e. for
ManagedNode1 and ManagedNode2
Now switch to this ansible user by issuing the su command as follows at ControlNode
[root@ip-172-31-43-225 ec2-user]# su ansible_user
[ol.ansible_user@ip-172-31-43-225 ec2-user]$
Now switch to this ansible user by issuing the su command as follows at both
ManagedNode1 and Managed Node2
Note that, I have created the ansible user by the name ansible_user and set some
password for all the three nodes i.e. ControlNode, ManagedNode1 and ManagedNode2
Step 9: Set Sudo privileges to ansible user
The ansible user must have the privileges as the root user have. So that the ansible user
also can install the necessary packages on its own. At the ControlNode terminal issue
the command and type exit to come out from ansible user and issue the command
visudo.

Edit the following line to this file so that the ansible user will get all the privileges that
the root user has,
Repeat the above step for both the ManagedNodes i.e. ManagedNode1 and
ManagedNode2
Step 10: Setup ssh configuration file
We have to edit the ssh configuration file. Hence open this configuration file present at
the
ControlNode.
[root@ip-172-31-43-225 ec2-user]# vi/etc/ssh/sshd_confg
Do three tasks inside this file. For that switch in the insert mode by simply typing “i”
Task 1: Uncomment the line “PermitRootLogin yes”
Task 2: Uncomment the line “PasswordAuthentication yes”
Task 3: Comment the line “Password Authentication no”
Save the file by: wq (i.e. colon, w, q)
Do these tasks in ManagedNode1 and ManagedNode2 as well.
then restart the sshd service at all three terminals by issuing the following command
# service sshd restart
Step 11: Connect control node with managed nodes
At the ControlNode terminal issue the command,
ssh <Pri vate IP of Node>
For example,
$ ssh 172.31.42.197
Then enter the password which we have set in step.

Similarly, we can connect to ManagedNode2 by entering the command ssh along with
its
Private IP.

Note that the ControlNode is getting connected to ManagedNode2


We can create some file from ControlNode to ManageNode2 by using touch command.

Open the terminal of ManagedNode2 and verify if the file named test_file1 is getting
created or not by typing the ls command.

Step 12: Establishing password less connection with nodes


When the control node wants to connect to managed node, each time it has to enter the
password of managed node. To avoid this, we must perform following tasks -
Tasks 1: Generate the public and private keys using ssh on the ControlNode
The command to generate the keys is,
ssh-keygen
This creates a directory named .ssh. We can go to this directory and can verify that the
public keys and private keys are getting generated.

Task 2: Copy the public key on all the ManagedNodes


In order to copy the public key generated by the ControlNode in above step is to be
copied at both the ManagedNodel and ManagedNode2. For that the command will be,
ssh-copy-id <ansible user name>@<private ip of node>
Since the user name of ManagedNode1 is ansible_user and its private ip is
172.31.42.197, I have issued the command as follows -

Similarly we can copy the public key to ManagedNode2


Thus now we can directly establish the connection from ControlNode to Managed Nodes
using the command,
ssh <private ip of node>
For example -
[ansible_user@ip-172-31-43-225 -]$ ssh 172.31.42.197
[ansible_user@ip-172-31-43-225 -]$ ssh 172.31.36.169
ANSIBLE MODULES:
 Ansible modules are used to perform various tasks on remote hosts.
 These are basically small, standalone scripts that ansible uses to communicate
with the remote hosts in order to execute specific actions.
 The modules can be executed from the command line or can be written in the
playbooks.
Syntax for writing the module on command line:
 While writing the module we use the options such as -m and -a.
 The –m is for module and -a is for argument, after the -a option we specify the
executable command in double quotes.

Commonly used modules:


1. Command: Following is a command module that executes a command on remote
hosts
$ansible all -m command -a “echo „Hello hosts‟ ”
2. User: The user module is used to create, modify or delete users. For example - To
create a user named „new_user‟ on all the hosts in the „dev‟ group using ansible, you
can use the user module. Here's the ansible command to do that:
$ ansible dev -m user -a “name=new_user state=present”
Sometimes the above command fails as there is no privilege to create user on remote
host. Then we can issue the command as follows
$ ansible all -m user -a “name=new_user state=present” --become --ask-become-
pass
The above command asks for the password for the remote host to login. On
supplying the password, the user will be created.
We can verify if new user is getting created or not on remote host by issuing
following command on each remote host.
$less /etc/passwd
If we want to create new user without asking for password on all the remote hosts
then we can issue the command as -
$ ansible all -m user -a “name=new_userl state=present” --become -b
The -b option is used to become superuser. By this the sudo or su privileges can be
granted.
3. Ping: The ping module is used to connectivity to remote hosts.
$ ansible all -m ping
4. Copy: The copy module is used to copy files from control machine to remote hosts.
$ ansible dev -m copy -a “src=/home/ansible_user/myfile.txt dest=/home
/ansible_user/myfile.txt”
The above command will copy the myfile.txt file from control node to all the
managed nodes of dev group.
5. Package: The package module is used to install, remove or upgrade the packages.
For example, the following command installs the nginx web server package:
$ ansible package -a “name=nginx state=present”
Here name indicates the name of the package to be installed, the state=present
means install the package. Normally “present” is for installation, “remove” is for
removing the package and “latest” is used to upgrade the package.
6. Shell: The shell module is used to run shell commands with more flexibility on
remote hosts. For example - Following shell command executes on remote hosts.
$ ansible dev -m shell -a “cmd=ls”
7. Service: The service module is used to start, stop or restart a specific service on
remote hosts. For example - Following service will start the apache web service on all
the remote hosts.
$ ansible dev -m service -a “name=apache2 state=started”
YAML BASICS:
 The YAML is human - readable data serialization language which is used to write
ansible playbooks.
 YAML stands for yet another markup language or YAML ain‟t markup language (a
recursive acronym), which emphasizes that YAML is for data, not documents.
 YAML is very popular because it is easy to read and understand.
 YAML files use a .yml or .yaml extension and follow specific syntax rules.
 Every YAML file starts with 3 dashes (---) while the file ends with three dots (...).
 Indentation and whitespaces: In YAML Python-style indentation is used to
determine the structure and indicate nesting. The indentation level must be
consistent throughout the document. The indentation is typically done using
number of spaces. Normally 2 spaces, 4 spaces per level of indentation is done.
 Comments: Comments can be identified with a pound or hash symbol (#). It‟s
always a best practice to use comments, as they describe the intention of the code.
YAML does not support multi-line comment, each line needs to be suffixed with the
pound character. For example
# This line is YAML comment
 Key value pair: The YAML script is based on key value pair. The key is followed by
colon and value is placed after the colon. The value can be string, number of any
other data type. The key value pair is used to store data, for defining the task or for
specifying the configurations. For example
name: “Ganesh
age: 47
msg: “Welcome Friend”
 List: In YAML we can declare a list or arrays. The list is used to define multiple items
under a single key. For example
Days:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
 Dictionaries: Dictionaries or maps can be created with the help of key value pair.
The dictionaries are represented as mappings. The mappings are basically the key
value pairs. For example

 The student dictionary has three key - value pairs - name, std and address. The
address dictionary has three key value pairs street, city and state.
 Multi-line values: There are two ways to define multi - line values in YAML.
 Literal style: We can define the multi - line values in YAML by using | character
at the start of value followed by newline. This is a way to represent multiline text
in a more readable format while preserving line breaks and indentation.
os: |
Windows
Linux
MacOs
The output of above representation will be -
Windows\nLinux\nMac Os\n
 Folded style: Use the > character to start the value and then end the value with
a newline character (\n). This is useful for writing long paragraphs of text
without introducing line breaks. newlines are converted to spaces, but it can be
useful for preserving leading indentation. For example,
os:>
Windows
Linux
MacOs
The output will be,
Windows Linux MacOs\n
 Data types: YAML supports various scalar data types, including strings, numbers,
Booleans and null values. Scalars do not require special syntax; you can simply
write them as plain values. For example -
name: Arun
age: 21
is_married: false
null_val: null
 YAML is a superset of JSON: As YAML is a superset of JSON (JavaScript Object
Notation), any valid JSON document should be valid YAML.
For example
{
“os”: “Enter your favourite operating system”,
“osystems” [
“Windows”, “Linux”, “MacOs”
]
}
The above can be converted as -
“os”: “Enter your favourite operating system”,
“osystems”: [“Windows”, “Linux”, “MacOs”]
Benefits of YAML Files:
 Human-readable: It is more human-readable. YAML allows you to represent complex
data structures in a human-readable format.
 Simple to use: It has a simple and clean syntax. YAML is easy to learn and Simple
to read. It can express a wide variety of different native data structures.
 Fast: It has fast implementations. YAML is fast to load and easy to process in
memory.
 Unambiguous: It is unambiguous. YAML unambiguously specifies the data
structures of the serialized data.
 Portable: It is portable across most programming languages. YAML supports
representing sequences as lists and mappings as dictionaries.
 Matching with popular languages: It matches native data structures of modern
programming languages such as Python, Ruby and JavaScript.in a language-
independent manner.
 Secure implementation: It has secure implementations.
ANSIBLE PLAYBOOKS:
• An ansible playbook is a set of instructions that ansible uses to automate tasks on
remote
hosts. Playbooks are written in YAML, a human-readable format.
• The playbooks are similar to an ansible to-do list that has a list of tasks.
• The extension to the playbook file is .yml or .yaml.
• The structure of playbook is as shown below ­

Each playbook contains following important elements:


• Hosts: In a play, we can specify the target hosts or groups of hosts where you want to
apply the tasks.
• Play: Playbooks are collections of one or more plays that are performed in certain
order. A play is an ordered sequence of tasks performed against hosts from the
inventory file (host file) which we define.
• Tasks: Tasks are the individual units of work within a play. Each task represents an
action to be taken on the; target hosts. Tasks can include ansible modules, which are
predefined scripts to perform various actions on remote hosts, such as installing
packages, managing services, copying files and more.
• Modules: Ansible provides a wide range of modules for different purposes. Modules are
used in tasks to perform specific actions. Examples include the yum module for package
management, the service module for managing services, the copy module for copying
files
and many more.
Along the above basic elements we can define variables, handlers and roles in the
playbook.
ANSIBLE ROLES:
• The playbooks we write. contain the tasks for configuration management. Sometimes
the
playbook gets populated with number of tasks, variables and handlers and makes it
difficult to understand and manage. In order to avoid such a mess, the concept of
ansible roles came into picture.
• In ansible roles there is a specific directory structure and the tasks can be separated
out in the appropriate files according to their functionalities. These files can be called
as per requirements.
• Ansible roles help structure and modularize our ansible projects.
• Using ansible roles we can make the server configuration tasks more maintainable,
reusable and easier to understand.
• The purpose of ansible roles is to encapsulate the set of tasks, variables and files that
define a specific piece of functionality for the target system.
• Ansible roles are like ready to use components for ansible playbooks. They allow you to
reuse code that has already been written and tested and they help you to build complex.
playbooks more efficiently.
Benefits of Ansible Roles:
• Reusability: Roles can be reused in multiple playbooks, which saves our time and
effort.
• Modularity: Roles help to keep ansible playbooks organized and modular.
• Shareability: Roles can be easily shared with other ansible users.
• Consistency: Roles help to ensure that ansible tasks are performed consistently across
different playbooks.
Typical Structure of Ansible Role:

• defaults: It stores the default variable for the role. For example, the default port
number is http is 8080, then it can be stored in defaults.
• files: This folder contains the files required to transfer or deploy to the target
machines.
• handlers: It contains handlers, which may be used by some role.
• meta: It defines some data or information about the role.
• tasks: It contains the main list of tasks to be executed by the role. These tasks might
be
defined in separate files as per the functionalities.
• templates: It contains the templates which can be deployed via a role.
Demo Example:
Start EC2-instance for ControlNode, ManagedNode1 and ManagedNode2
• Copy the public IP of ControlNode, Open PuTTY and paste it
• Select the path for your ansible_key.ppk file and insert it in PuTTY at Credentials
• This will allow you to open a terminal window for ControlNode.
• Repeat these steps for MangedNode1 and ManagedNode2 to get their terminal
windows.
Step 1: In the ControlNode terminal window, firstly login as EC2-intstace, then as root
user and then as ansible user. In my case the name of my ansible user is ansible_user.
Create a directory named roles using the command.
$ mkdir roles
Then switch to the roles folder using the command cd roles. To create a ansible roles,
use ansible-galaxy command which has the templates to create it.
The syntax for the command is ansible-galaxy init <name_of_role> --offline
Following screenshot creates a role named myweb

Ansible galaxy is a galaxy website where users can share roles and to a command – line
tool for installing, creating and managing roles. To create a role we use the ansible -
galaxy init command.
Here the name of the role is myweb. You can give any name of your own choice. The -
offline attribute is used to avoid the online repository getting downloaded.
Now issue the tree command. If the tree command is not working then install it using
the
command
$ sudo yum install tree
If we issue tree command then
We have got the clean directory structure with the ansible - galaxy command. Each
directory-must contain a main.yml file, which contains the relevant content.
Step 2: Now we will create different tasks and each task will be written in separate file.
These tasks files must be specified in main.yml file of tasks folder. Hence first of all , we
write the code in main.yml files. Just locate the tasks directory and open the main.yml
file using vi editor

main.yml[ Inside tasks folder ]


# tasks file for myserver
- mclude: install yml
- include: configure.yml
- include: service. yml
Just press colon (:) wq and exit from the file.
Step 3: Now in tasks folder inside the main.yml file we have included three files -
install.yml, configure.yml and service.yml. We will write each file one by one -
install.yml
--- # installin g httpd package
- name: install Apache server
yum:
name : httpd
state: latest
configure.yml
--- # send index.html file
- name: send index.html
copy: src=index.html dest=/var/www/html/index.html
service.yml
--- # start httpd service
- name: starting http servic e
service : name=httpd state=started
Step 4: Now move inside the files folder. Inside this files folder we will create one static
file named index.html which we want to display on web browser of each managed node.
Just create index.html file using vi editor
index.html
<html>
<h1> Hello Anuradha, how are you? </hl>
<h4> Enjoy working with Ansible roles </h4>
</html>
Step 5: Now if we issue the tree myweb command we get following screenshot.

Step 6: Finally, we will create a master.yml file which will invoke all the tasks defined in
tasks folder. This task file must be created at the top level of the roles directory.

master.yml
--- # This is master file that calls the roles
- hosts: dev
user: ansible_user
become: yes
connection: ssh
roles:
- myweb
The master.yml file is located inside the roles folder
Now, prior to actual execution of master.yml file, we can issue the following command
to check if any syntactical error exist or not –
$ ansible-playbook master.yml –syntax-check
Then issue the actual execution command, as there are no syntactical error in our
master.yml file. The command is ansible-playbook master.yml.
Step 7: We can verify the execution of above web server by following steps -
(1) Open the EC2-instance of ManagedNode1, copy the public IP of that instance.
(2) Open the web browser such as Microsoft Edge or FireFox and issue the web address
as http://<public_ip_of_instance _host>. Your index.html page will be displayed as
output.

Congratulations!!! We have successfully executed the ansible roles.


AHOC COMMANDS IN ANSIBLE:
The ansible adhoc commands are CLI (Command Line Interface) commands used for
simple and one time task such as shutting down all the hosts at a time or transferring
some file to all the nodes.
The adhoc commands are quick and easy but they are not reusable.
The adhoc commands are used in ansible to perform tasks or operations that are needed
on immediate basis or only as per the requirements.
Syntax for Adhoc Commands:
$ ansible <hosts> [-m <module name> ] –a <“arguments”>-u<username> [--become]
(1) To test the connection between ControlNode and all the managed nodes
$ ansible dev -m ping
It returns following result
172.31.36.169 | SUCCESS => {
“ansible_facts” {
“discovered _interpreter _python”: “/usr/bin/python”
},
“changed”: false,
“ping”: “pong”
}
172.31.42.197 ] SUCCESS => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: false,
“ping”: “pong”
(2) To check the list of all the hosts
$ ansible dev -a “ls”
Note that dev is the naine of the group of hosts the -a attribute denotes the argument.

We can select particular host from the group of hosts. For instance, if the group of
servers is named as dev then dev [0] denotes first server in the group, dev [1] represents
second server and so on. If we denote dev [-1] then it denotes the last server.
(3) To check the uptime of all the servers can be obtained by using following
commands,
$ ansible dev -m command -a uptime
$ ansible dev -m shell -a uptime
$ ansible de -a uptime
The result can be -

(4) To check the free memory or memory usage of hosts


$ ansible dev -a “free –m”
(5) To get the physical memory allocated to the hosts
$ ansible dev -m shell -a “cat/proc/meminfo|head -2”
172.31.36.169 | CHANGED | rc=0 >>
MemTotal: 975592 kB
MemFree: 666956 kB
172.31.42.197 | CHANGED | rc=0>>
MemTotal: 975592 kB
MemFree: 666416 kB
(6) To transfer a file to all the hosts of a group
$ ansible dev -m copy -a “src=/test_file.txt dest=-/test_file.txt”
By above command, we can copy the test_file.txt of current working directory will. get
copied to all the hosts present in the dev group at their current working directories.
(7) To create a new directory on all the hosts of a group
$ ansible de -b –m copy -a “src = /home/ansible_user /my_test_dir dest=/var/tmp”
The -b option is used to indicate to become the root user.
(8) To manage a package on all the hosts
In order to install the network time protocol(ntp) package all the connected hosts, we can
use following ad-hoc command from control node.
$ ansible all -b -m yum -a “name=ntp state=present”
To manage a service on all the hosts
To start a service
$ ansible dev -m service -a “name=ntp state=started enabled=yes”
To restart a service
$ ansible dev -m service -a “name=ntp state=restarted”
To stop a service
$ ansible dev -m service -a “name=ntp state=stopped”
(9) To gather the facts
The setup module returns detailed information about the remote systems managed by
ansible, also known as system facts. The adhoc comimand is -
$ ansible dev -m setup
(10) To reboot the all the servers
Although ansible doesn‟t have a dedicated module to restart servers, we can issue a bash
command that calls the /sbin/reboot command on the remote host.
$ ansible dev -a “/sbin/reboot”

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy