Going Deeper into Ansible Playbooks

In a previous blogpost, we introduced some basic Ansible fundamentals, installation procedures, and a guide to ad-hoc mode.
Ansible can be used in either Ad-Hoc or Playbook mode. As covered in our previous post, ad-hoc mode allows direct management of your hosts by executing single line commands and leveraging Ansible modules. Ad-hoc mode is useful when you plan to perform a quick and simple activity like shutting down your hosts or checking connectivity between your Ansible server and hosts using ping. But when you plan to manage host configurations and deployments, Ansible playbooks become more attractive.
According to Ansible documentation, “Playbooks are Ansible’s configuration, deployment, and orchestration language. They can describe a policy you want your remote systems to enforce, or a set of steps in a general IT process.”
Playbooks are written in human readable YAML format and can be created either by placing everything in a single file or by following a structure model. Each Ansible playbook contains one or more plays to help you to perfor functions on different hosts. The goal of a play is to map roles to hosts and perform tasks under a role on different hosts. Tasks are nothing but modules called on hosts.

learning-cloud-computing
Keep it Simple

Ansible Playbook Structure

Here is sample Ansible playbook:

---
- hosts: webservers
vars:
   http_port: 80
   max_clients: 200
remote_user: root
tasks:
- name: ensure apache is at the latest version
   yum: pkg=httpd state=latest
- name: write the apache config file
   template: src=/srv/httpd.j2 dest=/etc/httpd.conf
   notify:
   - restart apache
- name: ensure apache is running
   service: name=httpd state=started
handlers:
   - name: restart apache
     service: name=httpd state=restarted in more than one way. You

In the above Ansible playbook, we created an entire configuration as one single file. This is fine if you’re writing a playbook for a simple deployment or configuration. However, once you decide to implement complex deployment scenarios, it is better to use a structured model, adding re-usability.
The structure of an Ansible playbook:

site.yml
hosts
group_vars/
      group1
      group2
host_vars/
      hostname1
      hostname2
roles/
      common/
            files/
            templates/
            tasks/
            handlers/
            vars/
            defaults/
            meta/
      webservers/
            …
            …
      applicationservers/
            …
            …
      databaseservers/
            …
            …

Let’s analyze this structure.

  • site.yml – site.yml is our master YAML playbook file. It contains information about rest of the playbook.
  • Hosts

Ansible contains information about the hosts and groups of hosts to be managed in the hosts file. This is also called an inventory file. One can also divide hosts files into files with different environment names, i..e, instead of “hosts”, you can create two different files called “production” and “staging”. Apart from mentioning hosts and group of hosts information, you can also include host-specific information (ssh port, db parameters etc) in a hosts file.

Here is a sample hosts file:

[webservers]
prod-web01.example.com
prod-web02.example.com
[databaseservers]
prod-db01.example.com
prod-db02.example.com
  • group_vars and hosts_vars

Like the hosts inventory file, you can also include hosts and groups of hosts configuration variables in a separate configuration folder like group_vars and hosts_vars. These can include configuration parameters, whether on the application or operating system level, which may not be valid for all groups or hosts. This is where having multiple files can be useful: inside group_vars or hosts_vars, you can create a group or host in more than one way, allowing you to define specific configuration parameters.

A sample group_vars configuration:

---
# file: group_vars/webservers
apacheMaxRequestsPerChild: 3000
apacheMaxClients: 900

If you look at above configuration, the apacheMaxRequestsPerChild or apacheMaxClients configuration parameters are only valid for the webservers hosts group. They don’t apply to the database or application hosts group.

If there is some configuration which you want to apply to all groups, this can be easily done:

---
# file: group_vars/all
ntp: ntp-boston.example.com
backup: backup-boston.example.com
  • Roles

As you add more and more functionality to your Ansible playbooks, it becomes difficult to manage it as a single file. Roles allow you to prepare a minimal Ansible playbook the defines how a server is supposed to perform rather than specifying the steps to get a server to act in a specific way.

According to Ansible documentation, “Roles in Ansible build on the idea of include files and combine them to form clean, reusable abstractions – they allow you to focus more on the big picture and only dive down into the details when needed.”

To correctly use roles with Ansible, you need to create a roles directory in your working Ansible directory, and then any necessary sub-directories.

The Ansible roles structure:

roles
|__ defaults
        |__ main.yml
|__ files
|__ templates
|__ tasks
        |__ main.yml
|__ meta
        |__ main.yml
|__ vars
        |__ main.yml
|__ handlers
        |__ main.yml

There are two ways to build the roles directory format, manually or by using Ansible-Galaxy. Ansible galaxy is free site for finding, reusing and sharing community developed roles. To create a role using ansible galaxy, use the ansible-galaxy command :

# ansible-galaxy init webservers

 To understand more about roles, it is important to understand the roles directory structure.

  • Defaults – In the defaults directory, we need to have a file called main.yml which includes information about default variables used by this role. For example, this can be a default directory to deploy your configuration or to set up a default port for your application etc.
---
webservers_dir: /var/www/html
webservers_port: 80
  • Files – the files directory contains files which need to be deployed to your hosts without any modification. These are simply copied over to your hosts. This could be your web application source code or some scripts.
  • Templates – templates are like files, but allow modification. You can pass configuration variables to templates and those modified templates will be placed on your hosts. Ansible allows you to reference variables in your playbooks using the Jinja2 templating system.

 Sample template definition :

template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  • Tasks – Each play can contain multiple tasks and each task can perform a variety of actions. Tasks basically execute modules with specific arguments. These arguments can be variables defined above. Along with modules, tasks also reference files and templates from other directories without providing a complete path. Tasks are executed in order against all hosts matching a particular host pattern. Tasks are written in main.yml or in other .yml files in same directory that are referenced by main.yml.

 Sample task definition:

---
# These tasks install http and the php modules.
- name: Install http and php etc
yum: name={{ item }} state=present
with_items:
- httpd
- php
- php-mysql
- git
- libsemanage-python
- libselinux-python
  • Meta – meta contains files that describe environment (operating system, version etc), author, and licensing attributes, and establishes role dependencies. If a role written above depends upon some other role, those dependencies are resolved under meta section (main.yml).

 Sample meta definition:

---
dependencies:
- { role: apt }
  • Vars – vars is identical to defaults, i.e., it is used to store variables in a YAML file. However, variables defined under vars have higher priority than variables defined under defaults. These defined variables are found in configuration files for tasks, templates and others.
  • Handlers – If you refer to the above sample playbook, you’ll find a “notify” section under tasks. Notify definitions point to handlers. Handlers are also tasks which run only under particular events, and are executed only if notified by multiple tasks or state changes. For example, “if a new application code is deployed on hosts, then restart Apache. If not, don’t restart Apache.”

 Sample handlers definition:

---
# file: roles/common/handlers/main.yml
- name: restart ntpd
service: name=ntpd state=restarted

Executing Ansible Playbook

To execute an Ansible playbook, you use the ansible-playbook command.

# ansible-playbook -i hosts site.yml

If you have a different Ansible inventory file for production and staging, you can execute a playbook on a production environment by referencing the production inventory file.

# ansible-playbook –i production site.yml

 

Written by

Head of Managed Services at REAN Cloud. Before joining REAN Cloud, I was CEO and Founder of StraightArc Solutions which was later acquired by REAN Cloud.I started my career working on cloud computing. Loves to talk about DevOps, System Administration, Scalability, High Availability, Disaster Recovery and Cloud Security. Apart from work, I love to meet people, travel and watch sports.

Related Posts

Albert Qian
— August 28, 2018

Introducing Assessment Cycles

Today, cloud technology platforms and best practices around them move faster than ever, resulting in a paradigm shift for how organizations onboard and train their employees. While assessing employee skills on an annual basis might have sufficed a decade ago, the reality is that organiz...

Read more
  • Cloud Computing
  • Product Feature
  • Skill Profiles
— July 31, 2018

Cloud Skills: Transforming Your Teams with Technology and Data

How building Cloud Academy helped us understand the challenges of transforming large teams, and how data and planning can help with your cloud transformation.When we started Cloud Academy a few years ago, our founding team knew that cloud was going to be a revolution for the IT indu...

Read more
  • Cloud Computing
  • Skill Profiles
— June 26, 2018

Disadvantages of Cloud Computing

If you want to deliver digital services of any kind, you’ll need to compute resources including CPU, memory, storage, and network connectivity. Which resources you choose for your delivery, cloud-based or local, is up to you. But you’ll definitely want to do your homework first.Cloud ...

Read more
  • AWS
  • Azure
  • Cloud Computing
  • Google Cloud
Albert Qian
— May 23, 2018

Announcing Skill Profiles Beta

Now that you’ve decided to invest in the cloud, one of your chief concerns might be maximizing your investment. With little time to align resources with your vision, how do you objectively know the capabilities of your teams?By partnering with hundreds of enterprise organizations, we’...

Read more
  • Cloud Computing
  • Product Feature
  • Skill Profiles
— April 5, 2018

A New Paradigm for Cloud Training is Needed (and Other Insights We Can Democratize)

It’s no secret that cloud, its supporting technologies, and the capabilities it unlocks is disrupting IT. Whether you’re cloud-first, multi-cloud, or migrating workload by workload, every step up the ever-changing cloud capability curve depends on your people, your technology, and your ...

Read more
  • Cloud Computing
— March 29, 2018

What is Chaos Engineering? Failure Becomes Reliability

In the IT world, failure is inevitable. A server might go down, an app may fail, etc. Does your team know what to do during a major outage? Do you know what instances may cause a larger systems failure? Chaos engineering, or chaos as a service, will help you fail responsibly.It almost...

Read more
  • Cloud Computing
  • DevOps
— November 22, 2017

AWS re:Invent 2017: Themes and Tools Shaping Cloud Computing in 2018

As the sixth annual re:Invent approaches, it’s a good time to look back at how the industry has progressed over the past year. How have last year’s trends held up, and what new trends are on the horizon? Where is AWS investing with its products and services? How are enterprises respondi...

Read more
  • AWS
  • Cloud Adoption
  • Cloud Computing
  • reInvent17
— October 27, 2017

Cloud Academy at Cloud Expo Santa Clara, Oct 31 – Nov 2

71% of IT decision-makers believe that a lack of cloud expertise in their organizations has resulted in lost revenue.1  That’s why building a culture of cloud—and the common language and skills to support cloud-first—is so important for companies who want to stay ahead of the transfor...

Read more
  • Cloud Computing
  • Events
— October 24, 2017

Product News: Announcing Cloud Academy Exams, Improved Filtering & Navigation, and More

At Cloud Academy, we’re obsessed with creating value for the organizations who trust us as the single source for the learning, practice, and collaboration that enables a culture of cloud.Today, we’re excited to announce the general availability of several new features in our Content L...

Read more
  • Cloud Computing
— August 29, 2017

On 'the public understanding of encryption' Tweet by Paul Johnston

Some of the questions by journalists about encryption prove they don't get it. Politicians don't seem to get it either (most of them). In fact, outside technology, there are some ridiculous notions of what encryption means. Over and over again, the same rubbish around encrypti...

Read more
  • Cloud Computing
— July 13, 2017

Our Hands-on Labs have a new look

Building new hands-on labs and improving our existing labs is a major focus of Cloud Academy for 2017 and beyond. If you search "types of adult learning," you will get approximately 16.9 gazillion hits. Many will boast about how they meet the needs of a certain type of learner (up to 70...

Read more
  • Cloud Computing
  • hands-on labs
— July 11, 2017

New infographic: Cloud computing in 2017

With 83% of businesses ranking cloud skills as critical for digital transformation in 2017, it’s great news for anyone with cloud architecting experience, and for those considering a career in cloud computing. In our new infographic, we compiled some of the latest industry research to l...

Read more
  • Cloud Computing