ansible - 3 minutes read

Provision a server with Ansible

Let me introduce you to Ansible! It's a fantastic automation engine brought to you by RedHat, and the best part? It's open-sourced and completely free to use!

Ansible makes life easier by automating a variety of tasks like provisioning, configuration management, application deployment, and orchestration—just to name a few. It’s a great tool to help streamline your IT processes and boost productivity.

Bash vs Ansible

Imagine we have a server and we want to install Apache2—but only if it's not already up and running. With a little help from Bash, we can create a script to do just that! Here’s how it would look:

#!/bin/bash
# Check if Apache2 is already installed
if command -v apache2 >/dev/null 2>&1; then
    echo "Apache2 is already installed."
else
    echo "Apache2 is not installed. Installing now..."
    
    # Update package list
    sudo apt-get update -y
    
    # Install Apache2
    sudo apt-get install -y apache2
    
    # Check if the installation was successful
    if command -v apache2 >/dev/null 2>&1; then
        echo "Apache2 has been successfully installed!"
    else
        echo "There was an issue installing Apache2."
    fi
fi

Now, let's explore how we can achieve the same thing using Ansible!

Here’s a glimpse of what that might look like:

- hosts: 123.122.11.10
  become: yes  # Run as sudo
  tasks:
    - name: Install Apache2
      apt:
        name: apache2
        state: present
        update_cache: yes
        
    - name: Ensure Apache2 is running
      service:
        name: apache2
        state: started
        enabled: yes

Using Ansible over Bash for automation brings numerous benefits, particularly when managing IT infrastructure and deploying applications. Here are some of the key advantages:

1. Consistency and Idempotence

Ansible: It makes sure that tasks only run when needed, so if your system is already in the right state, nothing changes. You can run the same playbook over and over without worrying about breaking things or causing unexpected changes!

Bash: Bash scripts don't naturally handle things as Ansible does. You'll often need to add extra checks to prevent tasks from running again, which can make scripts longer and more complicated.

2. Readability and Maintainability

Ansible: Playbooks are written in YAML, which is super easy to read and understand—no need to decode complex scripts! Plus, Ansible’s modular structure means you can easily update and manage your automation tasks over time.

Bash: Bash scripts can quickly get messy and hard to follow, especially when you start adding a lot of error handling, conditionals, and loops. As they grow, managing and updating them becomes a real headache.

3. Cross-Platform Compatibility

Ansible: It’s designed to work seamlessly across different operating systems without needing to tweak your scripts much. Ansible handles the OS-specific stuff behind the scenes with its modules, so you don’t have to worry about compatibility issues.

Bash: Bash is mainly built for Unix-like systems, so if you want your scripts to work on different environments like macOS, various Linux distributions, or Windows, you’ll often need to make a lot of adjustments.

4. Reusability and Modularity

Ansible: It allows you to create reusable roles, tasks, and playbooks, so you can easily standardize and share your automation code across different projects. This helps keep things consistent and saves you time.

5. Error Handling and Reporting

Ansible: Comes with built-in error handling, clear output, and detailed logs. This makes it easy to troubleshoot issues and understand exactly what happened during execution.

Bash: You have to manually handle errors with conditional checks, which can make your scripts more complex and harder to debug.

6. Version Control Integration

Ansible: YAML files work great with version control systems like Git, so you can easily track changes, manage versions, and collaborate with your team.

Bash: Although you can version-control Bash scripts, keeping track of changes and collaborating can be more challenging because of the complexity and readability of the scripts.

7. Extensive Community and Ecosystem

Ansible: Backed by a large community and with tons of roles and modules available on platforms like Ansible Galaxy, you can easily find and use existing solutions to speed up your development process.

Bash: There isn’t a central repository for reusable scripts, so finding reliable and well-maintained scripts can be a bit of a challenge.

8. Security

Ansible: Utilizes secure connections (like SSH) and integrates smoothly with secrets management systems like Vault, offering a secure way to handle credentials and sensitive data.

Bash: Credentials are often handled insecurely within scripts, which can lead to potential security risks.

9. Orchestration Capabilities

Ansible: Perfect for orchestrating complex workflows across multiple servers, networks, and services. It makes managing infrastructure smooth and robust.

Bash: Mainly geared towards automating tasks on a single system and doesn’t have the advanced orchestration capabilities needed for managing complex, multi-system environments.

10. Learning Curve and Scalability

Ansible: It’s easy to pick up, especially if you’re familiar with YAML. Plus, it scales well, making it a great choice for both small and large infrastructure deployments.

Bash: While powerful, it has a steeper learning curve for advanced scripting. It also doesn’t scale as easily when managing large or complex environments.

Overall, Ansible offers a more structured, maintainable, and powerful way to handle automation, especially for complex IT environments or when you need to scale operations across multiple systems.

Multi-OS example

The below is a simple example.

--- 
# our role lets call it apache2 :) ./apache2/tasks/main.yml
- name: Install Apache Web Server
  become: yes  # Run commands as root
  vars:
    apache_packages:
      Debian: apache2
      RedHat: httpd
      
  tasks:
    - name: Install Apache for Debian-based systems
      apt:
        name: "{{ apache_packages['Debian'] }}"
        state: present
      when: ansible_os_family == "Debian"
      
    - name: Install Apache for RedHat-based systems
      yum:
        name: "{{ apache_packages['RedHat'] }}"
        state: present
      when: ansible_os_family == "RedHat"
      
    - name: Start and enable Apache service for Debian
      service:
        name: "{{ apache_packages['Debian'] }}"
        state: started
        enabled: yes
      when: ansible_os_family == "Debian"
      
    - name: Start and enable Apache service for RedHat
      service:
        name: "{{ apache_packages['RedHat'] }}"
        state: started
        enabled: yes
      when: ansible_os_family == "RedHat"
# site.yml
- hosts: all
  become: yes
  roles:
    - apache2
#inventory
[staging]
123.34.22.11
[production]
111.12.1.11
ansible-playbook -i inventory site.yml --limit 'staging'

Reusable Roles

That role looks perfect! If you want to reuse it across different projects, Ansible makes it easy. You can create your own reusable roles and keep them in a vendor_roles directory, so they're ready to go whenever you need them.

From our example, go ahead and delete the ./apache2/tasks/main.yml file. Then, create a new file called requirements.yml and add the following content:

---
- name: apache2
  src: git+ssh://git@github.com/mtdevs28080617/ansible-role-apache2
  version: v1.0.0

Next run the following command:

ansible-galaxy install -r requirements.yml -p vendor_roles --force

 

You should now see our vendor role downloaded to that directory. 

 

Next, run the following command:

ANSIBLE_ROLES_PATH=./vendor_roles ansible-playbook site.yml -i inventory --limit 'staging'

 

With this setup, the role will automatically detect whether it's running on Debian or Red Hat and install Apache correctly on your staging environment. Plus, since the role is reusable and versioned, you can easily use it across all your projects. Say goodbye to writing tons of Bash scripts!

If you wish to download this role to have a play feel free https://github.com/mtdevs28080617/ansible-role-apache2, also make sure to check out https://www.ansible.com

Spread the word!

© Copyright 2025. All rights reserved, MTDevs.