Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Ansible

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Ansible

What is Ansible ?
Ansible is an open source automation and orchestration tool for software provisioning, configuration
management, and software deployment. Ansible can easily run and configure Unix-like systems as well
as Windows systems to provide infrastructure as code .

Why is Ansible ?
One of the most significant advantages of Ansible is that it is free to use by everyone.
It does not need any special system administrator skills to install and use Ansible
Its modularity regarding plugins, modules, inventories, and playbooks make Ansible the perfect
companion to orchestrate large environments .
Ansible is very lightweight and consistent, and no constraints regarding the operating system or
underlying hardware are present
It is also very secure due to its agentless capabilities and due to the use of OpenSSH security features .

Important Terms in Ansible


Ansible Server - The machine where Ansible is installed and from which all tasks and playbooks will
be ran
Module - Basically, a module is a command or set of similar Ansible commands meant to be executed
on the client-side
Tasks - A task is a section that consists of a single procedure to be completed
Role - A way of organizing tasks and related files to be later called in a playbook
Inventory/hosts -File containing data about the ansible client servers. Defined in later examples as
hosts file (Path - /etc/ansible/hosts)
Play -Execution of a playbook
Handler -Task which is called only if a notifier is present
Ansible configuration file /etc/ansible/ansible.cfg

Notifier -Section attributed to a task which calls a handler if the output is changed

Ansible Configuartion File Parameter(In this file by default all


parameters has been commented but when we’ll do entry of nodes and
group of nodes in /etc/ansible/hosts file then we have to uncomment
inventory parameter and as well as sudo user parameter)
Like - #inventory – inventory and #sudo_user – sudo_user
# config file for ansible -- https://ansible.com
# nearly all parameters can be overridden in ansible-playbook
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first
[defaults]
# some basic default values...
#inventory = /etc/ansible/hosts
#library = /usr/share/my_modules/
#module_utils = /usr/share/my_module_utils/
#remote_tmp = ~/.ansible/tmp
#local_tmp = ~/.ansible/tmp
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml
#forks =5
#poll_interval = 15
#sudo_user = root
#ask_sudo_pass = True
#ask_pass = True
#transport = smart
#remote_port = 22
#module_lang = C
#module_set_locale = False

Hosts file Path - /etc/ansible/hosts


# This is the default ansible 'hosts' file.
# It should live in /etc/ansible/hosts
# - Comments begin with the '#' character
# - Blank lines are ignored
# - Groups of hosts are delimited by [header] elements
# - You can enter hostnames or ip addresses
# - A hostname/ip can be a member of multiple groups

# Ex 1: Ungrouped hosts, specify before any group headers.


## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10
[demo]
172.31.34.69
172.31.44.213

[tomcat-nodes]
172.31.34.69
# Ex 2: A collection of hosts belonging to the 'webservers' group
## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110

Ansible Ad-hoc Commands (Note – If you run this command with local
user then add that user in sudoers file and start command syntax with
sudo command )
Syntax – sudo ansible <group of nodes/single node> -a “command

If you don’t want to use sudo command everytime then use –b option with a

Syntax – ansible <group of nodes/single node> -ba “command – it will execute without using sudo

-b option is used to become that is sudo

➢ It is nothing but the simple linux commands to execute simple task on nodes at a time
➢ If we don’t know that which module is used to done some other work on nodes then we can use
ad-hoc commands
➢ Ad-hoc commands are that commands which can run individually to perform quick functions
➢ These are of one time usage only
➢ Ad-hoc commands Path - /usr/bin/ansible
➢ Ansible commands –
➢ Syntax – ansible <node group name/single node> <argument> “command”
➢ Actual command – ansible 192.168.0.54/all/group_of_node –a “touch file1.txt”
➢ (Note – -a is used to execute ahead command)
➢ It will create file on 192.168.0.54 this node
➢ If we want to perform a task on all nodes then here below is that command
➢ Command – ansible all –a “command”
➢ If we want to perform a task on particular node within group
➢ Syntax – ansible <name of nodes group> [no of node] –a “command”
➢ (Note – first node of group is consider as 0 and last node is consider as -1)
➢ Command – ansible demo[0] –a “command”
➢ If we want to perform within two group of node on particular nodes individually then go
through below command
➢ Syntax – ansible <group1>[node no]:<group2>[node no]
➢ Command – ansible demo[0]:tomcat_nodes[2] –ba “yum install httpd –y”
➢ (Above command will execute on first node of group demo and as well as 3rd node of group
tomcat_nodes)
➢ If we want to perform a task within group of nodes in range of nodes then below is the
command
➢ Syntax – ansible <group of nodes>[node-node] –ba “command”
➢ Command – ansible tomcat_nodes[0-3] –ba “yum install tree –y”

Ansible Modules – Ansible ships with the number of modules that can be executed directly
nodes or through playbook
There are no servers , deamons or database required

Syntax of Modules - # ansible <node/group_of_nodes> –b –m <module_name> “command”


Ex. 0f Modules - # ansible 172.20.33.77/demo –b –m shell “touch /file state=present”
Description – (-b option is denoted for become and used to give sudo privilege)
(-m option is denoted for module and used to assign module)
(-a option is denoted for action and used to execute command)

Some Important modules which I have used in my task or playbook


1) Yum – it is used to install , remove or update packages

Syntax for single command - # ansible <group of node> -b –m yum –a “pkg=<pkg_name>


state=present/absent/update

Syntax for Playbook –

- name: Updating Repo


yum:
name: "<pkgname>"
state: latest/remove/absent/present
If you want to install or remove pkgs then state: present/installed/remove

2) User – it is used to create/remove user Parameter used in User module

(Name , password , state , shell , createhome , home)

Syntax for Plabook –

- name: Creating User Tomcat


user:
name: "{{user}}"
password: "{{passwd}}"
state: present
shell: "{{shell}}"
createhome: yes
home: /home/{{user}}

3) File – It is used to create directory or file / as well as changing ownership forcefully Parameter
used in file module (path , state , owner , group , mode , remote_src , recurse)
Syntax –
- name: Creating Directory Tomcat in /
file:
path: "{{path}}"
state: directory
owner: "{{user}}"
group: "{{user}}"
mode: "{{perm}}"
remote_src: yes
Changing ownership –
- name: Changing ownership recursive
file:
path: "{{path}}"
state: directory
owner: "{{user}}"
group: "{{user}}"
recurse: yes

4) get_url – It is used to download any package or file using url Parameter used with get_url
module as ( url , dest )
Syntax -
- name: Downloading Tomcat Tar
get_url:
url: "{{tomcat_url}}"
dest: /{{path}}

5) unarchive – it is used to untar file Parameter used with unarchive module as (src , dest ,
remote_src)
Syntax –
- name: Unarchiving apache tomcat
unarchive:
src: /tomcat/apache-tomcat-{{req_tomcat_ver}}.tar.gz
dest: /tomcat
remote_src: yes

6) copy – It is used to copy files from ansible engine or from target server to target servers if your
war file is present in your ansible server and you want to deploy on your nodes then simply give
path as src: ./{{dep_war}} because my current war file location is /ansible/playbook/sample.war
and I am already under this path that is cd /home/ansible/playbook that’s why I have mentioned
as src: ./{{dep_war}} ( It is the variable name which I add in vars/main.yml file - {{dep_war}}
Parameter used with copy module as ( src , dest , remote_src)
Syntax –
- name: deploying war file
copy:
src: ./{{dep_war}}
dest: /tomcat/apache-tomcat-{{req_tomcat_ver}}/webapps
remote_src: yes

7) shell – it is used to execute shell command to start services


Syntax –
- name: Starting Tomcat Service
shell: nohup /tomcat/apache-tomcat-{{req_tomcat_ver}}/bin/startup.sh

(Note – here nohup parameter is used for to start service beacuase in case if you not use nohup
parameter with this module it wont be start your service because when you start your service only with
This /tomcat/apache-tomcat-{{req_tomcat_ver}}/bin/startup.sh service will start but after it will exit
that’s why we must have to mention nohup parameter with this to execute and to run in background

If you are working with role to complete any task then follow below
steps –
Install ansible Server which will do manage nodes within your environment do below steps on ansible
server and as well as your nodes

Ansible Installation On Linux on Redhat and Centos


Install EPEL repo
wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
yum install epel-release-latest-7.noarch.rpm

yum install python python-devel openssl python-pip ansible –y

Check Ansible version


[root@server ~]# ansible --version
ansible 2.9.18
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules',
u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /bin/ansible
python version = 2.7.18 (default, Feb 18 2021, 06:07:59) [GCC 7.3.1 20180712 (Red Hat 7.3.1-12)]

1) first of all we need to add our target server/target nodes in inventory file that is
/etc/ansible/hosts , you can assign group of nodes or single ip its upto you below are the demo
group with two nodes

vim /etc/ansible/hosts

[demo]
172.31.34.69
172.31.44.213
:wq
2) Second step we want to states ansible server that inventory file present there then we have to go
in configuration file and uncomment the inventory parameter as well as sudo user parameter
Because with the local user you cant do anything done on nodes

Vim /etc/ansible/ansible.cfg
# some basic default values...
inventory = /etc/ansible/hosts
#library = /usr/share/my_modules/
#module_utils = /usr/share/my_module_utils/
#remote_tmp = ~/.ansible/tmp
#local_tmp = ~/.ansible/tmp
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml
#forks =5
#poll_interval = 15
sudo_user = root
:wq

Once if it is done then Create user on both server and nodes and give password and root user privilege
to them
[root@ip] # useradd ansible
[root@ip] # passwd ansible

Now go to sudoers file and add them into it


[root@ip] # Visudo
Find ALL=(ALL) with /ALL=(ALL) in command mode you will go on exact line like below
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
ansible ALL=(ALL) NOPASSWD: ALL – add this line below root
:wq save and quit

3) Third step we have to established ssh connection on ansible server as well nodes because
ansible is agentless and need not any agent or software to do work with nodes
First we need to go in ssh config file and and make changes with root user
[root@ip] # vim /etc/ssh/sshd_config
Do passwordAuthentication=yes
:wq

4) Once if it will done then ping your nodes with ansible server with simple ping command it will
pinged but while working with task we cant put password each and every time during task
execution that’s why we need to configure key-based authentication on server side as well as on
nodes
5) Now go with ansible user and do below steps to established ssh connection without giving
password each and every time (it is called trust relationship as well that is root-root , local-local)
[root@ip] # Su – ansible
[ansible@ip] $ ssh-keygen --- it will generate key-pair in current location like below

Generating public/private rsa key pair.


Enter file in which to save the key (/home/ansible/.ssh/id_rsa):
Created directory '/home/ansible/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/ansible/.ssh/id_rsa.
Your public key has been saved in /home/ansible/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:28yTN/j3oQGwPOmoASCQQqPY7PcG4Aq4cTh7QM8ajgA ansible@server.ansible.com
The key's randomart image is:
+---[RSA 2048]----+
|o+ |
|*o. |
|Eo+ . |
|=++. . + |
|O.++o S= . |
|=Oo..o o=.o. |
|=o. .o...B o. . |
| . .o + .+ .|
| . .o ..|
+----[SHA256]-----+

Now we have two keys that is private key and public key
Now we want to dispatch public key on all nodes which you will manage respectively go with below
command
[ansible@ip] $ ssh-copy-id ansible@172.31.34.69
o/p – public key will be gone on your node

6) Now take ssh of your nodes it wont be ask for password to connect with it

[ansible@ip] $ ssh ansible@172.31.34.69


[ansible@172.31.34.69] $

It means our key-based authentication is successfully configured

7) Now go to your ansible server and login with ansible user who will managed nodes
[ansible@ip] $ pwd
/home/ansible

Now Create Some parent directories for to do task with roles


Create one directory name playbook
[ansible@ip] $ mkdir playbook

Now go inside the playbook directory and create some other parent directories
[ansible@ip] $ cd playbook
[ansible@ip playbook] $ mkdir –p roles/tomcat/tasks
[ansible@ip playbook] $ mkdir roles/tomcat/vars
8) Now create a master.yml file which will call your created role to execute your task on nodes and
it will create parallely with roles directory
[ansible@ip playbook] $ touch master.yml

You will see structure like below


[ansible@server playbook]$ tree
.
├── master.yml
├── roles
│ └── webserver
│ ├── handlers
│ │ └── main.yml
│ ├── tasks
│ │ ├── main.yml
│ │
│ └── vars
│ └── main.yml
├── sample.war

9) Now add below lines in master.yml


[ansible@ip playbook] $ vim master.yml
- hosts: demo -------> hosts group name
user: ansible ---------> with user
become: yes ----------> with sudo
connection: ssh ------> to connect with ssh
roles: -------> module
- tomcat -----> rolename

:wq save and exit

10) Now create variable file name main.yml under roles/tomcat/vars dir
[ansible@ip playbook] $ vim roles/tomcat/vars/main.yml

java_ver: java-1.8.0-openjdk.x86_64
user: tomcat
passwd: tomcat
shell: /bin/bash
path: /tomcat
perm: 0770
req_tomcat_ver: 8.5.65
tomcat_url: https://downloads.apache.org/tomcat/tomcat-{{ req_tomcat_ver.split('.')[0] }}/v{{
req_tomcat_ver }}/bin/apache-tomcat-8.5.65.tar.gz
dep_war: sample.war

:wq save and quit


(Note – You can assign any variable under vars/main.yml file according to your task )
11) Now create main task file name main.yml under roles/tomcat/tasks/ dir , Here you have to write
your task with respect to assigning variable which mention in vars/main.yml file
roles/tomcat/tasks/main.yml (it contains all task which you perform on nodes)
(Imp_Note – Indentation is very important part during write your playbook Task should start
with “---“ three hyphen)
[ansible@ip playbook] $ vim roles/tomcat/tasks/main.yml

--- # tomcat installation with deploying war file and start --> it is just heading of your playbook
- name: Updating Repo ---------------------> it is just message you can right here according to your task
yum: ----------------> module name
name: "*" ----------------> supported parameters
state: latest
- name: Installing Required Java
yum:
name: "{{java_ver}}"
state: latest
- name: Creating User Tomcat
user:
name: "{{user}}"
password: "{{passwd}}"
state: present
shell: "{{shell}}"
createhome: yes
home: /home/{{user}}
- name: Creating Directory Tomcat in /
file:
path: "{{path}}"
state: directory
owner: "{{user}}"
group: "{{user}}"
mode: "{{perm}}"
remote_src: yes
- name: Downloading Tomcat Tar
get_url:
url: "{{tomcat_url}}"
dest: /{{path}}
- name: Changing ownership recursive
file:
path: "{{path}}"
state: directory
owner: "{{user}}"
group: "{{user}}"
recurse: yes
- name: Unarchiving apache tomcat
unarchive:
src: /tomcat/apache-tomcat-{{req_tomcat_ver}}.tar.gz
dest: /tomcat
remote_src: yes
- name: deploying war file
copy:
src: ./{{dep_war}}
dest: /tomcat/apache-tomcat-{{req_tomcat_ver}}/webapps
remote_src: yes
- name: Starting Tomcat Service
shell: nohup /tomcat/apache-tomcat-{{req_tomcat_ver}}/bin/startup.sh

:wq save and quit

12) you can check before to run playbook


syntax - $ ansible-playbook <name of master yml file> --check
command - $ ansible-playbook master.yml --check ------------> it will gives o/p as actual execution

13) Now run the playbook with below command you will get output as given below
[ansible@server playbook]$ ansible-playbook master.yml

PLAY [demo]
*************************************************************************************
*********************************************

TASK [webserver : Updating Repo]


*************************************************************************************
************************
[WARNING]: Platform linux on host 172.31.44.213 is using the discovered Python interpreter at
/usr/bin/python, but future installation of
another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for
more information.
changed: [172.31.44.213]
[WARNING]: Platform linux on host 172.31.34.69 is using the discovered Python interpreter at
/usr/bin/python, but future installation of
another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for
more information.
changed: [172.31.34.69]

TASK [webserver : Installing Required Java]


*************************************************************************************
*************
changed: [172.31.34.69]
changed: [172.31.44.213]

TASK [webserver : Creating User Tomcat]


*************************************************************************************
*****************
[WARNING]: The input password appears not to have been hashed. The 'password' argument must be
encrypted for this module to work properly.
changed: [172.31.44.213]
changed: [172.31.34.69]

TASK [webserver : Creating Directory Tomcat in /]


*************************************************************************************
*******
[WARNING]: The value True (type bool) in a string field was converted to u'True' (type string). If this
does not look like what you expect,
quote the entire value to ensure it does not change.
changed: [172.31.34.69]
changed: [172.31.44.213]

TASK [webserver : Downloading Tomcat Tar]


*************************************************************************************
***************
changed: [172.31.34.69]
changed: [172.31.44.213]

TASK [webserver : Changing ownership recursive]


*************************************************************************************
*********
changed: [172.31.44.213]
changed: [172.31.34.69]

TASK [webserver : Unarchiving apache tomcat]


*************************************************************************************
************
changed: [172.31.44.213]
changed: [172.31.34.69]

TASK [webserver : deploying war file]


*************************************************************************************
*******************
changed: [172.31.44.213]
changed: [172.31.34.69]

TASK [webserver : Starting Tomcat Service]


*************************************************************************************
**************
changed: [172.31.44.213]
changed: [172.31.34.69]

PLAY RECAP
*************************************************************************************
**********************************************
172.31.34.69 : ok=9 changed=9 unreachable=0 failed=0 skipped=0 rescued=0
ignored=0
172.31.44.213 : ok=9 changed=9 unreachable=0 failed=0 skipped=0 rescued=0
ignored=0

Now you have successfully install tomcat on your target nodes within some minutes without taking to
much time.
Thanks !

Flow of Task with Role


1) When you execute master.yml that time python interpreter will goes on your nodes and bring
back with gathering all information.
2) So basically master.yml will call the role which we have mentioned in it
3) Role will call their respective directories that is vars, tasks , handlers etc and will executes
main.yml file within all directories with respective to each other
4) Flow - master.yml--> roles--> role name--> vars/tasks dir--> main.yml file and will executes your
task on nodes

You might also like