Configuration management with Ansible
Terraform creates servers; Ansible makes them useful: packages installed, config files in place, services running. You describe the desired state in YAML, and Ansible logs in over SSH and makes each machine match it, as many times as you like, on as many machines as you like.
How Ansible works
- Agentless: nothing to install on the servers. The control node (your laptop or a CI runner, Linux or macOS; on Windows use WSL) connects over plain SSH with your normal keys, copies a small Python module over, runs it and removes it. The managed nodes just need SSH and Python 3.
- Push-based: changes happen when you run Ansible, not on a schedule.
- Modules do the work:
ansible.builtin.apt,copy,template,service,userand thousands more in collections. Each one knows how to check the current state before changing anything.
$ pipx install --include-deps ansible # or: sudo apt install ansible
$ ansible --version
Inventory: which machines
The inventory lists hosts and sorts them into groups. The INI format is the simplest:
# inventory.ini
[web]
web1 ansible_host=203.0.113.11
web2 ansible_host=203.0.113.12
[db]
db1 ansible_host=10.0.2.20
[all:vars]
ansible_user=ubuntu
ansible_ssh_private_key_file=~/.ssh/id_ed25519
A small ansible.cfg next to it saves typing -i inventory.ini every time:
# ansible.cfg
[defaults]
inventory = inventory.ini
In the cloud, dynamic inventory plugins (like amazon.aws.aws_ec2) build the list from your account instead, grouping instances by tags.
Ad-hoc commands
For one-off jobs you don't need a playbook: ansible <hosts> -m <module> -a <arguments>.
$ ansible all -m ansible.builtin.ping # can Ansible log in and run Python?
web1 | SUCCESS => {
"changed": false,
"ping": "pong"
}
$ ansible web -a "uptime" # default module: command
web1 | CHANGED | rc=0 >>
10:42:07 up 12 days, 3:10, 0 user, load average: 0.08, 0.03, 0.01
$ ansible web -b -m ansible.builtin.apt -a "name=htop state=present" # -b = sudo
$ ansible db -m ansible.builtin.setup -a "filter=ansible_distribution*" # facts
(ping here isn't ICMP ping: it checks SSH login and Python.)
A playbook: install and run nginx
A playbook is a YAML file with one or more plays; each play maps a group of hosts to a list of tasks, run in order.
# site.yml
---
- name: Install and run nginx
hosts: web
become: true # run tasks with sudo
vars:
site_title: "DevOps practice"
tasks:
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
cache_valid_time: 3600 # refresh the package list at most once an hour
- name: Deploy the nginx site config
ansible.builtin.template:
src: templates/site.conf.j2
dest: /etc/nginx/sites-available/default
owner: root
group: root
mode: "0644"
notify: Reload nginx # trigger the handler, only if this changed
- name: Deploy the homepage
ansible.builtin.template:
src: templates/index.html.j2
dest: /var/www/html/index.html
mode: "0644"
- name: Make sure nginx is running and starts on boot
ansible.builtin.service:
name: nginx
state: started
enabled: true
handlers:
- name: Reload nginx
ansible.builtin.service:
name: nginx
state: reloaded
The templates use Jinja2: templates/index.html.j2 could contain <h1>{{ site_title }}</h1><p>Served by {{ inventory_hostname }}</p>, and each server gets its own name filled in.
$ ansible-playbook site.yml --syntax-check
$ ansible-playbook site.yml
...
PLAY RECAP *********************************************************
web1 : ok=5 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
web2 : ok=5 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
That recap is from a second run: everything is already correct, so nothing changed. On the first run you'd see changed for the tasks that did real work, and the handler running at the end.
Idempotency and handlers
Idempotent means running the same playbook once or ten times gives the same result. Modules make this work by describing a state ("nginx is present") rather than an action ("install nginx"): if it's already true, they report ok and do nothing. The raw command and shell modules can't know that, so they report changed every run. Prefer a real module, or add creates:/removes: so the command is skipped when its work is done:
# not idempotent: adds another copy of the line on every run
- name: Tune swappiness
ansible.builtin.shell: echo "vm.swappiness=10" >> /etc/sysctl.conf
# idempotent: makes sure the line exists exactly once
- name: Tune swappiness
ansible.builtin.lineinfile:
path: /etc/sysctl.conf
line: "vm.swappiness=10"
Handlers are tasks that run only when notified, and only once, at the end of the play, however many tasks notified them. So nginx is reloaded only when its config actually changed, never on a run where nothing did.
Variables, roles and dry runs
- Variables can live in the play (
vars:), ingroup_vars/web.yml(for every host in the group), inhost_vars/web1.yml, or on the command line with-e "site_title=Test", which beats everything else. Facts gathered at the start of each play, likeansible_facts['distribution'], are variables too. - Roles package tasks, handlers, templates and default variables into a reusable folder:
ansible-galaxy role init roles/nginxcreates the structure, and a play uses it withroles: [nginx]. Community roles and collections come from Ansible Galaxy. --checkis a dry run: it reports what would change without changing it. Add--diffto see the exact lines that would change in files. Note that tasks depending on earlier ones can fail in check mode (the service task can't find nginx if it wasn't really installed).--limit web1runs on one host only, which is great for trying a change on one server first.-vto-vvvvadds detail when debugging.- Secrets go in files encrypted with Ansible Vault (
ansible-vault create group_vars/web/vault.yml), and you run with--ask-vault-pass.
Common errors and fixes
- UNREACHABLE with "Permission denied (publickey)": wrong user or key. Check
ansible_userandansible_ssh_private_key_file, and thatssh [email protected]works by hand. - Host key verification failed: the server isn't in
known_hostsyet. Connect once withssh, or add it withssh-keyscan. - "Missing sudo password":
becomeneeds a password on that server. Run with-K(--ask-become-pass). - YAML errors: indentation must be spaces, and a value that starts with
{{must be quoted:dest: "{{ web_root }}/index.html". - "… is undefined": a variable is misspelled or not defined for that host.
ansible-inventory --host web1shows which variables a host gets from the inventory.