ansible (1)

Automation with Ansible

In today’s IT landscape, where infrastructure grows complex and environments are distributed across cloud, on-premise, and hybrid setups, automation is key to ensuring consistency, scalability, and efficiency. Ansible stands out as one of the most popular automation tools, loved for its simplicity, agentless architecture, and power to manage configurations, deploy applications, and orchestrate services.

In this blog post, we’ll dive into what Ansible is, explore its use cases, and provide a cheatsheet to help you get started with some essential commands.


What is Ansible?

Ansible is an open-source IT automation tool that enables you to manage systems, deploy applications, and configure infrastructure through simple, human-readable playbooks written in YAML. Unlike many other automation tools, Ansible operates without the need to install any agents on target machines. It communicates with nodes via SSH (Linux/Unix) or WinRM (Windows), making it easier to adopt and manage.

Key Features of Ansible:

  1. Agentless: No software is required on the target machines—just an SSH connection.
  2. Declarative: You define what you want to do, and Ansible figures out the how.
  3. Idempotent: Ansible ensures that actions won’t be repeated unnecessarily—if the desired state is already achieved, no changes will be made.
  4. Extensible: You can extend its functionality by writing custom modules and plugins.
  5. Scalable: It can manage everything from a few servers to hundreds or thousands across different environments.

Key Ansible Components

  1. Inventory: Defines the list of hosts (servers) to manage.
  2. Playbooks: A series of tasks written in YAML that define what needs to be done.
  3. Tasks: Individual units of action within a playbook (e.g., installing software, restarting services).
  4. Modules: Reusable units of code that perform specific actions (e.g., yum, apt, copy, file, etc.).
  5. Roles: A way to organize playbooks and variables for reuse across projects.

Common Use Cases of Ansible

1. Configuration Management

Ansible excels at maintaining and managing system configurations, ensuring that all machines in your inventory are in a consistent and desired state. You can use it to install software packages, configure services, and manage user accounts across multiple servers.

Example: Ensure that Nginx is installed and running on all web servers.

- hosts: web_servers
  tasks:
    - name: Install Nginx
      apt:
        name: nginx
        state: present

    - name: Ensure Nginx is running
      service:
        name: nginx
        state: started
        enabled: yes

2. Application Deployment

Ansible can automate the deployment of applications, manage dependencies, configure environments, and orchestrate the overall process.

Example: Deploy a Python application with dependencies.

- hosts: app_servers
  tasks:
    - name: Install Python dependencies
      pip:
        name:
          - flask
          - requests
        state: present

    - name: Deploy the application
      copy:
        src: /local/path/to/app
        dest: /var/www/myapp

3. Cloud Provisioning

Ansible can interact with cloud providers (AWS, Azure, Google Cloud) to provision infrastructure, configure resources, and manage services. It works through cloud-specific modules that interface with APIs.

Example: Provision an EC2 instance on AWS.

- hosts: localhost
  tasks:
    - name: Launch an EC2 instance
      ec2:
        key_name: mykey
        instance_type: t2.micro
        image: ami-0abcdef12345
        region: us-east-1
        count: 1
        vpc_subnet_id: subnet-xyz123

4. Infrastructure as Code (IaC)

With Ansible, you can define your entire infrastructure as code. You write playbooks to manage resources, which can be versioned, reviewed, and re-executed as needed.

5. Security Automation

Ansible is also used to automate the enforcement of security policies, including patch management, firewall rules, user management, and configuration compliance.

Example: Configure firewall rules with Ansible.

- hosts: all
  tasks:
    - name: Allow HTTP and HTTPS traffic
      ufw:
        rule: allow
        port: "{{ item }}"
        proto: tcp
      loop:
        - 80
        - 443

Ansible Commands Cheatsheet

1. Ad-hoc Commands

Ad-hoc commands allow you to run one-off commands across your inventory without writing a playbook.

CommandDescription
ansible all -m pingPing all hosts in the inventory
ansible web -m shell -a "uptime"Run the uptime command on all web servers
ansible app -m apt -a "name=nginx state=present"Install Nginx on app servers
ansible db -m service -a "name=mysql state=started"Ensure MySQL service is running

2. Working with Playbooks

CommandDescription
ansible-playbook playbook.ymlRun the playbook.yml on all hosts defined in inventory
ansible-playbook -i inventory.yml playbook.ymlSpecify a custom inventory file
ansible-playbook --syntax-check playbook.ymlCheck playbook for syntax errors
ansible-playbook -u username playbook.ymlRun playbook using a specific SSH user
ansible-playbook --check playbook.ymlPerform a dry-run to see what changes would be made

3. Inventory Management

CommandDescription
ansible-inventory --list -i inventory.ymlList all hosts defined in the inventory
ansible all --list-hostsShow all hosts in the default inventory
ansible -i inventory.ini web -m pingUse a specific inventory file and ping all web servers
ansible-inventory -i inventory.yml --graphVisualize the inventory as a graph

4. Managing Roles and Galaxy

CommandDescription
ansible-galaxy init my_roleCreate a new role directory structure
ansible-galaxy install username.rolenameInstall a role from Ansible Galaxy
ansible-galaxy listList all installed roles
ansible-galaxy remove username.rolenameRemove an installed role

Example Playbook

Let’s walk through a simple playbook that sets up a LAMP stack (Linux, Apache, MySQL, PHP) on a group of web servers.

---
- hosts: web
  become: yes

  tasks:
    - name: Install Apache and PHP
      apt:
        name:
          - apache2
          - php
        state: present

    - name: Start and enable Apache
      service:
        name: apache2
        state: started
        enabled: yes

    - name: Install MySQL Server
      apt:
        name: mysql-server
        state: present

    - name: Create a MySQL database
      mysql_db:
        name: my_database
        state: present

    - name: Copy website files to /var/www/html
      copy:
        src: /local/path/to/website
        dest: /var/www/html

This playbook does the following:

  1. Installs Apache and PHP on all web servers.
  2. Ensures that Apache is started and enabled at boot.
  3. Installs MySQL and creates a new database.
  4. Copies website files to the default Apache document root.

You can execute this playbook by running:

ansible-playbook lamp_setup.yml

Conclusion

Ansible is a powerful, flexible, and easy-to-learn automation tool that brings consistency to system administration, configuration management, and application deployment. With its agentless nature and simple YAML syntax, it’s an ideal choice for teams looking to automate infrastructure at scale.

Whether you’re managing a handful of servers or orchestrating hundreds across various environments, Ansible’s versatility makes it a go-to solution for automation. Use the cheatsheet and sample playbooks to start automating your infrastructure today!