Ansible Tutorial

Spread the love

Ansible doesnot require any agent software to be installed on our machine.
Instead it uses passwordless ssh.
Note:Ansible uses agentless policy

1 Generate ssh keys on the controller machine
ssh -keygen

2 Copy the public key into the all the managed hosts
ssh-copy-id username@ip-adress-of-managed-host

3 Repeat Step No 2 for all the managed hosts

Ansible performs remote configuration by reading information
from a file called inventory file.The default inventory file is
present in /etc/ansible/hosts.
In this file we should define the ip adress of all the managed hosts that we want ansible to control

sudo vim /etc/ansible/hosts
Go into insert mode by pressing i
Enter the ip adresses of all the managed hosts
Save and quit(Esc :wq)

Ansible uses the following thre modes for remote configuration

1  Ansible adhoc commands
2  Ansible playbooks
3  Ansible roles

Impotant modules in ansible

1  command : This is used for executing basic linux commands on the remote machines
2  shell: This is used for executing linux commands which involve
redirection and piping
3  ping: Used to check if a remote manged host is pingable or not
4  copy: Used to copy files from controller into managed hosts
5  fetch: Used to copy files from managed hosts into controller
6  user: Used for creating users on the managed hosts and for
controlling their accounts
7  file: Used for creating files and directories on the managed
8  git: Used to automate the checkin and checkout process in
git version controlling
9  apt: Used for installing packages on the ubuntu based linux machines
10  yum:Used for installing packages in rhel,oel,centos,fedora
11  servcie: Used for starting or stopping services
12  uri : used to check if a remote url is reachable or not
13  debug :Used to capture the output of any specific ansible
module and display it on the console
14  ec2: Used for configuring servers on the AWS cloud

Adhoc commands

ansible all/group/ipadress -m modulename -a ‘arguments’


Execute ls -l command on all the manged hosts
ansible all -m command -a ‘ls -l’


Excecute ls -l command on all the managed nodes and store the output in file1
ansible all -m shell -a ‘ls -l > file1’ -b


Go to all the manged hosts and capture info about all the users who are using /bin/bash from /etc/passwd file and store in file2
ansible all -m shell -a ‘grep /bin/bash /etc/passwd > file2’ -b


Copy a file present on the controller into all the managed hosts
ansible all -m copy -a ‘src=ansbilesample dest=/home/vagrant’
We can also copy directories along with all its subdirectories
and files
ansible all -m copy -a ‘src=d1 dest=/home/vagrant’ -b

Copy module can also be used for changing the ownership,group ownership and permissions on
the file that is copied into the managed nodes

ansible all -m copy -a ‘src=file1 dest=/home/vagrant owner=root
group=root mode=777′ -b

We can also copy content into a file using copy module
ansible all -m copy -a ‘content=”Hello cloud \n” dest=/home/vagrant/myinventory’


This is used for creating files or directories on the managed nodes.We can also change the ownership,
group ownership and permission of the files created on the managed nodes

To create a file we can use state=touch

Ansible to create a file called ansiblefile on all the managed hosts
ansible all -m file -a ‘name=ansiblefile dest=/home/vagrant state=touch’ -b

To create a directory we can use state=directory

Ansible command to create a directory on all the manage hosts
ansible all -m file -a ‘name=ansdir dest=/home/vagrant state=directory’ -b

We can also create complete folder structure on the managed hosts
ansible all -m file -a ‘name=d1/d2/d3/d4/d5 dest=/home/vagrant state=directory’ -b

To control the ownership and group ownership and also the permissions on that file
ansible all -m file -a ‘name=ansiblefile dest=/home/vagrant state=touch owner=vagrant group=ansible mode=000’ -b

To recursively change the ownership groupownership and permissions from d3 folder to all its subfolders and files
ansible all -m file -a ‘name=d1/d2/d3 dest=/home/vagrant state=directory owner=ansible group=ansible mode=777 recurse=yes’ -b

APT Module

This is used for installaing or unistalling packages on the managed hosts

Ansible command to install tree on all manged hosts after
upgrading the apt repository
ansible all -m apt -a ‘name=tree state=present update_cache=yes’ -b

Ansible commna dto install apache2 on one machine
ansible -m apt -a ‘name=apache2 state=present’ -b

Configuring ansible on AWS

1 Create 2 or more aws instances(Ubuntu14)
2 Name the 1st instance as controller
and other instances as server1,2,3,etc
3 Open the terminal of controller machine through git
4 Install ansible
5 Create a user called ansible
sudo useradd -m ansible
6 Assign password for that user
sudo passwd ansible

7 Open another gitbash and go to server1
8 sudo vim /etc/ssh/sshd_config
Search for passwordauthentication and
change it from no to yes
9 Restart ssh service
sudo service ssh restart
10 Reset passwd for ubuntu user
sudo passwd ubuntu

Repeat Step-7-10 on all the managed hosts

11 Go to controller machine
13 sudo vim /etc/ansible/hosts
Enter tie private ips of all the managed hosts

14 sudo su – ansible
15 ssh-keygen
16 ssh-copy-id ubuntu@private-ip-of-mangedhost
Repeat step 16 for all manged host ip adresses


The adhoc commands that we have used till now can work only on one module and one set of arguments.

To perform complex configuration management activites we can use ansible playbooks
Playbooks are created in yml syntax and they are useful for running multiple ansible modules
with different set of arguments

Using playbooks it is possible to convert complex CM tasks into easily repetable routines

Create an ansible playbook for crearing directory on all the manged hosts and copying a file into that directoy

vim playbook1.yml
Go into insert mode by pressing i

– name: Creating dirs and coping files
hosts: all
– name: create directory
name: /home/ubuntu/dir1
state: directory
– name: copy file
src: /home/ansible/file1
dest: /home/ubuntu/dir1

Save and quit (Esc :wq)

2.To check the syntax of the above playbook
ansible-playbook playbook1.yml –syntax-check

To run the above playbook
ansible-playbook playbook1.yml

Create an ansible playbook for creating a user
called cloud on all the manged hosts and capture the user info from /etc/passwd file

vim playbook2.yml
Go into insertmode by pressing ‘i’

– name: Creating users and capturing their info
hosts: all
– name: User Creation
name: cloud
password: mypassword
home: /home/ansible
shell: /bin/bash
– name: Capture cloud info from /etc/passwd
shell: grep cloud /etc/passwd > file1
– name: Fetching cloud into controller
src: /home/ubuntu/file1
dest: /home/ansible


1 Install apache2 on one managed host
2 Edit the content of index.html file
3 Restart apache2
4 Check whether url is responding or not

vim playbook3.yml
Go into insert mode by pressing ‘i’

– name: Configuring apache2
become: yes
– name: Installing apache2
name: apache2
state: present
– name: Edit index.html file
content: “Hi This is the home page of cloud”
dest: /var/www/html/index.html
– name: Restart apache2
name: apache2
state: restarted
– name: Checking url response
status: 200

Create a playbook for copying file from one managed host
to another managed host

– hosts:
– name: Fetch file from 1st managed node
src: /home/vagrant/file1
dest: /home/vagrant
– hosts:
– name: Sending file from controller to managenode2
src: /home/vagrant/
dest: /home/vagrant

1 Install git on all managed hosts
2 Create a new directory on all the managed hosts
3 Clone a git rpository into that directory

vim playbook5.yml
Go into isnert mode by pressing ‘i’

– name: Working on Git
hosts: all
– name: Installing git
name: git
state: present
update_cache: yes
– name: Creating a directory
name: /home/vagrant/git_folder
state: directory
– name: Cloning Git repo
dest: /home/vagrant/git_folder
clone: yes

Variables in Ansible

These are classified into 3 types
1 Global Scope
2 Play Scope
3 HostScope

Global Scope are declared at the command prompt and they
can effect all the plays in the complete playbook

PlayScope variables are declared at the level of individual
plays and they will work on only a single play

Host Scope variables defined to work on a group of hosts
or on a single host as given in the inventory file

Global Scope variables


Create a playbook which can be used for installing or
unistalling paakcges
vim playbooks6.yml
Go into insert mode by pressing ‘i’

– name: Installing or uninstalling packages
hosts: all
– name: Installing/uninstalling
name: “{{a}}”
state: “{{b}}”
update_cache: “{{c}}”

Save and quit(Esc :wq)

To run the above playbook for installing tree
ansible-playbook playbook6.yml –extra-vars “a=tree b=present c=no” -b

We can also use it for uninstalling git
ansible-playbook playbook6.yml –extra-vars “a=git b=absent c=yes” -b


Create a playbook for creating directories or file and also controlling the ownership permissions etc

vim playbook7.yml
Go into insert mode by pressing ‘i’

– name: Creating files/directories changing perm etc
hosts: all
– name: create file/dir
name: “{{a}}”
state: “{{b}}”
owner: “{{c}}”
group: “{{d}}”
mode: “{{e}}”

Save and quit (Esc :wq)

To create a directory with the above play book
ansible-playbook playbook7.yml –extra-vars “a=/home/vagrant/d1 b=directory c=cloud d=root e=777” -b

to create a file using the same playbook
ansible-playbook playbook7.yml –extra-vars “a=/home/vagrant/d1/file1 b=touch c=vagrant d=cloud e=000” -b

Playscope variable


Create a playbook for installing apache2 using playscope
varaible.The same playbook should be capable of working
on installation or uinstallation of other packages

vim playbokk8.yml
Go into insert mode by pressing ‘i’

– name: Installing apahce2
hosts: all
a: apache2
b: present
c: no
– name: Apache installation
name: “{{a}}”
state: “{{b}}”
update_cache: “{{c}}”

Save and quit(Esc :wq)

To run tha above playbook
ansible-playbook playbook8.yml -b
It will install apache2

The above playbook works as a template whose default behaviour is installing apache but we can make the same playbook to install any oher package instead of apache2
by passing the values as global scope

ansible-playbook playbook8.yml –extra-vars “a=git b=absent c=no” -b

Order of presendence

Global scope variables are given the higgest priority
Host Scope variables have next level of priority
Play scope variables are given the least priority

You can also use keyword become on a particular task instead of the whole play:

– hosts: webservers
remote_user: yourname
– service:
name: nginx
state: started
become: yes
become_method: sudo

You can also login as you, and then become a user different than root:

– hosts: webservers
remote_user: yourname
become: yes
become_user: postgres

You can also use other privilege escalation methods, like su:

– hosts: webservers
remote_user: yourname
become: yes
become_method: su

Sample Playbook:

– hosts: webservers
remote_user: root

– name: ensure apache is at the latest version
name: httpd
state: latest
– name: write the apache config file
src: /srv/httpd.j2
dest: /etc/httpd.conf

– hosts: databases
remote_user: root

– name: ensure postgresql is at the latest version
name: postgresql
state: latest
– name: ensure that postgresql is started
name: postgresql
state: started

ansible playbook for ngnix:

– name: This sets up nginx webserver
hosts: db
remote_user: ubuntu
become: yes
become_method: sudo
– name: Install ngix packages
name: nginx
state: present
– name: ensure nginx is running
name: nginx
state: started

Create multiple directories. To create multiple directories with one single task you can use the loop with_items statement. So when you run the below playbook it is interpreted as 3 different tasks.

– hosts: webservers
become: true
– name: Create multiple directories
file: path={{item}} state=directory
– ‘/home/ansible/vn1’
– ‘/home/ansible/vn2’
– ‘/home/ansible/vn3’

Create the file on the target machines or servers as mentioned in the inventory file and the webserver’s group, save the below code with
.yml extension and run the playbook.

– hosts: webservers
become: true
– name: Create a file
file: path=/home/ansible/cloudsoft.txt state=touch

install jdk by ansible playbooks

– hosts: webservers
become: true

– name: Download JDK 8 RPM file
command: “wget –no-check-certificate –no-cookies –header ‘Cookie: oraclelicense=accept-securebackup-cookie’ {{download_url}} “
– name: Install JDK 8
command: “rpm -ivh jdk-8u171-linux-x64.rpm”

If we want to execute any module only if a previous modules is executed successfully and also it has done some changes we can use handlers

Handlers are used in combination with “notify” keyword
A successfull module sends its result to notify and based on that the handler gets execute

Handlers are given in allignment with the tasks

Handlers are executed only after all the tasks are execute

If multiple modules call the same handlers multiple time
the handler will be executed only once

The handlers are executed only in the order that they are given in the handlers section and not in the order that they are called in the tasks section

Install apache2
Edit index.html file
If edit is successfull ie (done some changes) restart apache2

vim playbook23.yml

Ansible Vault :

Most of the times when sensitive or confidential data need to be protected in the playbook, then it can be encrypted rather than just keeping it in a text file which is readable by all. Ansible Vault allows you to encrypt the playbook to protect the confidential data.

For Example, consider the following task where a confidential job agreement is being copied.

In such cases, you would need an Ansible Vault.

Following are the steps that you need follow to encrypt the above playbook files.

#1) Creating new encrypted files

To create new encrypted files with vault use the ansible-vault create command.
$ ansible-vault create jobagreement.yml

After confirming password an editing window will open to add contents to the file.
Ansible will encrypt the contents when you close the file. Instead of seeing the actual contents you will see encrypted blocks.

#2) To encrypt an existing yml file use the following

$ ansible-vault encrypt existingfile.yml

Password will again be asked for encryption.

#3) Viewing encrypted file

Use the command ansible-vault view to look at the actual contents of the file.

$ ansible-vault view jobagreement.yml

You will be asked for the password again to look at the contents of the file.

#4) Editing encrypted files

If you need to edit the file use the command ansible-vault edit

$ ansible-vault edit users.yml

Enter the password to edit the file.

#5) Changing password of the encrypted files

Use the command ansible-vault rekey to change the password of the file.                                          $ ansible-vault rekey jobagreement.yml

#6) Run an encrypted Ansible playbook file

Use the option –ask-vault-pass with the ansible-playbook command.
$ ansible-playbook users.yml –ask-vault-pass

#7) Manually decrypting the encrypted files

Use the command ansible-vault decrypt command.
$ ansible-vault decrypt jobagreement.yml

Leave a Reply

Your email address will not be published. Required fields are marked *