Ansible playbooks & roles
Configure servers idempotently with playbooks.
By Invicly Tech, , in Full DevOps with Python. About 11 minutes to read.
In short
Ansible configures servers over SSH using YAML playbooks, with no agent to install. Tasks are idempotent, so running a playbook twice changes nothing the second time.
Explained simply
Ansible is a tool that sets up servers for you. Instead of logging in to ten machines and typing the same commands, you write the steps once in a YAML file and Ansible runs them on all ten over SSH.
Nothing needs to be installed on the servers except SSH and Python, which most Linux systems already have. You install Ansible only on your own machine (the control node) or in your CI.
You describe the result you want, not the commands. For example: nginx should be installed, this config file should look like this, the service should be running. If a server is already in that state, Ansible leaves it alone and reports ok instead of changed.
That property is called idempotency: running the same playbook again is safe and changes nothing. It means you can run Ansible every day to fix any server that drifted, and you can trust it on new and old machines alike.
Press Play on a diagram to walk through it one step at a time.
- inventory.ini
- [web] host groups
- SSH user and addresses
- site.yml playbook
- hosts: web
- roles: [nginx, app]
- roles/nginx
- tasks/main.yml
- handlers/main.yml
- templates/site.conf.j2
- defaults/main.yml
- 1Playbook site.yml
Which roles run on which host groups
- 2Play
hosts: web, become: true
- 3Roles
common, nginx, app
- 4Tasks and handlers
Ordered steps inside each role
- 5Modules
apt, template, service do the work on the host
In depth
Inventory, SSH access and ad-hoc commands
The inventory lists your hosts. In INI format, a [web] section lists web servers, and each line can set connection variables like ansible_host=10.0.1.10 and ansible_user=ubuntu. Groups can contain groups with [prod:children]. Shared settings go in group_vars/web.yml and host_vars/web1.yml next to the inventory. ansible-inventory -i inventory.ini --graph shows how Ansible understands it.
Ansible uses your normal SSH setup: keys, ~/.ssh/config and the SSH agent. Test connectivity with ansible all -i inventory.ini -m ping, which logs in and checks that Python works (it is not an ICMP ping).
Ad-hoc commands run one module without a playbook, useful for quick checks: ansible web -a "uptime" runs a command, and ansible web -m ansible.builtin.apt -a "name=htop state=present" --become installs a package with sudo. By default Ansible works on 5 hosts in parallel (forks = 5), which you can raise with -f or in ansible.cfg.
- ansible all -m ping tests SSH and Python
- --become runs tasks with sudo
- ansible-inventory --graph shows groups and hosts
How a playbook runs
A playbook is a list of plays; each play targets hosts and lists tasks. Ansible first gathers facts (OS, IPs, memory) from each host unless gather_facts: false. Then it runs each task on all targeted hosts before moving to the next task. For each task, it copies a small Python module to the host, runs it, and gets back JSON saying ok, changed, failed or skipped.
Handlers are special tasks. A task with notify: Reload nginx queues the handler only if that task reported changed. Queued handlers run once at the end of the play, even if notified ten times. If a later task needs the restart to have happened, add meta: flush_handlers.
At the end, the PLAY RECAP lists counts per host: ok, changed, unreachable, failed, skipped, rescued and ignored. Before touching production, use --check (dry run) with --diff to see which files would change, and --limit web1 to try one host first.
- Control node to Web server: SSH: gather facts1SSH: gather facts
- Control node to Web server: Run template module for site.conf2Run template module for site.conf
- Web server to Control node: JSON: changed, so queue Reload nginx3JSON: changed, so queue Reload nginx
- Control node to Web server: End of play: run service reload4End of play: run service reload
- Web server to Control node: JSON: changed5JSON: changed
Variables and Jinja2 templates
Variables can be defined in many places: role defaults, inventory group_vars and host_vars, the play's vars, registered results, and extra vars on the command line with -e. There are over 20 precedence levels; remember the two ends. Role defaults (defaults/main.yml) are the lowest, meant to be overridden. Extra vars (-e) are the highest and always win.
Templates are files with Jinja2 placeholders, such as server_name {{ server_name }}; inside a .j2 file. The template module renders them on the control node and copies the result, reporting changed only when the content differs. Jinja2 also gives filters, for example {{ port | default(8000) }}, and loops, like {% for host in groups['app'] %} to list backend servers in an nginx upstream.
In YAML, a value that starts with {{ must be quoted: "{{ app_dir }}/config". Facts are variables too, such as ansible_facts['distribution']. For secrets, use Ansible Vault: ansible-vault encrypt_string creates an encrypted value you can commit, decrypted at run time with --ask-vault-pass.
- Role defaults lowest, -e extra vars highest
- Quote YAML values that start with {{
- ansible-vault encrypt_string for secrets in Git
Roles and real idempotency
A role is a standard folder layout that bundles everything for one job, like nginx or app. ansible-galaxy role init roles/nginx creates tasks/, handlers/, templates/, files/, vars/, defaults/ and meta/, each with a main.yml where needed. A playbook then just lists roles: [common, nginx, app]. Ansible Galaxy shares roles and collections; collections such as community.general and amazon.aws add modules, and you install them with ansible-galaxy collection install.
Idempotency comes from modules that check before acting. apt, copy, template, user, file and service all compare current with desired state. command and shell do not: they run every time and always report changed. If you must use them, add creates: /path so the task is skipped when the file exists, or changed_when to describe what counts as a change.
The test is simple: run the playbook twice. The second run must show changed=0 on every host. Molecule automates this check for roles in CI.
- apt: name=nginx state=present
- Checks first, acts only if needed
- Second run: ok
- Works with --check
- shell: apt-get install -y nginx
- Runs every time
- Second run: changed
- Needs creates or changed_when
Learn it in 6 short steps
About 1h each. Track them with a timer in your plan.
- 1Set up an inventory and SSH access~1h
- 2Run ad-hoc commands~1h
- 3Write a playbook with tasks and handlers~1h
- 4Use variables and Jinja2 templates~1h
- 5Organise tasks into roles~1h
- 6Verify idempotency with a second run~1h
Key points
- The inventory lists hosts and groups; playbooks map groups to tasks.
- Modules like apt, copy and service describe desired state, not shell steps.
- Handlers run only when notified by a changed task, like restarting nginx.
- A second run reporting changed=0 proves the playbook is idempotent.
Key terms
Tap a card to flip it. 0/6 known
Examples
- hosts: web
become: true
vars: { server_name: example.com }
tasks:
- name: Install nginx
apt: { name: nginx, state: present, update_cache: true }
- name: Configure site
template: { src: site.conf.j2, dest: /etc/nginx/sites-enabled/default }
notify: Reload nginx
handlers:
- name: Reload nginx
service: { name: nginx, state: reloaded }Run with ansible-playbook -i inventory.ini site.yml.
Deploy the FastAPI app as a systemd service
Step 1: create a dedicated system user. Step 2: copy the code and install requirements into a virtualenv with the pip module, which is idempotent. Step 3: render a systemd unit from a template; if it changes, notify a handler. Step 4: make sure the service is enabled and started. Step 5: the handler restarts the app only when something changed. Run with ansible-playbook -i inventory.ini app.yml, then run it again and expect changed=0.
- hosts: app
become: true
tasks:
- ansible.builtin.user: { name: api, system: true }
- ansible.builtin.copy: { src: app/, dest: /opt/api/, owner: api }
notify: Restart api
- ansible.builtin.pip: { requirements: /opt/api/requirements.txt, virtualenv: /opt/api/.venv, virtualenv_command: python3 -m venv }
- ansible.builtin.template: { src: api.service.j2, dest: /etc/systemd/system/api.service }
notify: Restart api
- ansible.builtin.systemd_service: { name: api, enabled: true, state: started, daemon_reload: true }
handlers:
- name: Restart api
ansible.builtin.systemd_service: { name: api, state: restarted, daemon_reload: true }Turn a shell task into an idempotent one
Your playbook downloads a binary with shell: curl ... and the recap always says changed. Step 1: notice that the second run is not clean. Step 2: replace curl with the get_url module, which skips the download when the file already exists with the right checksum. Step 3: for a command you cannot replace, add creates so it runs only once. Step 4: run twice and confirm changed=0.
# Before: always changed
- ansible.builtin.shell: curl -L -o /usr/local/bin/tool https://example.com/tool && chmod +x /usr/local/bin/tool
# After: idempotent
- ansible.builtin.get_url:
url: https://example.com/tool
dest: /usr/local/bin/tool
mode: "0755"
- ansible.builtin.command: /usr/local/bin/tool init
args:
creates: /etc/tool/initializedQuick reference
- ansible all -i inventory.ini -m ping checks SSH login and Python on every host
- ansible-playbook site.yml --check --diff shows what would change without changing it
- --limit web1 runs on one host; -f 20 raises parallel hosts from the default 5
- Handlers run once at the end of the play, only if a notifying task changed
- command and shell always report changed; add creates or changed_when
- ansible-galaxy role init roles/nginx creates the standard role layout
- Role defaults have the lowest precedence; -e extra vars have the highest
- ansible-vault encrypt_string 'secret' --name db_password gives a value safe to commit
Common mistakes
- Using shell or command for everything, which breaks idempotency.
- Putting passwords in plain YAML instead of Ansible Vault.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write an inventory with two web servers and one database, all logging in as ubuntu, then check you can reach them and see their uptime.
- Exercise 2medium
Write a template for an nginx upstream that lists every host in the app group on port app_port (default 8000), and a task that installs it and reloads nginx only when it changes.
- Exercise 3hard
Convert a single nginx playbook into a role with defaults, a template and a handler, use it from site.yml, and prove idempotency.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does Ansible need an agent on the servers?
- No. It connects over SSH and needs Python on the managed Linux hosts. Windows hosts are managed over WinRM or SSH with PowerShell modules instead.
- Can I run Ansible from Windows?
- Not natively: the control node must be Linux, macOS or another Unix-like system. On Windows, run Ansible inside WSL.
- Ansible or Terraform?
- Use Terraform to create cloud resources and keep track of them in state. Use Ansible to configure the operating system and apps on servers. They work well together.
- What is the difference between a role and a collection?
- A role bundles tasks, handlers, templates and defaults for one job. A collection is a larger package that can contain roles, modules and plugins, such as amazon.aws, installed with ansible-galaxy collection install.