+91 9619904949

Ansible is an open-source configuration management, deployment, and orchestration tool. It aims to provide large productivity gains to a wide variety of Automation challenges.

Ansible Introduction:

✓ Ansible is a simple open-source IT engine that automates: application deployment, intra-service orchestration, cloud provisioning, and many other IT tools.

✓ Ansible is easy to deploy because it does not use any agents or custom security inf restructure.

✓ Ansible uses playbook to describe automation jobs, and playbook uses very simple language i.e., YAML

✓ Ansible is designed for multi-tier deployment.

✓ Ansible uses the hosts’ file where one can group the hosts & can control the actions of a specific group in the playbooks.

Michael Dehaan developed Ansible and the Ansible project began in February 2012.

Redhat acquired the Ansible tool in 2015. it is available for RHEL, Debian, Centos, Oracle Linux, etc.

Can we this tool whether your servers are on-premises or in the cloud? It turns your code into infrastructure ie your computing environment has some of the same attributes as your application.

Why Do We Require Ansible:

✓ Ansible automates and simplifies repetitive, complex, and tedious operations.

✓ Ansible is open source, saves time as well as human efforts & is easy to implement.

✓ Ansible architecture is simple and effective, It works by connecting to your nodes & pushing small programs to them.

✓ Ansible is a push-based architecture & doesn’t need any agents running on the client nodes.

✓ Ansible works over SSH and doesn’t require any daemons, special servers, or libraries to work. A text editor and a command line tool are usually enough to get your work done.

✓ Ansible infrastructure is described in a text file (INI) and then all the information about the desired state of these machines is organized in playbooks.

Advantages: –

Ansible is free to use by everyone.

Ansible is very consistent and lightweight and no constraints regarding the OS or underlying hardware are present

Ssh-id is very secure due to its agent-less cooler abilities and open SSH security features.

Ansible does not need any special system administrator skills to install and use it.

Push mechanism.

Disadvantages: –

An insufficient user interface, though Ansible tower is GUI it is still in the development stages.
Cannot achieve full automation by Ansible.
New to the market therefore limited support and document are available.
The “yum install ansible” command installs ansible and all the configuration files by default are stored in the /etc/ansible directory.

/etc/ansible/ansible.cfg is the main configuration file and /etc/ansible/hosts is the default configuration file but each user cannot update the files.

So users can use their own environment to run ansible. For eg: anil is a DevOps admin and their role is to manage the web server but he doesn’t have root access.

So anil can setup his ansible environment as per below

 

#mkdir /home/anil/ansible

#cp /etc/ansible/ansible.cfg /home/anil/ansible

#vi /home/anil/.bashrc
And add
export ANSIBLE_CONFIG=/home/anil/ansible/ansible.cfg

#vi /home/anil/ansible/ansible.cfg
And add
inventory      = =/home/anil/ansible/anil-hosts

 

Ad-hoc Commands: –

Ad-hoc commands are commands which can be run individually to perform quick functions

these ad-hoc commands are not used for configuration management and deployment because these commands are of one-time usage.

The Ansible ad-hoc commands use the “Ansible” command line tool to automate a single task.

Ansible is the module: – Ansible module is an executable plug-in that gets the real job done it is invoked with the command line or Ansible playbook

Ansible ships with a number of modules (called module libraries) that can be executed directly on remote servers or through playbooks. Your library of modules can reside on any machine, there are no servers demons, or databases required.

Vault:-

Ansible allows Keeping passwords are keys in than plaintext inSensitive data such as encrypted files, rather than your playbooks.

Terms used in Ansible:-

Ansible Server The machine where Ansible is installed and from which all tasks and playbooks will be run.
Module Basically, a module is a command or set of similar commands meant to be executed on the client side.
Task A task is a section that consists of a single producer to be completed.
Role A way of organizing tasks and related file to be later called in a Playbook.
Fact Information is fetched from the client system from the Global variables with the gather facts operation.
Inventory The file contains data about the Ansible client servers.

vi /etc/ansible/hosts this file used for managing clients and groups.

Example of /etc/ansible/hosts 

#Making a comment in my hosts’ file

rainbows.nitwinngs.com

[testServer]
52.36.167.137 ansible_user=ec2-user ansible_ssh_user=ec2-user
test1.nitwinngs.com:2222

[testServer:vars] ansible_user=ec2-user

[webServers]
apache[01:50].nitwinngs.com
nginx[50:100].nitwinngs.com
Postfix.us[1:50].nitwinngs.com

[appServers]
app[a:f].nitwinngs.com

Play Execution of playbook.
Handler Task Which is called only if the notifier is present.
Notifier Section attributed to a task that calls a handler Output is changed.
Playbooks It consists of code in YAML  format, which describes tasks to be executed.
Host Nodes that are automated by Ansible

Roles:-
We can use two techniques for reusing tasks:-

  • include
  • roles

roles are good for organizing tasks and encapsulation data needed to accomplish those tasks.

we can organize the playbook into a directory structure called roles.

adding more and more functionality to the playbook will make it difficult to maintain in a single file.

Default It Stores the data about role/application Default Variables e.g. if you want to run to port 80 or 8080 then Variables need to define in this path.
Files It Contains files that need to be transferred to the remote VM (static files)
Handlers They are triggers or tasks. We Can Segregate all the handlers required in Playbook
Meta This directory contains files that establish roles dependencies eg, Author Name, Supported platform, and Dependencies if any.
Tasks It Contains all the tasks that are normally in the playbook eg, Installing packages and Copying files, etc.
Vars Variables for the role Can be specified in this directory and used in your Configuration files Both Vars and default stores Variables.

 

VARIABLE PRECEDENCE:-

1 Role defaults
2 Inventory variables
3 Inventory group_vars
4 Inventory host_vars
5 Playbook group_vars
6 Playbook host_vars
7 Host facts
8 Registered vars
9 Set_facts
10 Play vars
11 Play vars_prompt
12 Play vars_files
13 Role and include vars
14 Block variables
15 Task variables
16 Extra_vars

Basic Command:-

 

yum install epel-release.noarch Install Epel repo
Yum install ansible Install Ansible
Ansible –version
Ansible all –list-hosts The “all” pattern refers to all the machines present in an inventory file.
Ansible group-name –list-hosts

 

List all the hosts present in the specific group
Ansible group-name[0] –list-hosts group-name[0]   0=1st host of group
group-name[1]    1= 2nd host of group
group-name[-1]   -1= last host of group
group-name[1:5]  1:5] 2nd to  6th  host of group
groupname1[1:5]:groupname2[2:6] host of 2 different group
Ansible all  -a  “ls”
Ansible group-name  -a  “ls” -kEg:-Ansible mail  -a  “ls”
 Run command for all hosts or specific groups. By default, module is a command Where

-a is an argument
-k for asking password

Ansible web -m command -a “ls” The command module runs a single command on specific group hosts.
Ansible web -m raw  -a “ls; dir; date;ifconfig” Use the RAW module to fire multiple commands.
Ansible web -m copy -a ‘src=/etc/apf/conf.apf_glob  dest=/etc/apf/conf.apf owner=root group=root mode=660 backup=yes’ Copy module
Ansible web -m copy -a ‘src=/tmp/apf/conf.apf_glob remote_src=yes dest=/etc/apf/conf.apf owner=root group=root mode=660 backup=yes’ Copy from target to target
Ansible all -m fetch -a ‘src=/etc/httpd/conf/httpd.conf  dest=/backup/httd” Fetch files from the remote server to the master server.
Ansible all -m file -a ‘path=/etc/httpd/ssl state=directory”

 

Or

Ansible all -m file -a ‘path=/etc/httpd/ssl/wings.key state=touch”

Or

Ansible all -m file -a ‘path=/etc/httpd/ssl/wings.key mode=777”

 

Or

 

Ansible all -m file -a ‘path=/etc/httpd/ssl/wings.key state=absent”

 

Create a file or folder using the file module.

Or

Create file.

 

 

 

 

 

 

Or

 

Change file or folder permission.

 

 

Or

 

Delete the file or Folder.

Ansible group-name -a “sudo yum install httpd -y”

or

 

Ansible group-name -ba “yum install httpd -y”

or

Ansible group-name -b -m module-name  -a “pkg=httpd status=present”

 

eg:-

Ansible mail -b -m yum  -a “pkg=postfix status=present”

Install the package  using Ansible

-b = –become  sudo  and -a is an argument

 

(-a for argument and -m for the module)

when you use -m (module) syntax always into YAML language.

-m Yum -a “pkg=postfix status=present”
-m service -a “name=postfix status=started”
-m user -a “name=raj”
-m copy -a “src=main.cf  dest=/etc/postfix”

Ansible -i inventory all -m command  -a “service iptables stop ” –become –ask-become-pass Ansible groupname -m command -a “Linux_commad”
Eg: Ansible webservers -m command -a “mkdir /tmp/blackpost”
Ansible all -m ping Check connection with node
Ansible mail -m setup

Ansible mail -m setup

 -a “filter=*ipv4*”

Check all the information on the nodes.

 

Ansible-doc setup Ansible-doc module name to find information about the module
Ansible-playbook playbook-name.yml

Eg:-

Ansible-playbook info.yml

Run playbook using Ansible-playbook command

 

ansible-vault create Vault.yml Creating a new encrypted playbook
ansible-vault edit Vault.yml Edit the encrypted playbook
ansible-vault rekey Vault.yml To Change the password
ansible- vault encrypt target.yml To encrypt an existing playbook
ansible-vault decrypt target yml To Decrypt an encrypted playbook
ansible – playbook handlers yml –check

 

Dryrun:-Check whether the playbook is formatted Correctly

 

PlayBook:-

→ Playbooks in ansible are written in YAML format

→ It is human readable data Serialization Language. It is commonly used for Configuration files

→ Playbook is like a file where you write Codes consisting of Vars, tasks, handlers, files, templates, and roles.

→ Each Playbook is Composed of one or more modules in a list Module is a Collection of Configuration files.

→ Playbooks are divided into many Sections like –

Target Section: – Defines the host against which the playbooks task has to be executed

Variable Section – Define Variables.

Task Section:- List all modules that we need to run in order.

How to write YAML:-

 ansible, nearly every YAML file starts with a list.

 Each item in the list is a list of key-value pairs, commonly called a dictionary.

 All YAML files have to begin with “—” and end with “…”

 All members of list lines must begin with the Same indentation level starting with “-”.

for eg –
— # A list of Mail Servers:
– Postfix
– Exim
– Qmail
– PowerMta
– MailerQ
– GreenArrow

Variables:-

  • Ansible uses variables that are defined previously to enable more flexibility in playbooks and roles. They Can be used to loop through a set of given Values, access Various information like the hostname of a system, and replace Certain strings in templates with specific Values
  • Put the Variable Section above tasks so that we define it first & Use it later.

Handlers Section:-

A handler is exactly the same as a task, but it will run when Called by another task.
or
Handlers are just like regular tasks in an ansible playbook but are only run if the task Contains a notify directive and also indicates that it changed something.

DRYRUN:-

Check whether the playbook is formatted correctly.

ansible-playbook handlers yml –check

1 Info.yml — # node information playbook
– hosts: mail
user: ansible

   become: yes
   connection: ssh
   gather_facts: yes
2 Apache.yml — #install httpd on mail group
– name: Apache playbook
hosts: mail
user: ansible
become: yes
become_user: root
  tasks:
– name: ensure apache is at the latest version
yum:
name: httpd
state: latest
– name: ensure apache is running
service:
name: httpd
state: started
3 Var.yml — # node information playbook
– hosts: mail   user: ansible
   become: yes
   connection: ssh
   gather_facts: yesvars:
pkgname: postfix
task:
-name install packages using variable
     Action yum name= ‘{{pkgname }}’ state=installed
4 Handlers.yml — # MY PLAYBOOK FOR HANDLERS

hosts: demo
user: ansible
become: yes
connection: ssh

tasks:

–  name: install httpd server on centos
action: yum name=httpd state-installed
notify: restart httpd

handlers:
– name: restart httpd
action: service name=httpd         state=restarted

5 Loops.yml — # MY LOOPS PLAYBOOK

– hosts: demo
user: ansible
become: yes
connection: ssh

 tasks:
– name: add list of users in my nodes
user: name='{{userslist} }’ state-present
with_userslist:
– Anil
– jalela
– Nilax
– Arti

OR Install packages

– name: install and configure packages
hosts: “{{myHost}}”
remote_user: ec2-user
become: yes

vars_files:
– Maria_vars.yml

tasks:
– name: install packages
yum: name={{item}} state=installed
with_item
– bind-utils
– netcat
– fping
– nmap
– httpd

 

OR Loop like

– name: testing loops
hosts: testServer
remote_user: ec2-user
become: yes

tasks:
– name: looping over environment facts
debug
msg={{item.key}}={{item.value}}
with_dict: ansible_env

 – name: looping over files and then copy copy: src={{item}} dest=/tmp/loops with_fileglob: “/tmp/*.conf”

 – name: do until something
shell: echo hello
register: output
retries: 5
delay: 5
until: output.stdout.find(‘hello’) != -1

6 Condition.yml — # CONDITIONAL PLAYBOOK

-hosts: demo
user: ansible
become: yes
connection: ssh

tasks:
–          name: Install apache server for debian family
command: apt-get -y install apache2
when: ansible_os_family == “Debian”
–          name: install apache server for redhat family
command: yum -y install httpd
when: ansible_os_family =”Redhat”

7 Mariadb.yml

 

Ansible-playbook -i hosts Mariadb.yml

 

– name: install and configure mariadb
hosts: testServer
remote_user: ec2-user
become: yes

vars:
mysql_port: 3306

tasks:
– name: install mariadb
yum: name=mariadb-server state=latest

– name: create mysql configuration file
template: src=my.cnf.j2 dest=/etc/my.cnf
notify: restart mariadb

– name: create mariadb log file
file: path=/var/log/mysqld.log state=touch owner=mysql group=mysql mode=0775

– name: start mariadb service
service: name=mariadb state=started enabled=yes

handlers:
– name: restart mariadb
service: name=mariadb state-restarted
my.cnf.j2 template file look  like :-

#cat my.cnf.j2

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
port={{ mysql_port }}
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mariadb/mysqld.pid 

8 Mariadb.yml

With log path and port variable


– name: install and configure mariadb
hosts: testServer
remote_user: ec2-user
become: yesvars:
mysql_port: 3306
log_path: /var/log/
tasks:
– name: install mariadb
yum: name=mariadb-server state=latest
– name: create mysql configuration file
template: src=my.cnf.j2 dest=/etc/my.cnf
notify: restart mariadb
– name: create mariadb log file
file: path={{ log_path }}/mysqld.log state=touch  owner=mysql group=mysql mode=0775

– name: start mariadb service
service: name=mariadb state=started enabled=yes

handlers:
– name: restart mariadb
service: name=mariadb state-restarted

9 Mariadb.yml

With Maria_vars.yml

And define hostname in run time

 

Ansible-playbook -i hosts Mariadb.yml

–extra-vars “hosts= testServer”

– name: install and configure mariadb
hosts: “{{myHost}}”
remote_user: ec2-user
become: yes

vars_files:
– Maria_vars.yml

tasks:
– name: install mariadb
yum: name=mariadb-server state=latest

– name: create mysql configuration file
template: src=my.cnf.j2 dest=/etc/my.cnf
notify: restart mariadb

– name: create mariadb log file
file: path=/var/log/mysqld.log state=touch  owner=mysql group=mysql mode=0775

– name: start mariadb service
service: name=mariadb state=started enabled=yes

handlers:
– name: restart mariadb
service: name=mariadb state-restarted

Maria_vars.yml vars file look  like :-
#cat Maria_vars.yml


mysql_port: 3306
log_path: /var/log/

Var_cases.yml

 

Ansible-playbook -i hosts Var_cases.yml

 

–  name: testing variables
hosts: testServer
remote_user: ec2-usertasks:
– name: get date on the server
shell: date
register: output
– debug: msg=”the date is {{output.stdout}}”– debug: var ansible_distribution_version
name: group some machines together temporarily
group_by: key=rhel_{{ansible_distribution_version}}
register: group_result
– debug: var=group_result
Conditionals.yml

 

Ansible-playbook -i hosts Conditionals.yml

 


– name: testing conditionals
hosts: testServer
remote_user: ec2-user
become: yes 
vars:
unicorn: true
tasks:
– name: don’t install on debian machines
yum: name=httpd state=latest
when: (ansible_os_family==”RedHat” and ansible_distribution_major_version==”6″)
– name: are unicorns real or fake
shell: echo “unicorns are fake”
when: not unicorn
 

# – fail: msg=”unicorns require rainbow variable to be set”
#when: rainbow is undefined

– name: test to see if selinux is running
shell: getenforce
register: sestatus

– name: configure SELinux if not enforcing
seboolean: name=mysql_connect_any state=true persistent=yes when: sestatus.rc != 0

– name: checking systems
shell: cat /var/log/messages
register: log_output

– name: next task
shell: echo “systemd knows when we’re doing ansible stuff”
when: log_output.stdout.find(‘ansible’) != 0
register: shell_echo
– debug: var=shell_echo