Skip to Content

Getting Started with Ansible: A Simple Guide for Beginners

Ansible is an open-source automation tool that helps in configuring, deploying, and managing software applications across various servers.

It uses SSH for communication, so there’s no need to install an agent on remote machines. Here’s a simple guide to get started with Ansible for beginners:

What is Ansible?

Ansible is an IT automation tool that can help you with application deployment, task automation, and configuration management. It’s agentless, uses Python, and works over SSH.

It makes your life easier by doing these tasks automatically.

Why Use Ansible?

  • Simplicity: Ansible uses YAML format for its playbooks, which are easy to read and write.
  • Agentless: No need to install agents on remote systems.
  • Idempotent: Running a playbook multiple times will give the same result.
  • Wide Range of Modules: Supports a vast array of modules for different tasks.

What You Need

  • Basic Command Line Knowledge: Knowing how to use a terminal or command line is helpful.
  • Python Installed: Ansible works with Python. Make sure you have it installed.

Step-by-Step Guide

1. Install Ansible

You need to install Ansible on your computer.

  • On Linux or macOS:
    sudo apt update
    sudo apt install ansible

    Or, if you prefer using Python:

    pip install ansible
  • On Windows:Use WSL (Windows Subsystem for Linux): Install WSL, then follow the Linux instructions within WSL.

2. Create an Inventory File

Ansible needs to know which computers (servers) you want to manage. This is done using an inventory file.

Create a file named hosts (you can use any name):

[webservers]
server1.example.com
server2.example.com

[databases]
dbserver.example.com

Replace server1.example.com, etc., with the addresses of your actual servers.

3. Write a Playbook

A playbook is a set of instructions for Ansible, written in a simple format called YAML.

Create a file named site.yml:

---
- name: Install web server
  hosts: webservers
  become: yes
  tasks:
    - name: Install nginx
      apt:
        name: nginx
        state: present

- name: Install database server
  hosts: databases
  become: yes
  tasks:
    - name: Install MySQL
      apt:
        name: mysql-server
        state: present

This playbook does two things:

  • Installs nginx on the web servers.
  • Installs MySQL on the database servers.

4. Run the Playbook

Now you need to run your playbook to apply the changes.

In your terminal, type:

ansible-playbook -i hosts site.yml

This command tells Ansible to use your hosts file and run the instructions in site.yml.

5. Understand the Ansible Basics

  • Playbook: A file that contains instructions for Ansible.
  • Play: A set of instructions for a specific group of servers.
  • Task: An individual action to be done, like installing software.
  • Module: The tool Ansible uses to perform tasks (e.g., apt for installing software).

Using Ansible Variables

You can make your playbooks more flexible by using variables. For example, if you want to easily change the software being installed, you can use a variable.

Update site.yml like this:

---
- name: Install web server
  hosts: webservers
  become: yes
  vars:
    package_name: nginx
  tasks:
    - name: Install package
      apt:
        name: "{{ package_name }}"
        state: present

Here, package_name is a variable you can change easily.
Certainly! Below is the information on using loops and conditions in Ansible, formatted as HTML:

Basic Looping in Ansible

Ansible loops are used to repeat a task multiple times with different items. The loop keyword is commonly used for this purpose.


- name: Install packages
  hosts: servers
  tasks:
    - name: Install packages
      apt:
        name: "{{ item }}"
        state: present
      loop:
        - nginx
        - mysql
        - php
    

Looping Over Dictionaries

You can loop over complex data structures like dictionaries by referencing subkeys.


- name: Add several users
  user:
    name: "{{ item.name }}"
    state: present
    groups: "{{ item.groups }}"
  loop:
    - { name: 'testuser1', groups: 'wheel' }
    - { name: 'testuser2', groups: 'root' }
    

Nested Loops

Nested loops can be managed using loop_control to prevent variable conflicts.


- include_tasks: inner.yml
  loop: [1, 2, 3]
  loop_control:
    loop_var: outer_item
    

In inner.yml:


- debug:
    msg: "outer item={{ outer_item }} inner item={{ item }}"
  loop: ['a', 'b', 'c']
    

Using Conditions with Loops

Conditions can be applied to loops to execute tasks only when certain criteria are met.


- name: Install packages conditionally
  apt:
    name: "{{ item }}"
    state: present
  loop:
    - nginx
    - mysql
    - php
  when: ansible_os_family == "Debian"
    

Loop Control

Ansible provides loop_control for additional customization, such as pausing between iterations or labeling outputs.


- name: Print numbers with pause
  debug:
    msg: "{{ item }}"
  loop: [1, 2, 3]
  loop_control:
    pause: 3
    

By using loops and conditions effectively, you can simplify your Ansible playbooks, reduce redundancy, and enhance automation efficiency.

Basic Error Handling in Ansible

By default, Ansible stops executing tasks on a host when a task fails and continues with other hosts. This behavior ensures that errors are addressed immediately, preventing further issues.

Ignoring Errors

You can use the ignore_errors: yes directive to allow a playbook to continue executing tasks even if a particular task fails. This is useful when a failure is non-critical.


- name: This will not be counted as a failure
  command: /bin/false
  ignore_errors: yes
    

Conditional Failure

The failed_when directive allows you to define custom conditions for a task to be considered failed. You can specify conditions based on command output or return codes.


- name: Fail task when the command error output prints FAILED
  command: /usr/bin/example-command -x -y -z
  register: command_result
  failed_when: "'FAILED' in command_result.stderr"
    

Handling Unreachable Hosts

Introduced in Ansible 2.7, the ignore_unreachable option allows tasks to continue executing even if a host becomes unreachable.


- hosts: all
  ignore_unreachable: true
  tasks:
    - name: This executes, fails, and the failure is ignored
      ansible.builtin.command: /bin/true
    

Block and Rescue

Blocks are used to group tasks together and apply common options to them. You can use blocks to handle errors collectively.


tasks:
  - block:
      - name: Install httpd
        yum:
          name: httpd
          state: present
    rescue:
      - name: Handle installation failure
        debug:
          msg: "Failed to install httpd"
    

Aborting on Errors

The any_errors_fatal option can be set at the play or block level to abort execution on all hosts if a task fails. This is useful when all tasks must succeed for the playbook to continue.


- hosts: somehosts
  any_errors_fatal: true
  tasks:
    - name: Critical task
      command: /usr/bin/critical-command
    

By leveraging these error-handling techniques, you can create robust Ansible playbooks that can handle failures gracefully and ensure that your automation processes are reliable.

Learn More

Tips for Beginners

  • Start Simple: Begin with basic playbooks and build up from there.
  • Use –check: Run playbooks with the –check option to see what changes will be made without actually applying them.
  • Read the Output: Look at the messages Ansible gives you to understand what’s happening and fix any problems.

By following these steps, you’ll get a good start with Ansible and be able to automate many of your tasks. Have fun automating!

Eric Swill

Saturday 24th of August 2024

I've been going through this insightful Ansible guide, and I must say, it's been quite the eye-opener. For those of us who are new to the world of Ansible or looking to sharpen our skills, this guide has been a fantastic resource.

Thank you.