What is Ansible

If you have to install some tools e.g. Nginx or Mysql on a server, it won’t be a problem for you. However, if the number of servers increases, the same task must be repeated multiple times. Moreover, humans are prone to make mistakes that cause errors.  This is why we use Ansible to automate processes.

Ansible is a tool that provides;

  • IT Automation
  • Config Management
  • Automatic Deployment

With Ansible, the code is prepared once for installation and deployed many times to many servers. This lets us work on more productive tasks rather than repetitive ones.

Components for using Ansible;

  • Local machine (which ansible is installed & have ssh access to the remote machines)
  • Remote machines (which are the systems that will be configured.)
  • Playbooks (which is a collection of config files)
  • Inventory (which is a document that groups the servers)

Playbooks;

The configuration files contain instructions that are written in YAML format.

e.g.

---
- 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
  • A playbook begins with “– – –
  • Playbooks might contain multiple plays (step1 & step2 in the example)
  • The host is the target server for the play and might be
    • “all” for all servers in the specified inventory
    • “localhost” for the server that is running ansible playbook
    • “webserver1” for a single target in the specified inventory
    • “webservers” for a list of targets in the specified inventory
  • All plays (step1 & step2) have a list of tasks that will be run in the given order.
  • Each task in the list of the tasks has a name (it is not a must)
  • The name is followed by instructions to execute the task.

How to specify Hosts? – Inventory

The Inventory file can classify servers into groups. In the example, we have two groups for our servers;

  • appservers
  • webservers
  • dbservers

The hostnames of the servers are specified under the group name.

[appservers]
appserver1
appserver2

[webservers]
webserver1
webserver2
webserver3

[dbservers]
dbserver1
dbserver2

Ansible should be installed only on the local machine. This is because Ansible runs agentless. Also, the playbook and inventory specified only on the local machine. Other than this, Ansible runs plays on remote servers with SSH protocol. If you can ssh a server, you can also run an ansible playbook on that server.

Leave a Comment

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