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

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





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
- 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

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
Simple but right on the fly
buying cialis online reviews
Il Viagra Napoletano haurrehigh [url=]Cialis[/url] Engeda Amoxicillin Treat Abcess Awagosoods <a href=>Cialis</a> noinly Fish
Alternativas Del Viagra haurrehigh [url=]cialis cheapest online prices[/url] Engeda Propecia Effects Testicular Pain
looking for secure website to purchase cheap viagra in the united states <a href="">viagra free trial</a> viagra canadian generic [url=]how much do viagra cost[/url] ’
buying inexpensive viagra <a href="">ordering viagra through paypal</a> best prices on viagra [url=]generic viagra australia[/url] ’
canadian drugs without prescription <a href=" ">india generic viagra</a> drugs online
where to buy viagra online <a href=" ">cheap viagra and cialis in australia</a> differences between viagra levitra and cialis
viagra super power <a href=" ">best prices on viagra</a> 4 pack viagra
canadianpharmacy <a href=" ">mexican pharmacy online medications</a> online canadian pharmacies
best online pharmacy stores <a href="">online pharmacy no prescription</a> quit smoking
canada pharmacies prescription drugs <a href=" ">erectile dysfunction pills</a> drugstore online
canada prescription plus pharmacy <a href=" ">online medicine tablets shopping</a> viagra generic online pharmacy
can i purchase cialis online <a href=" ">effects of cialis and grapefruit</a> cialis viagra jokes
cialis price at walmart <a href=" "> </a> buying cialis in australia
buy sildenafil 100mg uk <a href=" ">viagra usa pharmacy </a> where to buy viagra
security bank cash loan requirements <a href=" ">payday loans in lebanon tennessee</a> payday loans with just a prepaid debit card
comparar cialis e viagra <a href=" ">cialis junge männer</a> cialis levitra viagra diferencias
bad credit payday loans guaranteed approval no teletrack <a href=" ">cash advance fee uob</a> ridgecrest ca cash advance
loans for cash now <a href=" ">payday loans ontario child tax credit</a> payday loans san clemente ca
fast payday loans australia <a href=" ">the cash store loan insurance</a> payday loans se portland or
sun viking viagra <a href=" ">paying for viagra with paypal </a> wild viagra uk
viagra headache <a href=" "> </a> does viagra make you last longer
overnight cialisis on line <a href=" "> </a> free samples cialis
[url=]fake essay writer[/url] best writing paper <a href=" ">write my social work essay</a> cheap essay writer
[url=]buy vibramycin doxycycline new zealand[/url]
[url=]can i take 40mg of cialis[/url] [url=]cialis amazon[/url] [url=]viagra vs cialis forum[/url] [url=]viagra dosages[/url] [url=]does cialis make you last longer[/url]
online pharmacy no prescription Cialis Soft Tabs
Nolvadex pharmacies near me
best viagra alternatives [url= ]buy viagra online without prescription[/url] can you snort viagra
viagra cialis levitra online pharmacy [url= ]levitra prix[/url] levitra free samples
cialis and viagra mix where can i buy cialis online
tadalafil benefits [url= ]cheapest tadalafil 32[/url] sildalis sildenafil tadalafil
canada pharmacies Luvox
online pharmacy reviews [url= ]online pharmacy without a prescription[/url] canadian prescription drugs
<a href=>brand cialis online[/url]
rx pharmacy [url= ]pharmacy prices compare[/url] canada pharma limited llc
cialis & viagra professional cialis
vietnamese viagra female viagra porn
Apcalis SX Remeron
cialis no prescrition generic cialis forums
mejor web para comprar viagra best alternative to viagra
generic cialis 40mg generis cialis online overnight delivery
cialis dosage for women cialis paypal pay with
get viagra prescribed online does viagra make your penis bigger
online pharmacy reviews [url= ]24 hr pharmacy near me[/url] online pharmacy dubai
buy cialis canada paypal cialis none prescription
temp effet du viagra en que te ayuda el viagra
canadapharmacyonline pharmacy technician classes online free
cialis цена on line cialis
24 hour drug store Atacand
cialis or viagra [url= ]generic cialis express delivery[/url] purchase cialis
canadian pharmacy india Lanoxin
cheap cialis online [url= ]overnight cialisis on line[/url] cialis 36 hour
cialis generic cialis without prescriptions
walgreen viagra [url= ]viagra for womens where to buy[/url] viagra india
Caverta [url= ]legal online pharmacies in the us[/url] dysfunction
indian cialis indian cialis
<a href=>levitra without a script[/url]
can i buy cialis over the counter at walgreens [url= ]buy cialis fast shipping[/url] black tab cialis
Verapamil [url= ]best online pharmacies canada[/url] legal canadian prescription drugs online
cialis paypal viagra [url= ]cheap cialis generic online[/url] cialis available in walgreens over counter??
how long does it take for cialis to work? [url= ]where can i buy cialis 20mg[/url] where is cialis manufactured
cialis at costco [url= ]buy cialis 36 hour[/url] how to cut 20mg. cialis
online course for pharmacy technician [url= ]kamagra oral jelly[/url] reputable indian online pharmacy
cialis 2.5mg online [url= ]cialis coupons[/url] buying cialis in south africa
cialis no prescription [url= ]cheapest generic cialis online[/url] buy cialis
schnucks pharmacy buttler hill rd store hours [url= ]pharmacy tech practice tests online free[/url] online pharmacy reviews
<a href=>cialis and viagra sales[/url]
online pharmacy mexico [url= ]online pharmacy valium[/url] ritalin canadian pharmacy
<a href=>dapoxetine 30 mg[/url]
<a href=>order on line levitra</a>