Ansible: Tutorial & Best Practices

A tool to automate system configuration

Ansible is a configuration management tool that allows you to automate the deployment and configuration of applications and systems. With Ansible, you can use a single set of configuration files to manage multiple servers and devices.

To use ansible to configure Linux servers, you need to have the ansible software installed on your local machine and SSH access to the servers you want to manage. Here is an overview of the basic steps for using ansible to configure Linux servers:

Create an inventory file that lists the servers you want to manage:

webserver1 ansible_host= ansible_user=user1
webserver2 ansible_host= ansible_user=user1

This creates a group called "webservers" and lists the servers "webserver1" and "webserver2" with their respective IP addresses and SSH username.

Create a playbook file that specifies the tasks you want to run on the servers:

- hosts: webservers
    - name: Install Apache
      apt: name=apache2 state=present
    - name: Start Apache
      service: name=apache2 state=started enabled=yes
      This playbook installs the Apache web server and starts the service on all servers in the "webservers" group.

Run the playbook using the ansible-playbook command:

ansible-playbook -i inventory.ini playbook.yml

This runs the tasks specified in the playbook file on the servers listed in the inventory file.

Ansible allows you to define complex configuration scenarios using a simple and easy-to-read syntax. You can use variables, loops, and conditionals to customize your playbooks and adapt them to different environments.

Installation Using APT

apt install ansible

Inventory Configuration

Edit the file /etc/ansible/hosts and create your inventory like this:

# define a group of machines and specify port for ssh if not 22
vm1 ansible_port=22 ansible_host=
vm2 ansible_port=22 ansible_host=
vm3 ansible_port=22 ansible_host=

# another group
vm0 ansible_port=22 ansible_host=

# group of groups


Variables for hosts and groups can be set in individual files:


SSH Configuration

Make sure that you can login using ssh on all servers

Test Connection

ansible all -m ping


ansible vms -m ping

Create Master Playbook

Define a playbook for the complete infrastructure in site.yml:

- import_playbook: common.yml
- import_playbook: webservers.yml

Create Tasks in Individual Playbooks

Configure apt and install packages:

- hosts: all
    - name: Install pv
      apt: pkg=pv state=installed update_cache=true

Execute Playbooks

ansible-playbook site.yml --limit vms

For more information, you can refer to the ansible documentation or use the ansible-doc command to view the available modules and options.

Except where otherwise noted, content on this site is licensed under a CC BY-SA 4.0 license CC BY SA