Aurora Store already has two playbooks, common.yml and webservers.yml, and it's missing the third: the database one for db1. Before writing it, it's worth stopping to understand the full anatomy of a playbook: what a file can contain, which keywords plays and tasks accept, in what order Ansible runs each section and how several playbooks are combined into a main one. In this lesson you will write a file with several plays, create dbservers.yml to install PostgreSQL on db1, reorganize the playbooks with pre_tasks and post_tasks sections and create site.yml, the entry point that configures Aurora's entire infrastructure with a single command. By the end, the playbook structure you will use until roles arrive will be set.
Contents
- Anatomy of a playbook
- Several plays in the same file
- Play keywords
- Task keywords
- Execution order
- The database playbook:
dbservers.yml pre_tasksandpost_taskson the web servers- One entry point for everything:
site.ymlwithimport_playbook - Aurora's naming and style conventions
- Anatomy of a playbook
Let's go back to the hierarchy from Lesson 3.1, now with all its pieces:
flowchart TD
F[".yml file"] --> L["List of items"]
L --> P["Play<br/>(hosts + keywords)"]
L --> I["import_playbook<br/>(another file)"]
P --> S1["pre_tasks"]
P --> S2["roles (Module 4)"]
P --> S3["tasks"]
P --> S4["post_tasks"]
P --> S5["handlers (Lesson 5.1)"]
S3 --> T["Task<br/>(module + keywords)"]
A playbook file is a list whose items can be:
- Plays: a map with
hostsand, usually, some task section. - Imports of other playbooks:
ansible.builtin.import_playbook(section 8).
Inside a play there are play keywords (name, hosts, become, vars…) and task sections (pre_tasks, tasks, post_tasks, handlers, and the roles section). Inside each section, every task combines a module with task keywords (name, become, when, register…).
- Several plays in the same file
A play can only target one host pattern. When you need to do different things on different groups, you write several plays. For example, this test file, aurora-demo.yml, prepares both kinds of server at once:
---
- name: Prepare the web servers
hosts: webservers
become: true
tasks:
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
- name: Prepare the database servers
hosts: dbservers
become: true
tasks:
- name: Install PostgreSQL
ansible.builtin.apt:
name: postgresql
state: present
update_cache: true
cache_valid_time: 3600playbook: aurora-demo.yml
play #1 (webservers): Prepare the web servers TAGS: []
tasks:
Install nginx TAGS: []
play #2 (dbservers): Prepare the database servers TAGS: []
tasks:
Install PostgreSQL TAGS: []Important rules:
- Plays run in order, one after the other: the second doesn't start until the first has finished on all its hosts.
- Each play is independent: it has its own
hosts,become, variables and fact gathering. - The final
PLAY RECAPadds up the results of all the plays for each host.
Putting all the plays in one file is convenient for small things, but in a growing project it's better to have one file per server type and a main file that brings them together. That's what you will do in this lesson. Delete the test file (you never got to run it):
- Play keywords
| Keyword | What it's for | Example | Covered in depth in |
|---|---|---|---|
name |
Description that appears in the output | name: Configure the web servers |
This lesson |
hosts |
Inventory host pattern (mandatory) | hosts: webservers, hosts: aurora:!web2 |
Lesson 2.1 |
become |
Escalate privileges for every task | become: true |
Lesson 2.4 |
become_user |
User to escalate to (root by default) |
become_user: postgres |
This lesson |
become_method |
Escalation method (sudo by default) |
become_method: sudo |
Lesson 2.3 |
gather_facts |
Whether to gather facts at the start | gather_facts: false |
Lesson 3.5 |
remote_user |
SSH user (overrides remote_user in ansible.cfg) |
remote_user: vagrant |
Lesson 2.3 |
vars |
Variables defined in the play itself | vars: {aurora_maintenance: false} |
Lesson 3.5 |
vars_files |
YAML variable files to load | vars_files: [vars/extra.yml] |
Lesson 3.5 |
pre_tasks |
Tasks that run before all the others | Update the package cache | This lesson |
tasks |
The main tasks | — | — |
post_tasks |
Tasks that run at the end | Verify the service | This lesson |
handlers |
Tasks that run only when notified | Reload nginx | Lesson 5.1 |
roles |
Roles to apply | roles: [common] |
Module 4 |
serial |
Run in batches of hosts | serial: 1 |
Lesson 5.7 |
tags |
Tags for selective execution | tags: [web] |
Lesson 5.6 |
environment |
Environment variables for the tasks | environment: {LANG: C.UTF-8} |
— |
Some of them in detail:
become and become_user. become: true turns escalation on; become_user decides to whom. If you don't set become_user, it's root. It can be set on the play and overridden on a specific task, which is exactly what you'll do with PostgreSQL: the play escalates to root, but the tasks that create users and databases run as the postgres user.
gather_facts. true by default. Turn it off in plays that don't use facts and that you want to be faster, or when the host doesn't have Python yet (in that case only the raw and script modules work):
- name: Check connectivity without gathering facts
hosts: aurora
gather_facts: false
tasks:
- name: Ping
ansible.builtin.ping:remote_user. In Aurora the SSH user is already in ansible.cfg (vagrant), so we don't write it in the plays. Use it only if a play must connect with a different user.
vars and vars_files. They let you define variables in the playbook itself. In Aurora most variables live in the inventory (group_vars/, host_vars/); in Lesson 3.5 you'll see when it makes sense to use each source.
- Task keywords
A task is a map with exactly one module and any number of keywords:
| Keyword | What it's for | Covered in depth in |
|---|---|---|
name |
Description of the task | This lesson |
| (the module) | The action: ansible.builtin.apt:, community.general.ufw:… |
Lessons 2.5 and 2.6 |
become, become_user |
Escalation for this task only | This lesson |
when |
Run only if a condition is met | Lesson 3.6 |
loop |
Repeat the task for each item in a list | Lesson 3.6 |
register |
Store the result in a variable | Lesson 3.7 |
changed_when, failed_when |
Redefine when the task counts as changed or failed | Lessons 3.7 and 5.5 |
ignore_errors |
Continue even if the task fails | Lesson 5.5 |
notify |
Notify a handler if the task changes something | Lesson 5.1 |
tags |
Tags to run only part of the playbook | Lesson 5.6 |
vars |
Variables for this task only | Lesson 3.5 |
check_mode, diff |
Force or disable simulation or the diff for this task | Lesson 3.7 |
delegate_to, run_once |
Run on another host or only once | Lesson 5.7 |
no_log |
Hide the output (sensitive data) | Lesson 5.4 |
An example that combines several of them (don't add it yet):
- name: Create the store database
community.postgresql.postgresql_db:
name: "{{ aurora_db_name }}"
state: present
become: true
become_user: postgres
when: aurora_env != 'production'
tags: [database]
notify: Record the change in the Aurora logNotice that keywords go at the same level as the module, not inside its parameters. If you indented become_user: postgres under community.postgresql.postgresql_db:, Ansible would treat it as a module parameter and fail with Unsupported parameters.
- Execution order
Within a play, Ansible always runs the sections in the same order, regardless of the order in which you write them in the file:
flowchart TD
A["Gathering Facts<br/>(if gather_facts: true)"] --> B["pre_tasks"]
B --> C["handlers notified in pre_tasks"]
C --> D["roles"]
D --> E["tasks"]
E --> F["handlers notified in roles and tasks"]
F --> G["post_tasks"]
G --> H["handlers notified in post_tasks"]
H --> I["Next play"]
And within each section, with the default strategy (linear, Lesson 1.4):
- Ansible runs task 1 on all the hosts in the play (in parallel, up to
forks). - When they have all finished task 1, it moves on to task 2, and so on.
- If a task fails on a host, that host is removed from the rest of the play; the others carry on.
- If all hosts fail, the play stops, and so do the following plays.
Handlers appear in the diagram so you know where they fit; you will study them in Lesson 5.1.
- The database playbook:
dbservers.yml
dbservers.ymlYou now have the pieces to write the playbook for db1. You will use the variables from inventory/group_vars/dbservers.yml (Lesson 2.2): aurora_db_name and aurora_db_user. Create dbservers.yml:
---
- name: Configure the Aurora Store database servers
hosts: dbservers
become: true
pre_tasks:
- name: Update the package cache if it is older than one hour
ansible.builtin.apt:
update_cache: true
cache_valid_time: 3600
tasks:
- name: Install PostgreSQL and the Ansible module dependencies
ansible.builtin.apt:
name:
- postgresql
- python3-psycopg2
- acl
state: present
- name: Ensure PostgreSQL is started and enabled
ansible.builtin.systemd_service:
name: postgresql
state: started
enabled: true
- name: Create the application user in PostgreSQL
community.postgresql.postgresql_user:
name: "{{ aurora_db_user }}"
state: present
become_user: postgres
- name: Create the store database
community.postgresql.postgresql_db:
name: "{{ aurora_db_name }}"
owner: "{{ aurora_db_user }}"
state: present
become_user: postgres
post_tasks:
- name: Check that PostgreSQL accepts connections
community.postgresql.postgresql_ping:
become_user: postgresWhat appears for the first time:
pre_tasksupdates theaptcache before any installation. Separating it from the installation task makes it clear that it's a preparatory step.name:with a list installs the three packages in a singleapttransaction, faster than three tasks.python3-psycopg2andaclare the requirements you discovered in Lesson 2.6: the library used by thecommunity.postgresqlmodules and the package that lets Ansible becomepostgreswithout permission problems.become_user: postgreson the PostgreSQL tasks: the play escalates toroot(become: true), whereas these tasks escalate topostgres, the database superuser, which connects through the local socket without a password.- The user is created before the database, because the database needs it as its owner (
owner). Task order is execution order. post_taskschecks at the end that the server accepts connections.postgresql_pingdoesn't change anything: it only queries (alwaysok).- The
aurorauser is created without a password for now. Passwords are secrets and must not be written in plain text in the repository: you will add them encrypted with Ansible Vault in Lesson 5.4.
Run it and check idempotency:
ansible-playbook dbservers.yml --syntax-check
ansible-playbook dbservers.yml
ansible-playbook dbservers.ymlFirst run:
PLAY RECAP *********************************************************************
db1 : ok=7 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0The three changes are the package installation, the user and the database (the service was already started and enabled when the package was installed, so that task shows ok; depending on the apt version and how old the cache is, the pre_tasks task may also count as a change). Second run: ok=7 changed=0. Verify with an ad hoc command:
The output shows the aurora database, owned by aurora.
pre_tasks and post_tasks on the web servers
pre_tasks and post_tasks on the web serversApply the same organization to webservers.yml: the cache update moves to pre_tasks and the installation task becomes simpler. Replace the beginning of the play with:
---
- name: Configure the Aurora Store web servers
hosts: webservers
become: true
pre_tasks:
- name: Update the package cache if it is older than one hour
ansible.builtin.apt:
update_cache: true
cache_valid_time: 3600
tasks:
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
# ... the rest of the tasks, unchanged ...What about post_tasks on the web servers? It's the natural place to verify that the website responds, but to do it properly you need to register the result of an HTTP request and wait for the service to be ready. You will add it in Lessons 3.6 and 3.7.
Run ansible-playbook webservers.yml and confirm changed=0: you have reorganized the code without changing the state of the servers. This is refactoring, and idempotency lets you check that you haven't broken anything.
- One entry point for everything:
site.yml with import_playbook
site.yml with import_playbookYou now have three playbooks. Configuring the whole infrastructure would mean launching three commands in the right order. The Ansible convention is to have a main playbook, site.yml, that imports the others:
---
# Aurora Store main playbook: configures the whole infrastructure.
# Usage: ansible-playbook site.yml [--limit <hosts>]
- name: Common configuration for all servers
ansible.builtin.import_playbook: common.yml
- name: Database servers
ansible.builtin.import_playbook: dbservers.yml
- name: Web servers
ansible.builtin.import_playbook: webservers.ymlansible.builtin.import_playbookinserts the plays from another file at that point, as if they were written there. It's an item of the playbook list, at the same level as a play, not a task.- The import is static: Ansible reads all the files before starting, so a syntax error in any of them is detected with
ansible-playbook site.yml --syntax-check. - The order reflects the dependencies: first the common configuration (time zone, basic packages), then the database and finally the website, which in Lesson 3.5 will need data from the database.
- Paths are relative to the importing file.
Run the whole infrastructure:
PLAY [Common configuration for Aurora Store servers] ***************************
...
PLAY [Configure the Aurora Store database servers] *****************************
...
PLAY [Configure the Aurora Store web servers] **********************************
...
PLAY RECAP *********************************************************************
db1 : ok=11 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
web1 : ok=16 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
web2 : ok=16 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0Notice that Gathering Facts appears once per play: each play gathers the facts of its hosts. It's a cost you'll learn to reduce in Lessons 5.8 and 9.3.
The individual playbooks still work on their own (ansible-playbook webservers.yml), and site.yml accepts --limit:
import_playbookonly imports complete playbooks. To reuse lists of tasks within a play there areimport_tasksandinclude_tasks, which you will study in Lesson 4.5 along with the difference between static import and dynamic inclusion.
Commit the work:
git add dbservers.yml webservers.yml site.yml
git commit -m "Database playbook, pre_tasks/post_tasks and site.yml"
- Aurora's naming and style conventions
With several playbooks, consistency is as important as correctness. These are the conventions aurora-infra follows from now on:
| Element | Convention | Example |
|---|---|---|
| Location | Playbooks at the root of the repository | ~/aurora-infra/webservers.yml |
| Main file | site.yml, which imports all the others |
ansible-playbook site.yml |
| Files per server type | Name of the inventory group | webservers.yml, dbservers.yml |
| Common configuration | common.yml (it will become the common role in Module 4) |
common.yml |
| Extension | .yml |
Don't mix with .yaml |
| Start of file | --- |
— |
| Play name | Verb + target, mentioning "Aurora Store" | Configure the Aurora Store web servers |
| Task name | Imperative verb, initial capital, unique within the play | Install nginx, Create the store database |
| Modules | Always with FQCN | ansible.builtin.copy |
| Parameters | Native YAML, one per line | — |
| Booleans | true / false |
become: true |
| Permissions | In quotes with a leading zero | mode: "0644" |
| Variables | Lowercase, underscores, prefix per component | aurora_, nginx_, postgresql_ |
| Indentation | 2 spaces | — |
Structure of aurora-infra at the end of the lesson:
aurora-infra/
├── ansible.cfg
├── site.yml ← entry point
├── common.yml ← all servers (aurora group)
├── dbservers.yml ← PostgreSQL on db1
├── webservers.yml ← nginx on web1 and web2
├── inventory/
│ ├── hosts.yml
│ ├── group_vars/
│ │ ├── all/aurora.yml
│ │ ├── dbservers.yml
│ │ └── webservers.yml
│ └── host_vars/
│ ├── db1.yml
│ ├── web1.yml
│ └── web2.yml
└── lab/
└── VagrantfileCommon Mistakes and Tips
ERROR! 'tasks' is not a valid attribute for a Playor similar: it's almost always a typo in a keyword (task:,pre_task:,post-tasks:) or an indentation that pushes it out of the play. Check with--syntax-check.- Task keywords inside the module's parameters:
become_user,whenorregisterindented under the module causeUnsupported parameters. They go at the level ofname. import_playbookindented inside a play or used as a task: it causes an error. It's a top-level item of the file.- Permission errors with
become_user: postgres(Failed to set permissions on the temporary files): theaclpackage is missing, which is why it's installed in the same task as PostgreSQL. - Relying on the order in which sections are written: even if you write
post_tasksbeforetasks, they run afterwards. Write them in their real order so as not to confuse anyone. - Tip: always run
ansible-playbook site.yml --syntax-checkbefore a commit; it checks all the imported playbooks in one go.
Exercises
Exercise 1: Reading the execution order
Without running it, state in what order the tasks of this play will run and on which hosts:
- name: Order exercise
hosts: webservers
post_tasks:
- name: Task C
ansible.builtin.debug:
msg: C
tasks:
- name: Task B
ansible.builtin.debug:
msg: B
pre_tasks:
- name: Task A
ansible.builtin.debug:
msg: AExercise 2: A play without facts
Create a test playbook, uptime.yml, with a play on aurora that doesn't gather facts and that shows each server's uptime with ansible.builtin.command: uptime. Run it and compare it with common.yml: which task has disappeared from the output?
Exercise 3: A test database
Add a task to dbservers.yml that creates an aurora_test database owned by {{ aurora_db_user }}. Where must it go for it to work? Run it on db1 only, using site.yml. Then remove it with state: absent and take the task out.
Solutions
Exercise 1. Gathering Facts → Task A → Task B → Task C, each one on web1 and web2 before moving on to the next. The order in which they're written doesn't matter: pre_tasks, tasks and post_tasks always run in this order.
Exercise 2.
---
- name: Check the uptime
hosts: aurora
gather_facts: false
tasks:
- name: Run uptime
ansible.builtin.command: uptimeTASK [Gathering Facts] disappears and the play is faster. With -v you see the output of uptime. The task shows up as changed because command always does; in Lesson 3.7 you will learn to fix that with changed_when.
Exercise 3. The task must go after Create the application user in PostgreSQL, because it needs the owner to exist, and with become_user: postgres:
- name: Create the test database
community.postgresql.postgresql_db:
name: aurora_test
owner: "{{ aurora_db_user }}"
state: present
become_user: postgresTo remove it, change state: present to state: absent, run it again and then delete the task from the file. This pattern (first absent, then remove the task) is the right way to remove something with Ansible: if you only delete the task, the database would still exist on the server.
Conclusion
You now know the full anatomy of a playbook: a file is a list of plays and imports; each play combines a host pattern with keywords (become, become_user, gather_facts, remote_user, vars, vars_files…) and sections that always run in the same order (pre_tasks, roles, tasks, post_tasks, with handlers in between); each task combines a module with its own keywords. You have created dbservers.yml, which installs PostgreSQL on db1 and creates the store's user and database with become_user: postgres, you have reorganized webservers.yml with pre_tasks, and you have set Aurora's structure: site.yml imports common.yml, dbservers.yml and webservers.yml, and the whole infrastructure is configured with a single command. So far, the values in the playbooks come from the inventory or are written directly in the tasks. In the next lesson, Variables and Facts, you will learn all the ways to define and use variables, how to take advantage of the information Ansible gathers from each server and how to share data between hosts, for example so that the web servers know where the database is.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
