Guides

What is Ansible?

Engin Can Höke
  • #ansible
  • #automation
  • #devops

If you need to install tools like Nginx or MySQL on a server, it’s manageable. However, as the number of servers increases, repeating the same tasks becomes tedious and error-prone. This is where Ansible comes into play, automating processes to enhance efficiency.

What Does Ansible Provide?

Ansible is a tool that offers:

  • IT Automation
  • Configuration Management
  • Automatic Deployment

With Ansible, you write the code for installation once and deploy it across multiple servers, allowing you to focus on more productive tasks instead of repetitive ones.

Components of Ansible

To use Ansible, you’ll need:

  • Local Machine: Where Ansible is installed and has SSH access to remote machines.
  • Remote Machines: The systems to be configured.
  • Playbooks: Collections of configuration files written in YAML format.
  • Inventory: A document that groups the servers.

Understanding Playbooks

Playbooks are configuration files containing instructions in YAML format. Here’s an example:

---
- name: step1
  hosts: webserver1
  tasks:
    - name: "apt-get update"
      apt:
        update_cache: yes
        cache_valid_time: 3600

    - name: "install nginx"
      apt:
        name: ['nginx']
        state: latest

- name: step2
  hosts: dbserver1
  tasks:
    - name: "apt-get update"
      apt:
        update_cache: yes
        cache_valid_time: 3600

    - name: "install mysql"
      apt:
        name: ['mysql-server']
        state: latest

Key points about playbooks:

  • A playbook begins with ---.
  • Playbooks can contain multiple plays (e.g., step1 and step2 in the example).
  • The hosts field specifies the target server(s) for the play and can be:
    • "all" for all servers in the specified inventory.
    • "localhost" for the server running the Ansible playbook.
    • "webserver1" for a single target in the specified inventory.
    • "webservers" for a list of targets in the specified inventory.
  • Each play has a list of tasks executed in order.
  • Each task can have a name (optional) and contains the instructions to execute.

Specifying Hosts with Inventory

The Inventory file classifies servers into groups. For example:

[appservers]
appserver1
appserver2

[webservers]
webserver1
webserver2
webserver3

[dbservers]
dbserver1
dbserver2

How Does Ansible Work?

Ansible needs to be installed only on the local machine because it operates agentlessly. The playbook and inventory are specified on the local machine. Ansible executes plays on remote servers using the SSH protocol. If you can SSH into a server, you can run an Ansible playbook on that server.

For more detailed information, refer to the official Ansible documentation.

I hope this guide helps you understand the basics of Ansible and how it can streamline your IT automation tasks.