How to Write an Ansible Playbook.

How to Write an Ansible Playbook.

Ansible is one of the popular Opensource Software Configuration Management tools compared with other tools. In our previous article, we have discussed How to Create an Ansible Inventory. As we discussed, ansible is mainly used for IT Automation, Provisioning, and Application Deployment purpose. Ansible will play its role with multiple managed nodes like App servers, Database, and more. Running the ansible can be in many ways. Among them, Ad-Hoc tasks are meant for simple and single tasks. But Running ansible with Playbook is more powerful. In this article, we will discuss How to Write an Ansible Playbook.

Read this: How to Create an Ansible Inventory.

Introduction to Ansible Playbook.

Ansible playbook is like a configuration management runbook with powerful control over scripting orchestrating. Just like a source code of the application, we can write and maintain the Ansible Playbook in the version control system and multiple people can work with it.

Look at sample Ansible Playbook: Ansible_riemann_influxdb_grafana.

Ansible Playbook Architecture
Ansible Playbook Architecture

This Ansible Playbook can be run with the different command line tool called “ansible-playbook” and ideal command will look like:

Ansible-playbook -i <inventory_file_path> <ansible_playbook_path>

Basics of writing Playbook.

Ansible Playbook is written in YAML format which is very simple and straight forward which makes it easy like reading and writing the English language. Also, since it is written in YAML syntax, we need to maintain indentation correct, else we will end up syntax error.

Let’s see some important basic concepts and keywords we should know about playbooks before writing one.

Defining Hosts

The Playbook is going to run one or more tasks on the target hosts which are defined in the Ansible Inventory file. But we need to mention which one or group of hosts we need to run on the targeted machine. We normally mention the same

---
- hosts: app_servers

Remote User

Along with hosts, we need to declare the Remote User on which account the defined tasks in the playbook are going to be executed in the Remote machine. And this can be mentioned as

---
- hosts: app_servers
  remote_user: deployadmin

We can also make that above user to become any user that we need to run the tasks as.

---
- hosts: app_servers
  remote_user: deployadmin
  become: yes
  become_method: installuser

If the ‘become_user’ must be authenticated with a password, we can make ansible to prompt for the same while running the code by mentioning the “--ask-become-pass” along with ansible-playbook command-line tool.

Performing Tasks

Ansible playbook contains one or more task which will essentially run and perform some activity on the remote server. Basically, we call that as a module, which mean, every task will execute some module that is responsible for performing some activity on the remote server. So, the task section looks like below

tasks:
  - name: run the example command on shell
    shell: /usr/bin/examplecommand

In this, “name” is the keyword to label the task. It is human-readable, so it can be written as you wish. “shell” is the keyword that will have shell command to be executed. Similarly, we have a list of tasks that will make almost everything possible that we do with the remote server.

Templating the Module.

Template” is the keyword to mention the file which contains configurations with the place for dynamic values. When the Ansible playbook gets executed, the template file will be filled with the defined values to create a dynamic configuration file. This module is templated by Jinja2 to inject dynamic values. Below is the sample template file (Apache Config)

<VirtualHost *:{{ http_port }}>
    ServerAdmin webmaster@{{ domain }}
    ServerName {{ domain }}
    ServerAlias www.{{ domain }}
    DocumentRoot /var/www/{{ domain }}
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

In this example apache config file, we have double curly braces “{{“ opened and closed and inside we have variables that will be declared in ansible-playbook. In this example, “http_port” and “domain” are variables that are declared in the variable section in the playbook. So the template section of the playbook can look like below:

- hosts: app_servers
	  remote_user: deployadmin
become: yes
become_method: installuser
vars:
	http_port: 80
	domain: example.com
tasks:
	template:
	  src: templates/apacheconfig.j2
	  dest: /etc/apache2/sites-available/000-default.conf

Handlers

Handlers are one or more tasks that will help in handling the post-task situation. For example, if we have an apache server configured by the ansible-playbook, we need to restart the server. So, we call “notifier” which will run a set of handlers post the playbook execution.

tasks:
  - name: start apache server
    service:
      name: httpd
      state: started
  	notify:
  		- restart apache_restart

In this, we have notified the handler with the name of the handler called “apache_restart” which will again call the task “services” to restart the server.

So, the overall Ansible playbook will look like this:

---
- hosts: app_servers
  remote_user: deployadmin
  become: yes
  become_method: installuser 
  vars:
    http_port: 80
    domain: example.com
  tasks:
    - name: install apache2
      apt: name=apache2 update_cache=yes state=latest
    template:
      src: templates/apacheconfig.j2
      dest: /etc/apache2/sites-available/000-default.conf
    notify:
      - restart apache2
  handlers:
    - name: restart apache2
      service: name=apache2 state=restarted

Just save this as apacheconfig.yml and in the same directory, create a folder called template, and keep apacheconfig.j2 with the apache2 jinja2 config mentioned earlier. Along with this, populate the inventory file with the list of the remote server to apache2 be installed and give the group name as “app_servers”. Don’t forget to change whatever remote_user and Become user. Finally, execute the following command:

ansible-playbook -I path_to_inventoryfile --ask-become-pass apacheconfig.yml.

This will run the ansible playbook to the listed remote servers in inventory file.

Conclusion

Ansible playbook makes configuration management easier. With the help of other stacks of ansible features, we can build the advanced enterprise-level configuration management tool. As of now, we have discussed How to Write an Ansible Playbook. In our upcoming article, we will discuss more advanced concepts and procedures of ansible. Stay tuned and subscribe DigitalVarys for more articles and study materials on DevOpsAgileDevSecOps, and App Development.

Leave a Reply