Section 1: Getting started with Ansible
How Ansible works
Ansible is an automation tool that connects to machines, usually over SSH, and runs small programs called modules on them. A module does one job, such as installing a package, copying a file or managing a service, and reports whether it changed anything.
Agentless
Nothing needs to be installed on managed servers except Python and an SSH server, which most Linux distributions already have. The machine running Ansible is the control node. The servers are managed nodes. This makes Ansible easy to adopt: if you can SSH to a server, Ansible can manage it.
Declarative tasks
Compare a shell script with an Ansible task:
# shell: imperative, runs every time
apt-get install -y nginx
# Ansible: describes the desired state
- name: Ensure nginx is installed
ansible.builtin.apt:
name: nginx
state: present
The module checks whether nginx is already installed. If it is, nothing happens and the task reports ok. If not, it installs it and reports changed. This property, idempotency, means you can run the same playbook again and again safely, which is the foundation of everything in this course.
The main building blocks
- Inventory: the list of hosts and groups to manage.
- Modules: units of work, such as
apt,copy,template,user,service. - Tasks: a module call with arguments and a name.
- Playbooks: YAML files mapping groups of hosts to lists of tasks.
- Handlers: tasks that run only when notified, for example restarting nginx after its configuration changed.
- Roles: a standard folder structure for reusable automation.
- Collections: packages of modules, roles and plugins, such as
community.generaloransible.posix.
Installing Ansible
Install it on the control node only, ideally in a virtual environment so versions are under your control:
python3 -m venv ~/.venvs/ansible
source ~/.venvs/ansible/bin/activate
python -m pip install ansible ansible-lint
ansible --version
The ansible package includes ansible-core plus a curated set of collections. Experienced teams sometimes install only ansible-core and declare the exact collections they need in a requirements file, which we do later.
Ansible runs on Linux and macOS control nodes. On Windows, use WSL 2.