Introduction to Ansible

Ansible kind of exploded into popularity almost immediately after its release in 2012, and has become a staple for network administrators. In today's article, we're just going to immediately dive in and give you a good idea of what Ansible does and how you can get the most out of it.

Ansible is an open source automation platform. What that means is that it lets you manage software installations, updates, configurations and tasks within your network environment. It's especially handy in situations where you need to carry out sequential operations. It's also comparably easy to use, when put against other similar solutions.

The good:

  • Low barrier for entry, and general ease of use.
  • Very helpful with scaling of homogenous environment.
  • Easy host management using Playbooks.
  • Very secure since it uses SSH to connect.
  • Allows sequential execution of scheduled tasks (ie, it won't start a new taks before finishing another one).
  • Easy to install and configure.

The bad:

  • SSH connections can get slow in scaled environments.
  • As the platform continues to develop, it sometimes breaks backwards compatability.
  • No GUI to manage playbooks

Ansible is free and open-source remote server manager available for Linux, Mac and BSD. There is also an enterprise version called Ansible Tower, which is a web based solution and makes everything even easier. However, we'll just stick to the free version for this article.

Installing Ansible is pretty simple. Using Ubuntu or Debian the command is easy:

# apt install ansible

If you're running CentOS or Fedora, you can use EPEL to install it using this:

# yum install epel-release -y ; yum install ansible -y

Once you have Ansible installed, you'll need to add your remote servers to its configuration file, located in /etc/ansible/hosts:

# vim /etc/ansible/hosts
[remote-hosts]
host1
host2
...
192.168.1.29

Then you'll need to add an open SSH key from your Ansible server to your remote servers (/root/.ssh/authorized_keys):

# ssh-keygen
# cat /etc/ansible/hosts | xargs -i ssh-copy-id {}

Afterwards, it's easy to check your connections through the ansible ping command, being sure to include the "all" tag to have go through every connected server :

# ansible -m ping all
host1 | success >> {
  "changed": false,
  "ping": "pong"
}
...
host2 | success >> {
  "changed": false,
  "ping": "pong"
}

The host file allows for a lot of flexibility in terms of how you manage servers, allowing you to group them, assig SSH ports and more. For instance, I have a setup with two backends running on Cent OS 7, a load balancer on Ubuntu and a database server also running on Ubuntu. So let's group them together with Ansible: 

 


# cat /etc/ansible/hosts
[backend]
backend-node-1
backend-node-2

[balancer]
balancer-0

[dbs]
mysql-server-0

[ubuntu-hosts]
balancer-0
mysql-server-0

[centos-hosts]
backend-node-1
backend-node-2

We can also use Ansible to add services. Let's add the "httpd" service to our backend:

# ansible backend -m service -a "name=httpd state=stopped"
backend-node-1 | success >> {
  "changed": true,
  "name": "httpd",
  "state": "stopped"
}
backend-node-2 | success >> {
  "changed": true,
  "name": "httpd",
  "state": "stopped"
}

But the real draw of using Ansible is their playbooks system. Like the sports reference of the name implies, a playbook is a set of instructions for Ansible to follow in sequential order. Playbooks are written in a script called YAML which is surprisingly intuitive to the point where you should be able to get used to it only after a few minutes of use. So writing and editing playbooks is relatively easy as well. 

Here, for instance, is what a playbook for installing NGinx will look like. First, we need to create a directory structure for the playbook:


# mkdir handlers 
# mkdir tasks
# mkdir templates
# mkdir vars

"Handlers" directory is used for processing periodical assignments, like restarting services and such. "Tasks" will have you executables. "Templates" will have your configuration templates, and "vars" are there to keep shared variables used by the playbook.

Now let's fill in our handler:
 

# vim handlers/main.yml
---
- name: restart nginx
service: name=nginx state=restarted enabled=yes

Finally, let's get Ansible installed:


# vim tasks/main.yml
---
- name: Install EPEL repo in CentOS
  yum: name=epel-release state=present
  when: ansible_os_family == "RedHat"

- name: Install nginx package
  apt: name=nginx state=present

- name: Create directory for configs
  file: dest=/srv/{{ s_name }} state=directory

- name: Copy virtualhost config
  template: src=default.conf dest=/etc/nginx/conf.d/{{ s_name }}.conf

- name: Copy index.html to directory
  template: src=index.html dest=/srv/{{ s_name}}/index.html
  notify: restart nginx

With this code, we're installing the EPEL repository fpr RHEL-based distros as this repo contains the nginx packet. The code installs the nginx packet, creates a /srv/[host name here without brackets] to store configurations that are then copied to it along with the indexing template. 

Template for virtual hosts will look like this:

# vim templates/default.conf
server {
listen 80;
server_name {{ s_name }};
root /srv/{{ s_name }};
location / { index index.html index.htm; }
}

This is the index file template:

# vim templates/index.html
My name is {{ s_name }}

You might've noticed that the brackets in that code designate variables where Ansible stores your server names, which are stored in the vars directory:

# vim vars/main.yml
---
s_name: "{{ ansible_fqdn }}"

For our example, the variable server_name will correspond the server name, and will show up when you run the hostname -f command on our remote server.

You might've also noticed lines that look like this in the tasks/main.yml file:

when: ansible_os_family == "RedHat"

Ansible can identify the running OS on the host, and uses that information to make decisions as to how to proceed with the install. For instance, we don't need to install the EPEL repository when putting NGinx on an Ubuntu platofrm, so some of these commands won't be executed for hosts that aren't RHEL-based.

All that's left is creating the actual playbook file:

# vim nginx-install.yml
---
- name: Install nginx on remote hosts
hosts: backend
roles:
- nginx

Now to run the playbook:

# ansible-playbook nginx-install.yml
...
PLAY RECAP ********************************************************************
backend-node-1 : ok=6 changed=5 unreachable=0 failed=0
backend-node-2 : ok=6 changed=5 unreachable=0 failed=0

Alright, let's check if our web-server works:

# curl backend-node-1
My name is backend-node-1
# curl backend-node-2
My name is backend-node-2

Hopefully, this guide gave you a good idea of how to setup Ansible. And if you got any questions, feel free to hit us up on Twitter and Facebook, and follow and like our pages to stay updated with releases and more articles!

Ansible itself is very modular, and you can check out what's available here: Modules by category.

And full documentation of Ansible and how to use it can be found here: Documentation.

-Until next time!

September 25 2017

Add or review comments

Please leave your comment

Existing comments

Comments 72


aparna
Hi A good explaination on Introduction to Ansible Just want to add one thing is a command to create roles ansible-galaxy init rolename It gives the default structure of role directory structure Thanks Cheers
Eugenio
Simple but right on the fly
buying cialis online reviews
Il Viagra Napoletano haurrehigh [url=https://biracialism.com/]Cialis[/url] Engeda Amoxicillin Treat Abcess Awagosoods <a href=https://biracialism.com/#>Cialis</a> noinly Fish
Twediab
Alternativas Del Viagra haurrehigh [url=https://xbuycheapcialiss.com/]cialis cheapest online prices[/url] Engeda Propecia Effects Testicular Pain
Lbgsesse
looking for secure website to purchase cheap viagra in the united states <a href="http://genqpviag.com/#">viagra free trial</a> viagra canadian generic [url=http://genqpviag.com/]how much do viagra cost[/url] ’
Jdbxsesse
buying inexpensive viagra <a href="http://llviabest.com/#">ordering viagra through paypal</a> best prices on viagra [url=http://llviabest.com/]generic viagra australia[/url] ’
Lbsxsesse
canadian drugs without prescription <a href="https://ssviagriia.com/ ">india generic viagra</a> drugs online
FvfcExole
where to buy viagra online <a href="http://hopeviagrin.com/ ">cheap viagra and cialis in australia</a> differences between viagra levitra and cialis
NncsExole
viagra super power <a href="http://lightvigra.com/ ">best prices on viagra</a> 4 pack viagra
Jbbvsesse
canadianpharmacy <a href="http://canadianpharmnorx.com/ ">mexican pharmacy online medications</a> online canadian pharmacies
Kbcxhifs
best online pharmacy stores <a href="http://xuypharmacyonline.com/">online pharmacy no prescription</a> quit smoking
Ahkdsesse
canada pharmacies prescription drugs <a href="http://storerxpharmcanada.com/ ">erectile dysfunction pills</a> drugstore online
JbnbUript
canada prescription plus pharmacy <a href="http://online21rxon.com/ ">online medicine tablets shopping</a> viagra generic online pharmacy
Labxsesse
can i purchase cialis online <a href="https://jecialisbn.com/ ">effects of cialis and grapefruit</a> cialis viagra jokes
FbsgExole
cialis price at walmart <a href="http://llecialisjaw.com/ ">http://llecialisjaw.com/ </a> buying cialis in australia
NbnhExole
buy sildenafil 100mg uk <a href="https://vigedon.com/ ">viagra usa pharmacy </a> where to buy viagra
Kvaxhifs
security bank cash loan requirements <a href="http://rirocash.com/ ">payday loans in lebanon tennessee</a> payday loans with just a prepaid debit card
Jbbnsesse
comparar cialis e viagra <a href="http://ljcialishe.com/ ">cialis junge männer</a> cialis levitra viagra diferencias
JbnvUript
bad credit payday loans guaranteed approval no teletrack <a href="http://samcash21.com/ ">cash advance fee uob</a> ridgecrest ca cash advance
Ahbzsesse
loans for cash now <a href="http://daymoneygo.com/ ">payday loans ontario child tax credit</a> payday loans san clemente ca
Fqbbsesse
fast payday loans australia <a href="http://ascashapply.com/ ">the cash store loan insurance</a> payday loans se portland or
AbcfHemyinend
sun viking viagra <a href="http://viagriyvik.com/ ">paying for viagra with paypal </a> wild viagra uk
FjjuExole
viagra headache <a href="https://viagraonlinejc.com/ ">http://viagraonlinejc.com/ </a> does viagra make you last longer
NbmoExole
overnight cialisis on line <a href="http://buycialisxz.com/ ">http://buycialisxz.com/ </a> free samples cialis
Lmoppsesse
[url=http://essaywriteris.com/]fake essay writer[/url] best writing paper <a href="http://essaywriteris.com/ ">write my social work essay</a> cheap essay writer
Twediab
[url=http://vsdoxycyclinev.com/]buy vibramycin doxycycline new zealand[/url]
Brfghifs
[url=https://ljcialishe.com/]can i take 40mg of cialis[/url] [url=https://cialisvja.com/]cialis amazon[/url] [url=https://viagraonlinejc.com/]viagra vs cialis forum[/url] [url=https://viagratx.com/]viagra dosages[/url] [url=https://buycialisxz.com/]does cialis make you last longer[/url]
Fbsfsesse
online pharmacy no prescription http://uspharmus.com/ Cialis Soft Tabs
Jbsdsesse
Nolvadex http://onlinecanda21.com/ pharmacies near me
Bbdfhifs
best viagra alternatives [url=https://gensitecil.com/ ]buy viagra online without prescription[/url] can you snort viagra
Lrbssesse
viagra cialis levitra online pharmacy [url=http://uslevitraanna.com/ ]levitra prix[/url] levitra free samples
LhdvExole
cialis and viagra mix http://asciled.com/ where can i buy cialis online
GvdbUript
tadalafil benefits [url=https://boxtadafil.com/ ]cheapest tadalafil 32[/url] sildalis sildenafil tadalafil
Abdgsesse
canada pharmacies http://canadianeve21.com/ Luvox
Fbsfsesse
online pharmacy reviews [url=http://uspharmus.com/ ]online pharmacy without a prescription[/url] canadian prescription drugs
Twediab
<a href=http://ponlinecialisk.com/>brand cialis online[/url]
Jbsdsesse
rx pharmacy [url=http://onlinecanda21.com/ ]pharmacy prices compare[/url] canada pharma limited llc
Fmrfsesse
cialis & viagra https://cialisee.com/ professional cialis
GtnbUript
vietnamese viagra http://jokviagra.com/ female viagra porn
Lebnsesse
Apcalis SX https://xlnpharmacy.com/ Remeron
LbsoExole
cialis no prescrition https://ucialisdas.com/ generic cialis forums
Anoosesse
mejor web para comprar viagra http://llviagra.com/ best alternative to viagra
Fmrfsesse
generic cialis 40mg http://cialisee.com/ generis cialis online overnight delivery
RebfExole
cialis dosage for women https://rcialisgl.com/ cialis paypal pay with
Bbshhifs
get viagra prescribed online http://loxviagra.com/ does viagra make your penis bigger
Jebgsesse
online pharmacy reviews [url=http://pharmacylo.com/ ]24 hr pharmacy near me[/url] online pharmacy dubai
LbsoExole
buy cialis canada paypal http://ucialisdas.com/ cialis none prescription
Anoosesse
temp effet du viagra https://llviagra.com/ en que te ayuda el viagra
Lebnsesse
canadapharmacyonline https://xlnpharmacy.com/ pharmacy technician classes online free
Fmrfsesse
cialis цена http://cialisee.com/ on line cialis
Jebgsesse
24 hour drug store http://pharmacylo.com/ Atacand
RebfExole
cialis or viagra [url=http://rcialisgl.com/ ]generic cialis express delivery[/url] purchase cialis
Lebnsesse
canadian pharmacy india http://xlnpharmacy.com/ Lanoxin
LbsoExole
cheap cialis online [url=https://ucialisdas.com/ ]overnight cialisis on line[/url] cialis 36 hour
Fmrfsesse
cialis generic http://cialisee.com/ cialis without prescriptions
GtnbUript
walgreen viagra [url=https://jokviagra.com/ ]viagra for womens where to buy[/url] viagra india
Jebgsesse
Caverta [url=https://pharmacylo.com/ ]legal online pharmacies in the us[/url] dysfunction
RebfExole
indian cialis https://rcialisgl.com/ indian cialis
Uphorry
<a href=https://vslevitrav.com/>levitra without a script[/url]
sesseHtf
can i buy cialis over the counter at walgreens [url=https://cialishav.com/ ]buy cialis fast shipping[/url] black tab cialis
sesseGtv
Verapamil [url=https://pharmacyhrn.com/ ]best online pharmacies canada[/url] legal canadian prescription drugs online
hifsSwa
cialis paypal viagra [url=https://ckacialis.com/ ]cheap cialis generic online[/url] cialis available in walgreens over counter??
Exoleloh
how long does it take for cialis to work? [url=https://rcialisgl.com/ ]where can i buy cialis 20mg[/url] where is cialis manufactured
UriptAsd
cialis at costco [url=https://cialisjla.com/ ]buy cialis 36 hour[/url] how to cut 20mg. cialis
sesseDev
online course for pharmacy technician [url=https://cjepharmacy.com/ ]kamagra oral jelly[/url] reputable indian online pharmacy
sesseHtf
cialis 2.5mg online [url=https://cialishav.com/ ]cialis coupons[/url] buying cialis in south africa
UriptAsd
cialis no prescription [url=https://cialisjla.com/ ]cheapest generic cialis online[/url] buy cialis
sesseAni
schnucks pharmacy buttler hill rd store hours [url=https://pharmacyken.com/ ]pharmacy tech practice tests online free[/url] online pharmacy reviews
Uphorry
<a href=https://sscialisvv.com>cialis and viagra sales[/url]
sesseAni
online pharmacy mexico [url=https://pharmacyken.com/ ]online pharmacy valium[/url] ritalin canadian pharmacy
Uphorry
<a href=http://priligyset.com>dapoxetine 30 mg[/url]
Uphorry
<a href=https://vslevitrav.com/>order on line levitra</a>