Ansible examples

·

14 min read

---
- name: Install Docker on a group of servers
  hosts: servers
  become: true

  tasks:
    - name: Install dependencies
      apt:
        name: "{{ item }}"
        state: present
      with_items:
        - apt-transport-https
        - ca-certificates
        - curl
        - gnupg
        - lsb-release

    - name: Add Docker GPG key
      apt_key:
        url: https://download.docker.com/linux/ubuntu/gpg
        state: present

    - name: Add Docker repository
      apt_repository:
        repo: "deb [arch=amd64] https://download.docker.com/linux/ubuntu {{ ansible_lsb.codename }} stable"
        state: present

    - name: Install Docker
      apt:
        name: docker-ce
        state: present

Install Docker

  • The become keyword indicates that the playbook should execute with elevated privileges (i.e., become root).

  • The tasks section contains a list of tasks to execute in sequence.

  • The first task uses the apt module to install the necessary dependencies for Docker using the with_items loop to install multiple packages.

  • The second task uses the apt_key module to add the Docker GPG key to the system keyring.

  • The third task uses the apt_repository module to add the Docker repository to the system's list of repositories using the value of the ansible_lsb.codename variable, which is the code name of the Ubuntu release version.

  • The fourth task uses the apt module to install the Docker Community Edition (CE) package.

playbook to send mail on having high cpu , memory disk usage

usage of handlers and notify

---
 - name: Handlers Example
   hosts: server1
   gather_facts: false
   tasks:
     - name: Install httpd latest version
       yum:
         name: httpd
         state: latest
       become: true
       notify: restart_httpd
   handlers:
     - name: restart_httpd
       become: true
       service:
         name: httpd

using handlers with multiple tasks

handlers:
    - name: restart memcached
      service: name=memcached state=restarted
      listen: "restart web services"
    - name: restart apache
      service: name=apache state=restarted
      listen: "restart web services"

tasks:
    - name: restart everything
      command: echo "this task will restart the web services"
      notify: "restart web services"

usage of blocks

groups the tasks under a block here these tasks need become:yes so grouped under a block

---
 - name: Ansible Blocks
   hosts: server1
   gather_facts: false

   tasks:
     - block:
        - name: List usr directory content
          command: "ls -l /usr/"

        - name: List root partition content
          command: "ls -l /root/"

        - name: List bin directory content
          command: "ls -l /bin/"
       become: yes

     - name: List ansible user's home directory content

       command: "ls -l ~/"

Error handling using blocks and rescue

error handling using other methods in ansible playbook

To start executing your playbook at a particular task (usually the task that failed on the previous run), use the --start-at-task option.

ansible-playbook playbook.yml --start-at-task="install packages"

To execute a playbook interactively, use --step.

ansible-playbook playbook.yml --step

With this option, Ansible stops on each task, and asks if it should execute that task. For example, if you have a task called “configure ssh”, the playbook run will stop and ask.

Perform task: configure ssh (y/n/c):

What happens if a task fails in Ansible?

By default Ansible stops executing tasks on a host when a task fails on that host. You can use ignore_errors to continue on in spite of the failure. The ignore_errors directive only works when the task is able to run and returns a value of 'failed'.

VARS in ansible

In Ansible, variables provide the much-needed flexibility in Playbooks, templates and inventories as we shall later see in this tutorial. Built-in variables can be used to provide system information such as hostname, system architecture, interfaces etc.

Apart from inventory_hostname, some other essential magic variables are:

  • host vars → leveraged for getting information about other hosts in the inventory, including any variables that are associated with them.

  • play_hosts → lists all the hosts that are targeted by the current play.

  • group_names → contains a list of groups names to which the current host belongs in the inventory.

  • groups → key/value pair of all the groups in the inventory with all the hosts that belong to each group.

Vars in playbook

---
- name: Example Ansible playbook for Handlers
hosts: all
become: yes
remote_user: ubuntu
roles:
- custom-role

vars:
# 1. String Variable
main_playbook_variable: "foo"

# 2. Boolean Variable
is_enabled: false

# 3. List Variable
fruits:
- apple
- banana
- orange

# 4. Dictionary Variable
fruit_prices:
apple: 0.5
banana: 0.25
orange: 0.75

# 5. Referencing nested variable
fruit_basket:
- name: John
fruits:
- apple
- orange
- name: Jane
fruits:
- banana
- apple
- orange

# 6. Variable from the my-vars.yml
vars_files:
- my-vars.yml

tasks:
- name: String Variable from - main_playbook_variable
debug:
var: main_playbook_variable

- name: Boolean variable
debug:
msg: "Variable is true"
when: is_enabled

- name: List variable - Print list of fruits
debug:
var: fruits

- name: List variable - Reference individual item in list
debug:
var: fruits[0]

- name: Dictionary Variable - Accessing all dictionary variable
debug:
var: fruit_prices

- name: Dictionary Variable - Accessing individual specific fields
debug:
var: fruit_prices.apple

- name: Get the price of an apple
command: echo "{{ fruit_prices['apple'] }}"
#Register the price of a apple to new variable - apple_price
register: apple_price_as_registered_var

- name: Print the value of register variable
debug:
var: apple_price_as_registered_var.stdout

- name: Get the value of apple from the nested variable
debug:
var: fruit_prices[fruit_basket[0].fruits[0]]

# Jinja 2 filter on variables
- name: Using Jinja 2 filters on variables
debug:
var: fruit_prices.keys() | list | map('upper') | list

# Accessing variable inside playbook from my-vars.yml
- name: Get the value of variable from my-vars.yml
debug:
var: vars_from_my_vars_yml

#Defining and accessing the variable at RunTime
- name: Get the value from run time
debug:
var: version

#Defining and accessing the variable at RunTime
- name: Print the value of variable when var file is passed at run time
debug:
var: other_variable

executing ansible-playbook

ansible-playbook --inventory inventory/ansible-variable-playbook/hosts ansible-variables-playbook.yml

ansible-playbook --inventory inventory/ansible-variable-playbook/hosts ansible-variables-playbook.yml --extra-vars '{"version":"1.0","other_variable":"foo-world"}' 

ansible-playbook --inventory inventory/ansible-variable-playbook/hosts ansible-variables-playbook.yml --extra-vars "@my-vars.yml"

User Prompt in ansible playbook

If you want your playbook to prompt the user for certain input, add a 'vars_prompt' section. Prompting the user for variables lets you avoid recording sensitive data like passwords

ansible.cfg

If installing Ansible from a package manager, the latest ansible.cfg file should be present in /etc/ansible

Ansible Playbooks vs Roles

Roles

Playbooks

Roles are reusable subsets of a play.

Playbooks contain Plays.

A set of tasks for accomplishing a certain role.

Mapps among hosts and roles.

Example: common, webservers.

Example: site.yml, fooservers.yml, webservers.yml.

Ansible Sudo or Ansible become

In the earlier versions of ansible there is an option named as sudo which is deprecated now, Since ansible 2.0 there are two new options named as become and become_user

Let's suppose you want to run a task on the remote server to install some packages using yum. It's very obvious that you should become root user as Non-Root user cannot install packages, in this case, you can use ansible sudo. To be precise ansible become method

Ansible components

Here is a look at the many components that make up the Ansible framework.

1. Modules

They are predetermined instructions that are executed directly on remote hosts. Playbooks run modules that manage applications, packages, and files.

2. Playbooks

Playbooks for Ansible are task-specific user guides. Playbooks dictate your workflow since functions written in them are executed in the order they are written. They are simple text documents created in YAML

Chiradeep BasuMallick Technical Writer

Last Updated: July 15, 2022


Ansible is an open-source, cross-platform tool for resource provisioning automation that DevOps professionals popularly use for continuous delivery of software code by taking advantage of an “infrastructure as code” approach. This article explains Ansible’s functioning, architecture, and features in detail. It also discusses what Ansible is used for in a modern, digital environment.

Table of Contents

What Is Ansible?

Ansible is defined as an open-source, cross-platform tool for resource provisioning automation that DevOps professionals popularly use for continuous delivery of software code by taking advantage of an “infrastructure as code” approach.

A Pictorial Representation of How Ansible Works

Over the years, the Ansible automation platform has evolved to deliver sophisticated automation solutions for operators, administrators, and IT decision-makers across various technical disciplines. It’s a leading enterprise automation solution with flourishing open-source software and the unofficial standard in IT automated systems. It operates on several Unix-like platforms and can manage systems like Unix and Microsoft architectures. It comes with descriptive language for describing system settings. Michael DeHaan created Ansible, which Red Hat acquired in 2015.

Ansible is an agentless system that executes actions over remote SSH or Windows Remote Management connections (allowing remote PowerShell execution). Ansible is an open-source IT automation engine that may help you save time at work while simultaneously improving the scalability, consistency, and dependability of your IT infrastructure.

It is designed for IT professionals who require it for app deployment, system integration, in-service coordination, and anything else that an IT admin or network manager routinely accomplishes. Sys admins and developers would be unable to keep up if they had to manage everything manually in today’s IT environments, which are usually too complex and often have to expand too quickly.

Automation makes complex activities easier to manage, allowing engineers to focus on tasks that offer value to the organization. This implies that time is saved and production is boosted. And as said earlier, Ansible is fast becoming extremely relevant among automation tools. While it is at the vanguard of automation, systems management, and DevOps, it is also a valuable everyday tool for developers. Ansible enables the rapid configuration of an entire network of devices without the requirement for programming expertise.

In contrast to more simplistic management tools, Ansible users can leverage Ansible automation for installing software, automating daily tasks, provisioning infrastructure, improving security and compliance, and sharing automation across the entire enterprise.

See More: DevOps vs. Agile Methodology: Key Differences and Similarities

What Is Ansible Used For?

There are several prominent use cases for ansible in an organization:

1. Ansible for DevOps

Ansible helps automate the implementation of internally generated applications to your production programs to make DevOps easier. For orchestration, automation, configuration, and management of IT infrastructure, Ansible is the most popular DevOps tool. Ansible’s advantages in DevOps include adapting and scaling in response to demand. The following are the benefits of Ansible in DevOps using Ansible: the feedback loop is accelerated quicker, installations are dependable, IT architecture is coordinated, and deployments are faster.

2. Managing Docker containers using Ansible

Docker is a high-performance framework for efficiently constructing and executing containers on local devices and servers. One can compare Docker containers to lightweight virtual devices. Ansible delivers a robust collection of capabilities and built-in modules that make building automation scripts easier thanks to its straightforward design. This makes it possible to create tasks and run them in your preferred setting. In the form of playbooks, Ansible uses the “yet another markup language” or YAML language.

3. Utilizing Ansible for automation

Automating the deployment of any hardware will be the first step toward automating the operational service lifecycle of your application. Ansible can automate IT infrastructures on bare metal servers, virtualization platforms, and cloud servers. Moreover, it can automate the setup of various systems, devices, databases, storage devices, networks, and firewalls.

4. Configuration management

Ansible is a simple, trustworthy, and consistent configuration management solution. You can set it up quickly if you have prior experience in IT. Ansible configurations are descriptions of fundamental infrastructure data humans can read and process by computers. You only require passwords or an SSH (Secure Socket Shell) key to begin monitoring machines.

5. Installing web application using Ansible

Ansible enables rapid and simple deployment of applications with several tiers. One does not have to develop a code base to manage processes; instead, one can just define the required actions in a playbook, and Ansible will determine how to get the processes to the desired outcome. In other words, there will be no need to set up applications on each machine manually. Ansible uses SSH to communicate with remote networks and implement all instructions when a module is launched from a control device.

See More: DevOps Roadmap: 7-Step Complete Guide

6. Other ansible uses

Other reasons to use ansible include:

  • Provisioning: The first step toward automating the life cycle of your applications is to set up your hardware. One can use Ansible to set up cloud platforms, network hardware devices, virtualized hosts, and bare metal servers, among other equipment. Users can set up the numerous servers needed in the computer network during provisioning.

  • Compliance and security – Site-wide security policies, like rules for firewall software, can be used with other automated processes. When you set up the security information on the control device and run the playbook that goes with it, the security information is automatically adjusted on the various connected servers.

See More: DevOps Engineer: Job Description, Key Skills, and Salary in 2022

How Does Ansible Work?

Ansible interacts with your networks and sends little programs, known as modules, to them. These modules are utilized to complete automated tasks as systems designed to be resource models for the functioning at the desired state. Ansible runs these modules and eliminates them after they’re done. If modules weren’t available, you would have to depend on ad-hoc procedures and scripting to complete tasks. Ansible’s management node is the primary node overseeing the Playbook’s implementation.

The management node sets up an SSH connection before executing the modules and installing the product on the host workstations. Once the modules have been deployed, it eliminates them. So that’s how it works with Ansible. Python is used to create an Ansible script and connects remote hosts through SSH, specified in the inventory file. Ansible is agentless – implying that it doesn’t need any program to be installed on the nodes it controls.

Ansible takes inventory data to determine which machines you wish to control. It has a default inventory file, but users can customize it to manage the servers they want to. To link to servers and conduct tasks, Ansible employs the SSH protocol. Ansible establishes a connection with the remote system and distributes the modules required for command or playbook execution. Ansible uses human-readable YAML templates to allow the automation of repetitive processes without the need to master a complex programming language.

You could use Ansible’s built-in modules to automate, or you can develop your own processes. Creating Ansible modules is possible using any programming language that can return JSON, including Ruby, Python, and shell. Powershell is used to develop Windows automation modules. It also stores your application’s history information, enabling you to repeal to a previous standard or update it simply. It provides the following advantages:

  • Ansible is a free and open-source software tool that all can access.

  • Ansible’s playbooks do not need coding expertise for installation and usage; they are straightforward to configure and use.

  • Ansible enables the modeling of even the most complex IT processes.

  • You can orchestrate the whole app environment regardless of where the application is deployed.

  • It has no agent in the client machines you desire to automate, and one must open no additional software or firewall ports.

  • Since no extra software is necessary, servers have a greater capacity for app resources, resulting in increased efficiency.

See More: Scrum vs. DevOps: Understanding the Key Differences

Understanding the Architecture of Ansible

Here is a look at the many components that make up the Ansible framework.

1. Modules

Modules are essential software that Ansible delivers from the command computer to all nodal network points or distant hosts. They are predetermined instructions that are executed directly on remote hosts. Playbooks run modules that manage applications, packages, and files. Ansible executes all modules for delivering updates or performing the required activity and then eliminates them after they’re through. Ansible has over 450 modules for typical tasks. Ansible has hundreds of built-in modules, the pieces of code that are run when a playbook is launched. A playbook has plays, containing various tasks that include modules.

2. Playbooks

Playbooks for Ansible are task-specific user guides. Playbooks dictate your workflow since functions written in them are executed in the order they are written. They are simple text documents created in YAML, a data serialization language that humans understand. They are at the heart of what makes Ansible so attractive since they describe the tasks one must perform quickly without requiring the user to remember particular terminology. In addition to being able to describe settings, they may also orchestrate the stages of any manually arranged task and conduct tasks concurrently or sequentially.

3. Plugins

Plugins are little pieces of code that augment a website’s functionality. Ansible comes with several of these, but one can create their own. Plugins are a specific type of module in this case. Before a module is performed on the nodes, the plugins are run. For logging reasons, plugins are executed on the primary control unit. You have call-back plugins because they allow you to connect to various Ansible events for display and reporting. To minimize the costs of fact-gathering processes, cache plugins are used. Action plugins are front-end modules that perform operations on the controller system prior to invoking the modules directly.

3. Plugins

Plugins are little pieces of code that augment a website’s functionality. Ansible comes with several of these, but one can create their own. Plugins are a specific type of module in this case. Before a module is performed on the nodes, the plugins are run

4. Inventories

The inventory comprises all the nodes or hosts that need to be taken care of, along with their IP addresses, server details, databases, and other information.

Uses of Ansible

Features of Ansible