Ansible simplifies IT automation by allowing you to configure, deploy, and manage infrastructure with straightforward YAML files. Here’s how we used Ansible to deploy Jenkins, SonarQube, and a sample application while automating repetitive tasks across our setup. We’ll also cover some powerful ways to extend Ansible’s capabilities.

Table of Contents

  • Key Components of Ansible
  • Setting Up Ansible
  • Writing Your First Playbook
  • Example: Using Ansible for Jenkins and SonarQube Deployment
  • Cool Things You Can Do with Ansible
  • Conclusion

Key Components of Ansible

Before diving into the example, let’s briefly cover some essential Ansible concepts:

  • Inventory: A list of hosts (servers) that Ansible will manage.
  • Playbooks: YAML files that define tasks Ansible should perform on managed hosts.
  • Roles: Reusable sets of tasks, variables, and handlers structured in a standard format.
  • Modules: Units of work that perform specific tasks, such as installing packages, managing files, or executing commands.
  • Variables: Used to make playbooks more dynamic, storing information like package names, IP addresses, and paths.

Setting Up Ansible

First, install Ansible on your control machine (e.g., your local workstation or a dedicated automation server). Ansible typically runs on Linux-based systems, but you can also install it on macOS.

# Install Ansible on Ubuntu
sudo apt update
sudo apt install ansible -y

Verify the installation:

ansible --version

Next, create an inventory file that specifies the hosts Ansible will manage. For example:

[webservers]
web1.example.com ansible_user=your_user ansible_ssh_private_key_file=~/.ssh/id_rsa
web2.example.com ansible_user=your_user ansible_ssh_private_key_file=~/.ssh/id_rsa

[dbservers]
db1.example.com ansible_user=your_user ansible_ssh_private_key_file=~/.ssh/id_rsa

[all:vars]
ansible_ssh_private_key_file=~/.ssh/id_rsa

Writing Your First Playbook

Ansible playbooks are YAML files where we define tasks for Ansible to execute. Below, we’ll go over a sample playbook provided in your configuration to deploy and configure Jenkins and SonarQube.


Example: Using Ansible for Jenkins and SonarQube Deployment

In this section, we’ll use the deploy.yml playbook file you provided, which automates the deployment and configuration of Jenkins and SonarQube on specified servers.

Playbook Structure

The playbook (deploy.yml) is structured as follows:

---
- name: Deploy Jenkins and SonarQube
hosts: all
become: true

tasks:
- name: Install required system packages
apt:
name: "{{ item }}"
state: present
loop:
- default-jdk
- wget
- gnupg

- name: Add Jenkins repository key
apt_key:
url: https://pkg.jenkins.io/debian-stable/jenkins.io.key
state: present

- name: Add Jenkins repository
apt_repository:
repo: deb http://pkg.jenkins.io/debian-stable binary/
state: present

- name: Update apt cache
apt:
update_cache: yes

- name: Install Jenkins
apt:
name: jenkins
state: present

- name: Start and enable Jenkins service
systemd:
name: jenkins
state: started
enabled: true

- name: Install Docker
apt:
name: docker.io
state: present

- name: Pull and run SonarQube container
docker_container:
name: sonarqube
image: sonarqube:lts
ports:
- "9000:9000"
state: started
restart_policy: always

Explanation of Each Task

  1. Install Required System Packages:
    • This task installs essential packages, such as Java Development Kit (JDK), wget, and gnupg, which are prerequisites for Jenkins and SonarQube.
  2. Add Jenkins Repository Key:
    • Ansible retrieves the GPG key for the Jenkins repository, allowing the system to authenticate and trust the repository.
  3. Add Jenkins Repository:
    • The Jenkins repository is added to the system’s sources, enabling package manager access to the Jenkins package.
  4. Update apt Cache:
    • After adding the Jenkins repository, this task updates the apt cache to recognize new packages.
  5. Install Jenkins:
    • Installs the Jenkins package, making it available on the server.
  6. Start and Enable Jenkins Service:
    • This task ensures Jenkins starts immediately and will start automatically after any server reboot.
  7. Install Docker:
    • Docker is required to run SonarQube as a container. This task installs Docker on the server.
  8. Pull and Run SonarQube Container:
    • Ansible pulls the latest SonarQube LTS image and runs it as a container, mapping port 9000 to make the SonarQube web interface accessible.

Running the Playbook

To execute this playbook, use the following command:

ansible-playbook -i inventory deploy.yml

This command runs the playbook on all hosts specified in the inventory file.


Cool Things You Can Do with Ansible

Ansible isn’t just a deployment tool. It’s a powerful automation engine that can drive some sophisticated workflows in DevOps, security, and infrastructure management. Here are some of the more interesting and practical ways to use Ansible beyond basic configuration.


Self-Healing Infrastructure

  • Pair Ansible with monitoring tools (like Prometheus or Nagios) to trigger playbooks based on alert conditions. For example, if a service goes down or a VM crashes, Ansible can restart the service or spin up a new instance, enabling true self-healing capabilities.

Configuration Drift Detection and Remediation

  • Run Ansible playbooks on a schedule or integrate it with CI pipelines to catch and correct configuration drift. You can set up ansible-pull as a cron job or use a Jenkins job to continuously enforce the desired configuration state, automatically reverting any unauthorized changes.

Automated Compliance and Security Hardening

  • Leverage roles from Ansible Galaxy or write custom playbooks to apply security standards (like CIS benchmarks). Automate SSH hardening, firewall settings, service restrictions, and file permissions to lock down servers across your environment.

Blue-Green Deployments

  • Ansible can automate blue-green deployments by provisioning a new “green” environment with the updated application version. Once everything checks out, you simply route traffic to the new environment, making it easy to roll back if issues arise.

Automate Cloud Infrastructure Provisioning (IaC)

  • Use Ansible to define, version, and deploy infrastructure on cloud providers (AWS, Azure, GCP). Manage everything from VMs to networks and databases as code, making it easy to scale, replicate, and update environments without manual configuration.

CI/CD Pipeline Integration

  • Integrate Ansible into your CI/CD pipelines (e.g., Jenkins) to automate application deployment and testing. Ansible can handle rollbacks if tests fail, giving you a fully automated, reliable deployment pipeline.

Orchestrate Multi-Tier Applications

  • Use Ansible playbooks to coordinate deployments for complex setups involving web servers, application servers, and databases. With Ansible roles and dependencies, you can control the order of operations and ensure dependencies are deployed and configured in the correct sequence.

Automated Backups and Disaster Recovery

  • Schedule playbooks to back up databases, file systems, or critical data. If disaster strikes, Ansible can quickly recreate infrastructure and restore data, streamlining your recovery process.

Network Automation

  • Ansible’s networking modules let you manage configurations across routers, switches, and firewalls from multiple vendors (Cisco, Juniper, Arista, etc.). Standardize and enforce configurations, apply security policies, and centralize network management with a single tool.

Dynamic Inventory for Scaling Environments

  • Ansible’s dynamic inventory feature lets you pull instance data from cloud providers or container orchestrators. This is essential for environments that scale up and down, ensuring Ansible knows which hosts are active at any given time.

Centralized Secret Management with Ansible Vault

  • Use Ansible Vault to encrypt variables and files. Ansible can securely retrieve secrets during playbook runs, and you can integrate it with tools like HashiCorp Vault or AWS Secrets Manager for centralized management.

Remote Provisioning and OS Updates

  • Set up playbooks to handle OS patching and upgrades on a regular basis. With Ansible, you can ensure your entire server fleet is patched and up-to-date, minimizing security risks from outdated software.

Conclusion

Ansible opens up a wide range of automation possibilities. From self-healing infrastructure and compliance enforcement to network management and disaster recovery, you can use Ansible to drive complex workflows and keep your infrastructure consistent and secure. Whether you’re just starting out or diving into advanced use cases, Ansible is a versatile tool that scales with your needs.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *