At the end of Module 8 you looked at aurora-infra and saw the problem: a dozen playbooks with very different purposes sit side by side in the root (configuring the lab, building an image, deploying to Kubernetes, creating an environment on AWS); variables live in three places (inventory/, group_vars/ next to the playbooks, and cloud/); and the staging environment only gets the common role, because all the inventory data was written with the lab in mind. A repository like this works as long as a single person who remembers everything maintains it; as soon as someone new joins, or as soon as there's a second real environment, mistakes start to happen: a lab change that ends up in production, a duplicated variable where nobody knows which value wins, a production secret that the whole team knows. In this lesson you'll reorganize aurora-infra following the structure recommended by the Ansible best practices guide: one inventory per environment (lab, staging and production), one Vault identity per environment, a clear rule about where each variable lives, the playbooks grouped in playbooks/, the full configuration of staging, and the minimum documentation a shared repository needs.
- Why reorganize now
Reorganizing a repository has a cost: moving files, reviewing paths, letting the team know. It pays to do it once the problems are visible, but before the repository has so many consumers that any move breaks something. Aurora is right at that point:
| Symptom | Consequence | What will fix it |
|---|---|---|
A single inventory/ with aurora_env: lab |
There's no way to configure staging or production with the same playbooks |
One inventory per environment (section 3) |
| "Wiring" variables (how the roles connect) mixed with lab values | Creating another environment would mean copying everything and changing what differs, without knowing what differs | Separate what's common from what's specific (section 4) |
A single Vault password (lab) |
Anyone who can run the lab could decrypt the production secrets | One Vault identity per environment (section 5) |
Twelve playbooks in the root next to ansible.cfg, ee/, ci/, terraform/… |
Hard to tell which one is the entry point; tools like ansible-lint don't recognize them by their location |
A playbooks/ directory (section 6) |
staging only gets common |
What you test in staging doesn't resemble what you deploy |
Full configuration (section 8) |
| No documentation in the root | Every new person depends on someone explaining the repository to them | README.md and CHANGELOG.md (section 13) |
Before you start. Work on a branch (
git switch -c reorganization) and don't merge it until the lab reportschangedonly where you expect it (you'll see this in section 7.6). A well-executed reorganization changes nothing on the servers: it only changes where each thing lives in the repository.
- The recommended structure and the one Aurora adopts
The Ansible best practices guide ("Sample Ansible setup") proposes two directory layouts:
- Basic layout: playbooks in the root, a single inventory (
productionandstagingas files) andgroup_vars//host_vars/in the root. It's the one Aurora has followed so far. - Alternative layout: an
inventories/directory with one subdirectory per environment, each with its own hosts file and its owngroup_vars/andhost_vars/. It's recommended when the environments have little data in common or when you need to strictly separate who can touch each one.
Aurora adopts the alternative layout, with two decisions of its own that you'll justify in the following sections: the variables common to all environments live next to the playbooks (in playbooks/group_vars/), and the playbooks are grouped in playbooks/. The overall layout looks like this:
flowchart TB
subgraph repo["aurora-infra"]
cfg["ansible.cfg<br/>(default inventory: lab)"]
subgraph inv["inventories/"]
lab["lab/<br/>hosts + lab data"]
stg["staging/<br/>hosts (generated) + staging data"]
prd["production/<br/>hosts + production data"]
end
subgraph pb["playbooks/"]
site["site.yml and the other playbooks"]
gv["group_vars/<br/>common wiring + vault per environment"]
end
roles["roles/ (our own)<br/>galaxy_roles/ (external)"]
end
lab --> site
stg --> site
prd --> site
gv --> site
roles --> site
The central idea: the same playbooks and the same roles are applied to any environment; the only thing that changes is the inventory you choose with -i.
- Per-environment inventories
3.1. What an environment is for Aurora
| Environment | Where it is | What it's for | Who runs it |
|---|---|---|---|
lab |
Vagrant VMs on your computer (lb1, web1, web2, db1, api1) and the k3s on awx1 |
Developing and testing changes; it's the course's "live" environment | Anyone on the team, from their terminal or from AWX |
staging |
AWS, eu-south-2, created and destroyed with OpenTofu (Lesson 8.5) |
Rehearsing changes in an environment similar to production before releasing them | The Operations team and CI |
production |
The store's data center, private network 10.20.1.0/24 (fictitious) |
Serving customers | Only AWX, with approval |
In the course, production is a paper inventory: its addresses are fictitious and you won't be able to connect to them. It will let you check that the structure works (ansible-inventory, --list-hosts, --syntax-check) and reason as you would in a real company.
3.2. One group per environment
Each inventory declares a group with the name of the environment (lab, staging, production) that contains all its hosts. It looks redundant (inside inventories/lab/ all the hosts belong to the lab), but it has two very specific uses:
- It lets you load variable files only for one environment from outside the inventory (you'll need this for Vault in section 5).
- It records the environment in
group_namesand, therefore, in the local facts published by thecommonrole (groups=aurora,lab,webservers): when you log into a server you know which environment it belongs to.
inventories/lab/hosts.yml (it's your old inventory/hosts.yml with the lab level added):
---
# Inventory of the lab environment: Vagrant lab (Lesson 1.3) and the k3s cluster on awx1.
all:
children:
lab:
children:
aurora: # All of the store's servers
children:
loadbalancers:
hosts:
lb1:
ansible_host: 192.168.56.10
webservers:
hosts:
web1:
ansible_host: 192.168.56.11
web2:
ansible_host: 192.168.56.12
dbservers:
hosts:
db1:
ansible_host: 192.168.56.21
apiservers:
hosts:
api1:
ansible_host: 192.168.56.41
k8s_clusters: # Kubernetes clusters (managed through their API, no SSH)
hosts:
k3s-lab:The functional groups (aurora, webservers, dbservers…) have the same name in every environment: the playbooks say hosts: webservers and neither know nor care which environment they're in.
3.3. How the environment is chosen
ansible-playbook playbooks/site.yml # lab (default inventory)
ansible-playbook -i inventories/staging playbooks/site.yml # staging
ansible-playbook -i inventories/production playbooks/site.yml # production (in practice, only AWX)In ansible.cfg, the line inventory = inventory becomes:
It's a security decision: if someone forgets -i, the playbook runs against the lab, never against production. Production must always be requested explicitly.
Why not a single inventory with
lab,stagingandproductiongroups? It would work technically, but a badly written pattern (hosts: webserverswithout--limit) would touch all three environments at once. With separate inventories, a command can only see the hosts of one environment.
- Where each variable lives: the inventory or next to the playbooks
4.1. Two kinds of variables
If you go through inventory/group_vars/, you'll see it contains two very different kinds of data:
| Kind | Examples | Does it change between environments? |
|---|---|---|
| Wiring: how the roles connect to each other and to Aurora | nginx_root: "{{ aurora_app_web_root }}", aurora_app_db_host: "{{ hostvars[...] }}", postgresql_hba_clients, nginx_upstream_servers, common_env: "{{ aurora_env }}", the list of team users |
No |
| Environment data: sizes, versions, names and addresses | aurora_env, aurora_domain, aurora_app_version, nginx_worker_connections, postgresql_shared_buffers, each web server's aurora_lb_weight |
Yes |
If you copy the wiring into three inventories, the day you change an expression you'll have to remember to change it three times. If you put the environment data in a common place, you won't be able to have different values. The solution is to separate them.
4.2. Aurora's rule
- Wiring and common data →
playbooks/group_vars/, next to the playbooks. Ansible loads those files for any inventory. - Environment data →
inventories/<environment>/group_vars/andhost_vars/. - One variable, one place. Never define the same variable in both locations.
The third rule isn't cosmetic. Remember precedence (Lesson 3.5): group_vars next to the playbook win over the inventory group_vars at the same level. If nginx_worker_connections were in playbooks/group_vars/webservers.yml and also in inventories/production/group_vars/webservers.yml, the production value would be silently ignored:
| Level (lowest to highest) | Location |
|---|---|
| 4 | inventories/<environment>/group_vars/all/ |
| 5 | playbooks/group_vars/all/ |
| 6 | inventories/<environment>/group_vars/<group> |
| 7 | playbooks/group_vars/<group> |
| 9 | inventories/<environment>/host_vars/<host> |
| 10 | playbooks/host_vars/<host> (Aurora doesn't use it) |
There's a useful exception: the inventory's host_vars (level 9) win over all group_vars. That's why a common default value can go in playbooks/group_vars/ and be adjusted per host in the inventory. You'll take advantage of this with aurora_lb_weight: it will be 1 for all the web servers and web1 will raise it to 2 in its host_vars.
4.3. This reshapes the Module 7 decision
In Lesson 7.4 you moved the vault.yml files to group_vars/ next to the playbooks because AWX imports the repository inventory without the Vault password: an encrypted file inside inventory/ broke the sync. That decision is still valid and now it's generalized: playbooks/group_vars/ is the place for everything that must not be imported as inventory (secrets) and for everything that is common (wiring). The consequences, which you already knew, still apply:
- AWX imports
inventories/lab(only hosts and environment data) and loadsplaybooks/group_vars/when running each job, because the playbook is inplaybooks/. - Commands that don't run a playbook (
ansiblead hoc,ansible-inventory,ansible-console) need--playbook-dir playbooksto see those variables.
What if I put
playbook_dir = playbooksinansible.cfg? That option exists and would save you typing--playbook-dir, but it would also make the AWX inventory sync (which runsansible-inventorywith the project'sansible.cfg) loadplaybooks/group_vars/, including the encrypted files, and it would fail again as in Lesson 7.4. Aurora doesn't use it; if you write a lot of ad hoc commands, create an alias in your~/.bashrc:alias aurora-adhoc='ansible --playbook-dir playbooks'.
4.4. The specific split
| File | Contents |
|---|---|
playbooks/group_vars/all/aurora.yml |
aurora_admin_email, aurora_db_password (reference to the vault) |
playbooks/group_vars/all/common.yml |
Parameters of the common role (unchanged) |
playbooks/group_vars/all/team.yml |
common_users (the team is the same in every environment) |
playbooks/group_vars/all/monitoring.yml |
node_exporter agent (unchanged) |
playbooks/group_vars/all/catalog.yml |
Image and products of the catalog API (unchanged) |
playbooks/group_vars/webservers.yml |
Wiring of nginx and aurora_app, default weight |
playbooks/group_vars/loadbalancers.yml |
Load balancer wiring |
playbooks/group_vars/dbservers.yml |
Wiring of postgresql (users, databases, access) |
playbooks/group_vars/apiservers.yml |
Source and port of the catalog API |
playbooks/group_vars/<environment>/vault.yml |
Secrets of each environment (section 5) |
inventories/<environment>/group_vars/all/aurora.yml |
aurora_env, aurora_domain, aurora_internal_ip |
inventories/<environment>/group_vars/<group>.yml |
Versions and sizes for the environment |
inventories/<environment>/host_vars/<host>.yml |
Per-host adjustments (weights, PostgreSQL memory…) |
4.5. A new variable: aurora_internal_ip
In the lab, the address Ansible connects to (ansible_host) is the same one the servers use to talk to each other (private network 192.168.56.0/24). Not on AWS: Ansible gets in through the public IP, but the web server must talk to PostgreSQL through the private IP (the aurora-staging-db security group only opens port 5432 to the web servers, over the internal network). Until now the wiring used ansible_host in four places:
aurora_app_db_host(which address the web server connects to),postgresql_listen_addresses(which address PostgreSQL listens on),postgresql_hba_clients(which addresses the web servers are accepted from),nginx_upstream_serversand the load balancer tasks inwebservers.yml.
They all switch to aurora_internal_ip, a variable that each environment defines: in the lab and in production it's "{{ ansible_host }}"; in staging, the private IP returned by Terraform. The wiring doesn't change from one environment to another; the data does.
4.6. The variable files, one by one
Common variables, playbooks/group_vars/all/aurora.yml:
---
# Aurora Store data common to all environments.
aurora_admin_email: [email protected]
# The real value is in the environment's vault: playbooks/group_vars/<environment>/vault.yml
aurora_db_password: "{{ vault_aurora_db_password }}"Lab data, inventories/lab/group_vars/all/aurora.yml:
---
# Data for the lab environment. Only what changes from one environment to another goes here.
aurora_env: lab
aurora_domain: aurora-store.example
# Address the servers use to talk to each other.
# In the lab it's the same as the connection address.
aurora_internal_ip: "{{ ansible_host }}"Web server wiring, playbooks/group_vars/webservers.yml:
---
# Web servers: wiring of the nginx and aurora_app roles (the same in every environment).
# The data that changes per environment is in inventories/<environment>/group_vars/webservers.yml.
# The store's database server (the first one in the group).
aurora_db_server: "{{ groups['dbservers'][0] }}"
# Weight in the load balancer; adjusted per host in inventories/<environment>/host_vars/.
aurora_lb_weight: 1
# aurora_app role parameters
aurora_app_web_root: /var/www/aurora
aurora_app_domain: "{{ aurora_domain }}"
# aurora_app_static_pages: (the robots.txt and status.html block, exactly as it was)
aurora_app_db_host: "{{ hostvars[aurora_db_server]['aurora_internal_ip'] }}"
aurora_app_db_port: "{{ hostvars[aurora_db_server]['postgresql_port'] }}"
aurora_app_db_name: "{{ hostvars[aurora_db_server]['aurora_db_name'] }}"
aurora_app_db_user: "{{ hostvars[aurora_db_server]['aurora_db_user'] }}"
aurora_app_db_password: "{{ aurora_db_password }}"
aurora_app_check_url: "http://localhost:{{ nginx_port }}/"
# nginx role parameters
nginx_port: 80
nginx_site_name: aurora
nginx_server_name: "{{ aurora_domain }} www.{{ aurora_domain }}"
nginx_root: "{{ aurora_app_web_root }}"
nginx_firewall_enabled: trueMove the aurora_app_static_pages block without touching it (where the comment is). Data for the lab web servers, inventories/lab/group_vars/webservers.yml:
---
# Web servers of the lab environment: only what depends on the environment.
aurora_app_version: "1.4.0"
nginx_worker_connections: 1024Load balancer wiring, playbooks/group_vars/loadbalancers.yml:
---
# Load balancers: wiring of the nginx role in load balancer mode.
nginx_port: 80
nginx_site_name: aurora
nginx_server_name: "{{ aurora_domain }} www.{{ aurora_domain }}"
nginx_firewall_enabled: true
# Web servers the traffic is distributed to: {internal IP: weight}.
nginx_upstream_servers: >-
{{ dict(groups['webservers']
| map('extract', hostvars, 'aurora_internal_ip')
| zip(groups['webservers'] | map('extract', hostvars, 'aurora_lb_weight'))) }}
# nginx port on the web servers.
nginx_upstream_port: "{{ hostvars[groups['webservers'][0]]['nginx_port'] }}"And inventories/lab/group_vars/loadbalancers.yml with only nginx_worker_connections: 1024.
Database wiring, playbooks/group_vars/dbservers.yml (formerly inventory/group_vars/dbservers/vars.yml):
---
# Database servers: wiring of the postgresql role (the same in every environment).
aurora_db_name: aurora
aurora_db_user: aurora
postgresql_version: 16
postgresql_port: 5432
postgresql_listen_addresses: "localhost,{{ aurora_internal_ip }}"
postgresql_conf_name: aurora
postgresql_users:
- name: "{{ aurora_db_user }}"
password: "{{ aurora_db_password }}"
- name: aurora_reporting
password: "{{ vault_aurora_reporting_db_password }}"
postgresql_databases:
- name: "{{ aurora_db_name }}"
owner: "{{ aurora_db_user }}"
- name: aurora_analytics
owner: aurora_reporting
# The web servers connect over the internal network.
postgresql_hba_clients: "{{ groups['webservers'] | map('extract', hostvars, 'aurora_internal_ip') | list }}"
postgresql_hba_database: "{{ aurora_db_name }}"
postgresql_hba_user: "{{ aurora_db_user }}"inventories/lab/group_vars/dbservers.yml:
---
# Database of the lab environment: sizing.
postgresql_max_connections: 100
postgresql_shared_buffers: 128MB(db1 keeps postgresql_shared_buffers: 512MB in inventories/lab/host_vars/db1.yml, which wins over both.)
Container servers, playbooks/group_vars/apiservers.yml:
---
# Catalog API: code source and port (the same in every environment).
aurora_catalog_source: http://git.aurora-store.example/ops/aurora-catalog.git
aurora_catalog_port: 8080inventories/lab/group_vars/apiservers.yml:
---
# Container servers of the lab environment.
aurora_catalog_version: "1.0.0"
docker_insecure_registries:
- registry.aurora-store.example:5000
# Lab ONLY: belonging to the docker group is equivalent to being root (Lesson 9.2).
docker_users:
- vagrantk8s_clusters.yml and the host_vars (web1, web2, db1, k3s-lab) move unchanged to inventories/lab/: the cluster only exists in the lab.
- One Vault identity per environment
5.1. The problem with a single password
With a single vault.yml encrypted with the lab identity, anyone who can run the lab can decrypt all the repository's secrets. Once the production ones show up, that's unacceptable. In Lesson 5.4 you labeled the identity lab precisely for this moment.
5.2. One vault per environment, selected by the environment group
Each environment has its own secrets file, encrypted with its own identity:
| File | Identity | Password file (outside the repo) | Who has it |
|---|---|---|---|
playbooks/group_vars/lab/vault.yml |
lab |
~/.ansible/vault/aurora-lab.pass |
The whole team |
playbooks/group_vars/staging/vault.yml |
staging |
~/.ansible/vault/aurora-staging.pass |
Operations and CI |
playbooks/group_vars/production/vault.yml |
production |
Only in AWX (credential) and in the password manager | Those responsible for production |
The trick is in the directory name: group_vars/lab/ is loaded for the hosts in the lab group. When you run with -i inventories/lab, the staging group doesn't exist, so Ansible doesn't even open group_vars/staging/vault.yml and doesn't need its password. Each person only needs the passwords of the environments they work with.
The lab's two encrypted files (group_vars/all/vault.yml and group_vars/dbservers/vault.yml) are merged into one. Both passwords become visible to all the hosts in the environment (previously only the dbservers hosts could see the reporting one); it's a small price to pay for a single file per environment, and the vault_ variables are still never printed thanks to no_log.
5.3. The passwords for the new identities
Generate the staging and production passwords the same way you generated the lab one in Lesson 5.4 (32 random characters, 0600 file, 0700 directory, a copy in the password manager):
for env in staging production; do
ansible localhost -m ansible.builtin.copy \
-a "content={{ lookup('ansible.builtin.password', '/dev/null', length=32, chars=['ascii_letters', 'digits']) }} dest=~/.ansible/vault/aurora-${env}.pass mode=0600"
doneIn a real company, you wouldn't have the production password on your laptop: the person in charge would generate it, store it in the team's password manager and load it into AWX. In the lab you create it yourself so you can practice the encryption.
Update your ~/.bashrc (replace the line from Lesson 7.3) with the identities you do use every day:
export ANSIBLE_VAULT_IDENTITY_LIST=lab@~/.ansible/vault/aurora-lab.pass,staging@~/.ansible/vault/aurora-staging.passThe production one isn't in the list: if you ever need it from the terminal (an emergency), you ask for it with --vault-id production@prompt. Don't include files you don't have in the list: Ansible would fail at startup because it couldn't find them.
5.4. Creating the files
The lab one comes from the two you already have (you'll do it in section 7). The staging and production ones are created with their identity:
Contents (values different from the lab ones; generate them as in Lesson 5.3):
---
vault_aurora_db_password: <new 24-character password>
vault_aurora_reporting_db_password: <a different one>Repeat with --encrypt-vault-id production --vault-id production@~/.ansible/vault/aurora-production.pass for playbooks/group_vars/production/vault.yml. Check the headers:
==> playbooks/group_vars/lab/vault.yml <== $ANSIBLE_VAULT;1.2;AES256;lab ==> playbooks/group_vars/production/vault.yml <== $ANSIBLE_VAULT;1.2;AES256;production ==> playbooks/group_vars/staging/vault.yml <== $ANSIBLE_VAULT;1.2;AES256;staging
The plaintext label in the header lets Ansible pick the right password directly.
- The playbooks in
playbooks/
playbooks/6.1. The decision
| Criterion | Playbooks in the root (until now) | Playbooks in playbooks/ |
|---|---|---|
| Finding the entry point | Mixed in with ansible.cfg, ee/, ci/, terraform/… |
A single place, with site.yml as the entry point |
roles/ next to the playbook |
Automatic | They must be found through roles_path (you already have it) |
| Common variables and vaults | group_vars/ in the root, easy to confuse with the inventory |
playbooks/group_vars/, clearly "the playbook's" |
ansible-lint |
Detects playbooks by their content | Recognizes playbooks/*.yml as playbooks by their path |
| Paths in AWX and CI | site.yml |
playbooks/site.yml (a one-time change) |
Aurora moves to playbooks/. The main drawback, that the roles are no longer "right next to them", doesn't affect Aurora: since Module 6 roles have been looked up with roles_path = galaxy_roles:roles in ansible.cfg, and Ansible resolves relative paths in ansible.cfg relative to the configuration file itself, not relative to the playbook. The same goes for collections_path = collections.
In AWX. AWX defines its own
ANSIBLE_ROLES_PATHfor the roles it installs fromroles/requirements.yml, but it adds theroles_pathfrom the project'sansible.cfgto that list, soroles/is still found. Check it in the first job after the migration (section 10): if some version didn't do this, you'd see "the role 'common' was not found", and the classic fix is a symbolic linkplaybooks/roles -> ../roles.
6.2. What moves and what gets renamed
| Before (root) | After |
|---|---|
site.yml, common.yml, dbservers.yml, loadbalancers.yml, webservers.yml, apiservers.yml, monitoring.yml, upgrade.yml, catalog-image.yml, kubernetes.yml |
playbooks/ (same name) |
staging-terraform.yml |
playbooks/staging-provision.yml (rewritten, section 8) |
staging-configure.yml |
Removed: staging gets the full site.yml |
cloud/aws-staging.yml |
playbooks/vars/aws-staging.yml |
group_vars/ (vaults) |
playbooks/group_vars/<environment>/vault.yml |
inventory/ |
inventories/lab/ + playbooks/group_vars/ |
Why playbooks/vars/aws-staging.yml and not inventories/staging/? Because those variables are used by a play on localhost (which doesn't belong to any inventory group) and, above all, because every file inside an inventory directory is read as an inventory: an aws-staging.yml there would produce parsing warnings or errors.
- The migration step by step
7.1. Moving without losing history
With git mv, Git keeps the history of each file. From ~/aurora-infra, on the reorganization branch:
git switch -c reorganization
# 1. Lab inventory
mkdir -p inventories playbooks/group_vars/all playbooks/vars playbooks/templates
git mv inventory inventories/lab
# 2. Playbooks
git mv site.yml common.yml dbservers.yml loadbalancers.yml webservers.yml \
apiservers.yml monitoring.yml upgrade.yml catalog-image.yml kubernetes.yml playbooks/
git mv staging-terraform.yml playbooks/staging-provision.yml
git rm -q staging-configure.yml
git mv cloud/aws-staging.yml playbooks/vars/aws-staging.yml
# 3. Common variables: from the inventory to next to the playbooks
git mv inventories/lab/group_vars/all/common.yml inventories/lab/group_vars/all/team.yml \
inventories/lab/group_vars/all/monitoring.yml inventories/lab/group_vars/all/catalog.yml \
playbooks/group_vars/all/
git mv inventories/lab/group_vars/dbservers/vars.yml playbooks/group_vars/dbservers.yml
git mv inventories/lab/group_vars/webservers.yml playbooks/group_vars/webservers.yml
git mv inventories/lab/group_vars/loadbalancers.yml playbooks/group_vars/loadbalancers.yml
git mv inventories/lab/group_vars/apiservers.yml playbooks/group_vars/apiservers.yml
# 4. Lab vault
mkdir -p playbooks/group_vars/lab
git mv group_vars/all/vault.yml playbooks/group_vars/lab/vault.ymlWhat's left to do by hand (editing):
- Separate what belongs to the environment: create
inventories/lab/group_vars/{webservers,loadbalancers,dbservers,apiservers}.ymlwith the data from section 4.6 and remove it from their counterparts inplaybooks/group_vars/. - Split
aurora.yml:aurora_envandaurora_domainstay ininventories/lab/group_vars/all/aurora.yml(plusaurora_internal_ip); createplaybooks/group_vars/all/aurora.ymlwithaurora_admin_emailandaurora_db_password. - Merge the vaults: copy the reporting secret to the lab vault and remove the old file:
ansible-vault view group_vars/dbservers/vault.yml # note down the value (don't paste it anywhere else)
ansible-vault edit playbooks/group_vars/lab/vault.yml # add vault_aurora_reporting_db_password
git rm -q group_vars/dbservers/vault.ymlansible_host→aurora_internal_ipin the wiring (section 4.6) and in the twoansible.builtin.replacetasks inplaybooks/webservers.ymlthat take the web server out of the load balancer and put it back in, because they look for the web server's internal address in the load balancer configuration:
regexp: '^(\s*server {{ hostvars[inventory_hostname]["aurora_internal_ip"] | regex_escape }}:\d+ weight=\d+);$'The "Check the store through the load balancer" task keeps hostvars[item]['ansible_host']: it runs on your computer (delegate_to: localhost) and must use the address your computer uses to reach the load balancer.
ansible.cfg:inventory = inventories/lab..gitignore: add/inventories/staging/hosts-terraform.yml(section 8).- Header of
playbooks/site.yml: update the usage comment (the rest doesn't change, because theimport_playbookpaths are relative tosite.ymlitself):
---
# Aurora Store entry point: applies the full configuration to ONE environment.
# ansible-playbook playbooks/site.yml -> lab (default)
# ansible-playbook -i inventories/staging playbooks/site.yml -> staging
# ansible-playbook -i inventories/production playbooks/site.yml -> production (AWX only)playbooks/vars/aws-staging.yml: the header comment and the path to the Terraform project, which is now relative to a different directory. Thecommunity.general.terraformmodule resolvesproject_pathrelative to the working directory; so as not to depend on where it's launched from, useplaybook_dir:
7.2. Checking that nothing has been duplicated
The "one variable, one place" rule can be verified with a single command: list the names defined on both sides and show the ones that match.
comm -12 \
<(grep -rhoE '^[a-z0-9_]+:' playbooks/group_vars | sort -u) \
<(grep -rhoE '^[a-z0-9_]+:' inventories/lab/group_vars | sort -u)grep -rhoE '^[a-z0-9_]+:'extracts the top-level keys of each YAML file, without the file name (-h) and only the match (-o).sort -usorts them without repeats;comm -12shows only the lines common to both lists.
The output must be empty. (The encrypted files contribute nothing: their content isn't readable YAML. And the host_vars are deliberately not checked: they're allowed to repeat a group variable to adjust it per host.)
7.3. Checking the inventory
@all: |--@ungrouped: |--@lab: | |--@aurora: | | |--@loadbalancers: | | | |--lb1 | | |--@webservers: | | | |--web1 | | | |--web2 | | |--@dbservers: | | | |--db1 | | |--@apiservers: | | | |--api1 | |--@k8s_clusters: | | |--k3s-lab
And a host's variables, now with --playbook-dir (without it, the common ones would be missing):
ansible-inventory --playbook-dir playbooks --host web1 | grep -E 'aurora_(env|internal_ip|app_version|lb_weight)'
ansible --playbook-dir playbooks lb1 -m ansible.builtin.debug -a "var=nginx_upstream_servers"The same dictionary as in Lesson 5.7: web1 keeps its weight of 2 from host_vars and web2 takes the common 1.
7.4. Checking the syntax of all the playbooks
7.5. Installing the dependencies (unchanged)
roles/requirements.yml and collections/requirements.yml haven't moved, and galaxy_roles/ and collections/ are resolved from ansible.cfg. There's nothing to reinstall.
7.6. The moment of truth: --check --diff
Expect a single change per server, and it's correct:
TASK [common : Publish the local facts] **************************************** --- before: /etc/ansible/facts.d/aurora.fact +++ after: /home/student/.ansible/tmp/.../facts.fact.j2 @@ -2,5 +2,5 @@ env=lab domain=aurora-store.example -groups=aurora,webservers +groups=aurora,lab,webservers managed_by=aurora-infra changed: [web1]
The groups local fact is computed from group_names, and the hosts now also belong to the lab group. Any other change indicates a migration mistake: a variable that hasn't been moved, a value that changed when it was split out, or an expression with aurora_internal_ip written wrong. With a clean output, apply and repeat:
ansible-playbook playbooks/site.yml # changed only in "Publish the local facts"
ansible-playbook playbooks/site.yml # changed=0 on every host
ansible-playbook playbooks/kubernetes.yml # changed=0Commit (still on the branch):
git add -A
git commit -m "Reorganization: per-environment inventories, playbooks/ and common variables next to the playbooks"
- The
staging environment, complete
staging environment, complete8.1. The approach
Since Lesson 8.5, the staging environment has been created with OpenTofu and configured only with common. Now, with per-environment inventories, it can receive exactly the same as the lab: site.yml. One question remains: the staging servers are created and destroyed frequently and their addresses change every time, so they can't be written by hand in hosts.yml.
Aurora's solution combines the two patterns from Lesson 8.5:
staging-provision.ymlruns Terraform withcommunity.general.terraform(pattern B, as before).- With the
serversoutput, it generates an inventory file,inventories/staging/hosts-terraform.yml(the idea behind pattern A, but produced by the playbook itself). - It reloads the inventory (
meta: refresh_inventory) and appliessite.yml.
The generated file isn't versioned: the IPs change every time the environment is recreated and add nothing to the history. As long as it exists, you can run any playbook against staging from your terminal (-i inventories/staging). In Lesson 10.2 you'll replace it with a dynamic inventory, which queries AWS on every run and doesn't need a generated file.
flowchart LR
A["staging-provision.yml<br/>(localhost)"] -->|"tofu apply"| B["AWS: VPC, SG,<br/>2 web + 1 db"]
B -->|"servers output"| A
A -->|"template"| C["inventories/staging/<br/>hosts-terraform.yml"]
C -->|"refresh_inventory"| D["site.yml<br/>(common, postgresql, nginx,<br/>aurora_app, node_exporter)"]
E["inventories/staging/<br/>hosts.yml + group_vars"] --> D
F["playbooks/group_vars/<br/>(wiring + staging vault)"] --> D
8.2. The staging inventory
inventories/staging/hosts.yml (versioned) declares only the structure of the groups:
---
# staging environment (AWS, Lesson 8.5). This file only declares the groups.
# The servers are in hosts-terraform.yml, generated by playbooks/staging-provision.yml
# (not versioned: the addresses change every time the environment is recreated).
all:
children:
staging:
children:
aurora:
children:
loadbalancers: # staging has no load balancer
webservers:
dbservers:
apiservers: # nor a container serverHaving the empty loadbalancers and apiservers groups is important: webservers.yml iterates over groups['loadbalancers'] to take each web server out of the load balancer and put it back. With the group empty, the loop does nothing; with the group missing, the expression would fail.
The template that generates the hosts, playbooks/templates/staging-hosts.yml.j2:
---
# {{ ansible_managed }}
# Generated by playbooks/staging-provision.yml from the Terraform "servers" output.
all:
children:
staging:
children:
aurora:
children:
{% for group, role in [('webservers', 'web'), ('dbservers', 'db')] %}
{{ group }}:
hosts:
{% for server in aurora_staging_servers | selectattr('role', 'equalto', role) %}
{{ server.name }}:
ansible_host: {{ server.public_ip }}
aurora_internal_ip: {{ server.private_ip }}
{% endfor %}
{% endfor %}- The outer loop iterates over pairs (inventory group, role in Terraform). That way, a new role in Terraform only requires adding a pair.
selectattr('role', 'equalto', role)filters theserverslist (the "contract" with Terraform from Lesson 8.5:name,role,public_ip,private_ip).- Each host gets its public IP to connect to and its private IP as
aurora_internal_ip. - The
{% %}tags in column 0 follow Aurora's convention (Lesson 5.2) and leave no blank lines thanks totrim_blocks.
An example of the result:
8.3. The staging data
inventories/staging/group_vars/all/aurora.yml:
---
# Data for the staging environment (AWS).
aurora_env: staging
aurora_domain: staging.aurora-store.example
# aurora_internal_ip: each host defines it in hosts-terraform.yml (private IP in the VPC).inventories/staging/group_vars/all/connection.yml:
---
# Connection to the AWS instances (Canonical's Ubuntu image).
ansible_user: ubuntu
ansible_ssh_private_key_file: ~/.ssh/aurora_staging_ed25519
# The instances are new every time they're recreated: their key is accepted the first time
# and stored in a dedicated known_hosts file, which is deleted when the environment is destroyed.
ansible_ssh_common_args: -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=~/.ssh/known_hosts_aurora_stagingThe inventory's ansible_user and ansible_ssh_private_key_file win over remote_user and private_key_file in ansible.cfg, which keep the lab values. The host key policy is reviewed in Lesson 9.2.
inventories/staging/group_vars/webservers.yml and dbservers.yml:
---
# staging web servers. New versions are released here before production.
aurora_app_version: "1.4.0"
nginx_worker_connections: 768---
# staging database (t3.micro, 1 GB of RAM).
postgresql_max_connections: 50
postgresql_shared_buffers: 128MB8.4. The staging-provision.yml playbook
---
# Provisions (OpenTofu/Terraform) and configures (site.yml) the Aurora Store staging environment.
# Create or update:
# ansible-playbook -i inventories/staging playbooks/staging-provision.yml
# Destroy:
# ansible-playbook -i inventories/staging playbooks/staging-provision.yml \
# -e aurora_staging_state=absent -e confirm=aurora-staging
# Creates billable resources on AWS! Requirements: tofu, credentials (AWS_PROFILE)
# and the "staging" Vault identity.
- name: Provision the Aurora Store staging environment with Terraform
hosts: localhost
connection: local
gather_facts: false
vars_files:
- vars/aws-staging.yml
vars:
aurora_staging_state: present
aurora_staging_hosts_file: "{{ playbook_dir }}/../inventories/staging/hosts-terraform.yml"
tasks:
- name: Check that the staging inventory is being used
ansible.builtin.assert:
that: "'staging' in groups"
fail_msg: "This playbook must be run with -i inventories/staging"
- name: Require confirmation to destroy
ansible.builtin.assert:
that: confirm | default('') == aurora_staging_name
fail_msg: "To destroy the environment, add -e confirm={{ aurora_staging_name }}"
when: aurora_staging_state == 'absent'
- name: Apply the environment's Terraform project
community.general.terraform:
project_path: "{{ aurora_staging_tf_project }}"
binary_path: "{{ aurora_staging_tf_binary }}"
state: "{{ aurora_staging_state }}"
force_init: true
variables:
region: "{{ aurora_staging_region }}"
az: "{{ aurora_staging_az }}"
vpc_cidr: "{{ aurora_staging_vpc_cidr }}"
subnet_cidr: "{{ aurora_staging_subnet_cidr }}"
admin_cidr: "{{ aurora_staging_admin_cidr }}"
instance_type: "{{ aurora_staging_instance_type }}"
web_count: "{{ aurora_staging_web_count }}"
db_count: "{{ aurora_staging_db_count }}"
ssh_public_key_file: "{{ aurora_staging_ssh_key }}.pub"
register: aurora_staging_tf
- name: Generate the inventory of the servers created
ansible.builtin.template:
src: staging-hosts.yml.j2
dest: "{{ aurora_staging_hosts_file }}"
mode: "0644"
vars:
aurora_staging_servers: "{{ aurora_staging_tf.outputs.servers.value | default([]) }}"
when: aurora_staging_state == 'present'
- name: Delete the generated inventory and the known host keys
ansible.builtin.file:
path: "{{ item }}"
state: absent
loop:
- "{{ aurora_staging_hosts_file }}"
- ~/.ssh/known_hosts_aurora_staging
when: aurora_staging_state == 'absent'
- name: Stop here if the environment has been destroyed
ansible.builtin.meta: end_playbook
when: aurora_staging_state == 'absent'
- name: Reload the inventory with the new servers
ansible.builtin.meta: refresh_inventory
- name: Wait for the staging servers to be ready
hosts: staging
gather_facts: false
become: true
tasks:
- name: Wait for the servers to accept SSH connections
ansible.builtin.wait_for_connection:
timeout: 300
- name: Wait for cloud-init to finish booting
ansible.builtin.command:
cmd: cloud-init status --wait
changed_when: false
- name: Apply the full Aurora Store configuration
ansible.builtin.import_playbook: site.ymlWhat's new compared to Lesson 8.5:
- The inventory guard.
ansible.cfgpoints to the lab: if someone forgot-i inventories/staging,refresh_inventorywould reload the lab inventory andsite.ymlwould be applied there with the AWS data. The first task prevents this by checking that thestaginggroup exists. template+refresh_inventoryinstead ofadd_host: the hosts end up in a file that outlives the run, so afterwards you can launchsite.yml,upgrade.ymlor an ad hoc command againststagingwithout provisioning again.meta: end_playbookwhen destroying: there's no point continuing with plays that no longer have hosts.import_playbook: site.yml:staginggets the same as the lab. The differences (no load balancer, no API, versions, sizing) come from the inventory, not from the code.
8.5. Running it
export AWS_PROFILE=aurora-staging
ansible-playbook -i inventories/staging playbooks/staging-provision.yml --check # plan: 11 resources
ansible-playbook -i inventories/staging playbooks/staging-provision.ymlWhen it finishes, check the store on a staging web server (its public IP is in hosts-terraform.yml) and run it again: the second run must report changed=0 in every play. From then on you can work with the environment just as you do with the lab:
ansible-inventory -i inventories/staging --graph
ansible -i inventories/staging --playbook-dir playbooks webservers -m ansible.builtin.ping
ansible-playbook -i inventories/staging playbooks/webservers.yml --tags deployRemember the cost.
stagingis billed for as long as it exists. Destroy it when you finish practicing:ansible-playbook -i inventories/staging playbooks/staging-provision.yml -e aurora_staging_state=absent -e confirm=aurora-staging.
- The
production environment
production environmentinventories/production/hosts.yml (fictitious addresses on the data center network):
---
# production environment: Aurora Store data center (network 10.20.1.0/24).
# Only run from AWX, with approval.
all:
children:
production:
children:
aurora:
children:
loadbalancers:
hosts:
prod-lb1:
ansible_host: 10.20.1.10
webservers:
hosts:
prod-web1:
ansible_host: 10.20.1.11
prod-web2:
ansible_host: 10.20.1.12
prod-web3:
ansible_host: 10.20.1.13
dbservers:
hosts:
prod-db1:
ansible_host: 10.20.1.21
apiservers:
hosts:
prod-api1:
ansible_host: 10.20.1.41The names carry the prod- prefix even though they're in a different inventory: if they ever show up in a log, an alert or a facts cache, they won't be confused with the lab's web1.
Environment data:
---
# inventories/production/group_vars/all/aurora.yml
aurora_env: production
aurora_domain: aurora-store.example
aurora_internal_ip: "{{ ansible_host }}"---
# inventories/production/group_vars/all/connection.yml
# Dedicated automation account (created with the common role, Lesson 9.2).
# The SSH key is supplied by the AWX machine credential: it isn't specified here.
ansible_user: automation---
# inventories/production/group_vars/webservers.yml
aurora_app_version: "1.4.0"
nginx_worker_connections: 4096---
# inventories/production/group_vars/dbservers.yml
postgresql_max_connections: 200
postgresql_shared_buffers: 2GB---
# inventories/production/group_vars/apiservers.yml
aurora_catalog_version: "1.0.0"
# No docker_users or insecure registries: the production registry uses TLS.The three web servers have the common weight (1), so no host_vars are needed. Check what can be checked without servers:
ansible-inventory -i inventories/production --graph
ansible-playbook -i inventories/production playbooks/site.yml --list-hosts
ansible-playbook -i inventories/production playbooks/site.yml --syntax-checkNone of the three needs the production password. On the other hand, ansible-inventory -i inventories/production --playbook-dir playbooks --host prod-web1 would ask for it: it loads playbooks/group_vars/production/vault.yml. That's exactly the isolation you were looking for.
- AWX, CI and
ansible-navigator after the change
ansible-navigator after the changeMerge the branch only after adapting the repository's consumers, in this order.
10.1. AWX
| Object | Change |
|---|---|
Inventory Aurora - Lab, source aurora-infra repository |
Inventory file: inventory/ → inventories/lab |
Template Aurora - Configure infrastructure |
Playbook: playbooks/site.yml |
Template Aurora - Check configuration |
Playbook: playbooks/site.yml |
Template Aurora - Deploy web |
Playbook: playbooks/webservers.yml |
Template Aurora - Update packages (if you created it) |
Playbook: playbooks/upgrade.yml |
Credential Aurora - Vault lab |
Unchanged: it's still the lab identity |
So as not to leave AWX broken for even a minute: merge into main, sync the project (the Playbook drop-down will already show the new paths), change the objects and launch Aurora - Check configuration. It must finish green with the same difference in aurora.fact (if you hadn't applied it yet) or with no changes. In the job details you'll see the hosts inside the lab group after the inventory sync.
What about staging and production in AWX? They'll be integrated in the final project, once the staging inventory is dynamic (Lesson 10.2) and AWX can see it without a file generated on your computer. The design has already been decided and delivers what was announced in Lesson 7.5: the workflow's check node will become a real deployment to staging, and only after it and the approval will the release go to production:
flowchart LR
S["Sync project"] --> ST["Deploy web<br/>(staging inventory,<br/>Vault staging credential)"]
ST -->|"On Success"| AP{"Approve the deployment"}
AP -->|"On Success"| PR["Deploy web<br/>(production inventory,<br/>Vault production credential)"]
Each AWX inventory will have its own Vault credential (Aurora - Vault staging, Aurora - Vault production) and the Operations and Development permissions will be different in each environment.
10.2. Gitea Actions CI
In .gitea/workflows/ci.yml, the syntax job now iterates over the directory:
- name: Check the playbook syntax
run: |
for playbook in playbooks/*.yml; do
echo "== $playbook"
.venv/bin/ansible-playbook "$playbook" --syntax-check
doneA new playbook is covered without touching the CI. And in .gitea/workflows/web-deploy.yml, the version check reads the lab inventory (the environment that workflow releases to until the final project):
declared=$(grep -E '^aurora_app_version:' inventories/lab/group_vars/webservers.yml | sed -E 's/.*"(.*)".*/\1/')10.3. ansible-navigator
In ansible-navigator.yml, add the staging identity (the path is the one inside the container, mounted from ~/.ansible/vault as in Lesson 7.6):
ANSIBLE_VAULT_IDENTITY_LIST: lab@/aurora-vault/aurora-lab.pass,staging@/aurora-vault/aurora-staging.passAnd run with the new path: ansible-navigator run playbooks/site.yml.
10.4. Merging
git add -A
git commit -m "Reorganization: full staging, production, AWX and CI with the new paths"
git push -u origin reorganizationOpen the pull request in Gitea, wait for the CI to pass (the syntax check already iterates over playbooks/) and merge it. Then sync the project in AWX and apply the table from section 10.1.
- Internal roles and external roles
With the reorganization, it's also worth writing down the policy on roles. Aurora has two locations:
| Location | What it contains | How it gets there | Versioned here? |
|---|---|---|---|
roles/ |
common, postgresql, aurora_app, docker, aurora_catalog, aurora_catalog_k8s |
Written in this repository | Yes |
galaxy_roles/ |
nginx (from ops/ansible-role-nginx), geerlingguy.node_exporter |
ansible-galaxy role install -r roles/requirements.yml |
No (.gitignore) |
Criteria for deciding where a role goes:
| Question | If the answer is yes… |
|---|---|
| Is it used (or will it soon be used) by other projects? | Its own repository with versions, like ansible-role-nginx (Lesson 6.4), or the aurora_store.infra collection |
Does it contain Aurora business logic (aurora_app, aurora_catalog)? |
It stays in roles/: nobody else needs it |
| Is there a community one that meets the criteria from Lesson 6.1? | roles/requirements.yml with a pinned version |
| Is it still evolving rapidly? | Better in roles/ until it stabilizes: extracting it early forces you to release a version for every change |
Today, the natural candidate for extraction is docker (it's generic and another team might need it); there's no need to do it yet. One rule that does apply from now on: a role in galaxy_roles/ is never edited in place. Any change is made in its repository, released with a new version, and roles/requirements.yml is updated, as you'll do with nginx in Lesson 9.2.
- Team naming conventions
What was spread across several lessons until now is gathered in a table that will also go in the README.md:
| Element | Convention | Example |
|---|---|---|
| YAML files | .yml, start with ---, 2 spaces, indented lists |
playbooks/webservers.yml |
| Playbooks | By host group (<group>.yml) or by action (object-verb.yml); entry point site.yml |
dbservers.yml, staging-provision.yml |
| Play name | "Verb … Aurora Store …" | Configure the Aurora Store web servers |
| Task name | Imperative, initial capital, unique within its play, no Jinja except at the end | Publish the database connection details |
| Modules | Always FQCN; parameters in native YAML (cmd: in command) |
ansible.builtin.template |
| Booleans and permissions | true/false; mode: "0644" in quotes |
|
| Role variables | Prefixed with the role name, registered ones too | nginx_port, common_local_facts |
| Aurora variables | aurora_ prefix |
aurora_internal_ip |
| Secrets | vault_ + the name of the variable that uses them, only in vault.yml |
vault_aurora_db_password |
| Groups | Plural in English for functions; environment name for the root group | webservers, staging |
| Hosts | Lab: function + number; other environments with a prefix | web1, prod-web1, aurora-staging-web-1 |
| Tags | Functional: packages, config, users, firewall, deploy, facts, monitoring, info (+never, always) |
--tags deploy |
| Branches and commits | Short lowercase branches with hyphens; commits in English, imperative or descriptive | reorganization, gzip-level |
| Git tags | Roles and collections: X.Y.Z; website releases: web-X.Y.Z |
1.1.0, web-1.4.0 |
| Managed files | # {{ ansible_managed }} header (except JSON) |
- Documenting the repository:
README.md and CHANGELOG.md
README.md and CHANGELOG.md13.1. README.md
The README.md is the first thing anyone opening the repository in Gitea sees. It shouldn't repeat the course: it should let a new person get to work and know whom to ask. Aurora's:
# aurora-infra
Automation of the Aurora Store infrastructure with Ansible: lab,
staging (AWS) and production.
## Structure
| Path | Contents |
|------|----------|
| `inventories/<environment>/` | Hosts and data for each environment (`lab`, `staging`, `production`) |
| `playbooks/` | Playbooks; `site.yml` applies the full configuration |
| `playbooks/group_vars/` | Common wiring and per-environment secrets (`<environment>/vault.yml`) |
| `roles/` | Our own roles; `roles/requirements.yml`, external roles |
| `collections/requirements.yml` | Collections with pinned versions |
| `terraform/staging/` | Staging infrastructure (OpenTofu) |
| `ee/` | `aurora-ee` execution environment |
| `.gitea/workflows/` | Continuous integration and deployment |
| `lab/` | Vagrant lab and the `awx1` machine |
## Getting started
1. Requirements: `ansible` 10 (ansible-core 2.17) with `pipx`, Vagrant for the lab.
2. Dependencies:
```bash
ansible-galaxy collection install -r collections/requirements.yml
ansible-galaxy role install -r roles/requirements.yml
```
3. Vault passwords: ask the person in charge for the ones for the environments you'll use,
store them in `~/.ansible/vault/aurora-<environment>.pass` (mode 0600) and add to `~/.bashrc`:
`export ANSIBLE_VAULT_IDENTITY_LIST=lab@~/.ansible/vault/aurora-lab.pass`
4. Lab: `cd lab && vagrant up`.
## Usage
| Action | Command |
|--------|---------|
| Configure the lab | `ansible-playbook playbooks/site.yml` |
| Check without changing | `ansible-playbook playbooks/site.yml --check --diff` |
| Create and configure staging | `ansible-playbook -i inventories/staging playbooks/staging-provision.yml` |
| Destroy staging | `... -e aurora_staging_state=absent -e confirm=aurora-staging` |
| Production | Only from AWX (`http://192.168.56.30:30080`) |
| Ad hoc with the common variables | `ansible --playbook-dir playbooks <pattern> -m <module>` |
## Releasing a website version
Change `aurora_app_version` in a *pull request*; once it's merged, create and push the
`web-X.Y.Z` tag. The CI launches the AWX workflow, which waits for approval.
## Conventions
See the team conventions table (names, prefixes, tags): a variable
is defined in only one place; an environment's data goes in its inventory and the common
wiring in `playbooks/group_vars/`.
## Contact
Operations team: [email protected](The outer block uses four backticks so that it can contain other code blocks; you don't write them in the real file.)
13.2. CHANGELOG.md
The roles and the collection already have their changelogs (Lessons 6.4 and 6.5). An infrastructure repository doesn't release versions, but it does need to answer "what changed and when?" without digging through hundreds of commits. Aurora uses a date-based changelog, with the usual Keep a Changelog sections (Added, Changed, Removed, Security):
# aurora-infra changelog
## [Unreleased]
## 2026-11-26 - Reorganization by environment
### Added
- Per-environment inventories: `inventories/lab`, `inventories/staging`, `inventories/production`.
- `staging` and `production` Vault identities.
- Full staging configuration with `playbooks/staging-provision.yml`.
- `README.md` and this changelog.
### Changed
- Playbooks moved to `playbooks/`; common variables to `playbooks/group_vars/`.
- The wiring uses `aurora_internal_ip` instead of `ansible_host`.
- AWX and CI point to the new paths.
### Removed
- `staging-configure.yml` and the `cloud/` directory.The [Unreleased] section collects what gets merged; when it's applied in production, it moves to a dated section. From here on, every relevant pull request adds its line.
- The final repository tree
aurora-infra/
├── README.md, CHANGELOG.md
├── ansible.cfg (inventory = inventories/lab)
├── ansible-navigator.yml (+ staging identity)
├── inventories/
│ ├── lab/
│ │ ├── hosts.yml (lab group → aurora, k8s_clusters)
│ │ ├── group_vars/{all/aurora.yml, webservers.yml, loadbalancers.yml, dbservers.yml, apiservers.yml, k8s_clusters.yml}
│ │ └── host_vars/{web1.yml, web2.yml, db1.yml, k3s-lab.yml}
│ ├── staging/
│ │ ├── hosts.yml (groups only)
│ │ ├── hosts-terraform.yml (generated, NOT versioned)
│ │ └── group_vars/{all/{aurora.yml, connection.yml}, webservers.yml, dbservers.yml}
│ └── production/
│ ├── hosts.yml (prod-lb1, prod-web1..3, prod-db1, prod-api1)
│ └── group_vars/{all/{aurora.yml, connection.yml}, webservers.yml, loadbalancers.yml, dbservers.yml, apiservers.yml}
├── playbooks/
│ ├── site.yml, common.yml, dbservers.yml, loadbalancers.yml, webservers.yml,
│ │ apiservers.yml, monitoring.yml, upgrade.yml, catalog-image.yml, kubernetes.yml
│ ├── staging-provision.yml
│ ├── group_vars/
│ │ ├── all/{aurora.yml, common.yml, team.yml, monitoring.yml, catalog.yml}
│ │ ├── webservers.yml, loadbalancers.yml, dbservers.yml, apiservers.yml
│ │ ├── lab/vault.yml (encrypted, id lab)
│ │ ├── staging/vault.yml (encrypted, id staging)
│ │ └── production/vault.yml (encrypted, id production)
│ ├── vars/aws-staging.yml
│ └── templates/staging-hosts.yml.j2
├── roles/
│ ├── requirements.yml
│ └── common/, postgresql/, aurora_app/, docker/, aurora_catalog/, aurora_catalog_k8s/
├── collections/requirements.yml
├── terraform/staging/
├── ee/execution-environment.yml
├── ci/requirements.txt
├── .gitea/workflows/{ci.yml, ee.yml, web-deploy.yml}
├── lab/{Vagrantfile, awx/}
├── .gitignore (+ /inventories/staging/hosts-terraform.yml)
└── .gitattributesOutside the repository: ~/.ansible/vault/aurora-{lab,staging,production}.pass and the new ANSIBLE_VAULT_IDENTITY_LIST line in ~/.bashrc.
Common Mistakes and Tips
- Variables that "don't apply" in an environment. It's almost always a variable defined in
playbooks/group_vars/<group>and also in the inventory: the playbook one wins. Run thecommcommand from section 7.2; its output must be empty. - Ad hoc
ansiblecan't find a variable.--playbook-dir playbooksis missing. Without it, only the inventory variables are loaded. - "Attempting to decrypt but no vault secrets found". You're using an inventory whose vault isn't in your
ANSIBLE_VAULT_IDENTITY_LIST(for example,-i inventories/productionfrom your terminal). That's the intended behavior. 'dict object' has no attribute 'loadbalancers'. An inventory without theloadbalancersgroup declared. Every environment must declare the same functional groups, even if they're empty.- Applying
staging-provision.ymlwithout-i. The guard in the first play stops it. Don't remove it: without it, thestagingconfiguration would end up in the lab. - Relative paths that stop working.
vars_files, thesrcoftemplateandimport_playbookare relative to the playbook;roles_pathandcollections_path, toansible.cfg; some module parameters (likeproject_path), to the working directory. When in doubt, build the path withplaybook_dir. - Merging the reorganization and forgetting AWX. The templates would point to
site.yml, which no longer exists in the root, and the nightly check would fail. Keep the table from section 10.1 at hand before merging. - Tip: when you reorganize, first make only moves (
git mv) and verify with--check; then, in another commit, make the content changes. Reviewing a 300-line diff in which everything has been moved and modified is almost impossible.
Exercises
Exercise 1: where does each variable go?
For each case, state the exact file where you'd define it: (a) Production will have 4 web servers and prod-web4 is more powerful (weight 3). (b) A jq package is added to every server in every environment. (c) The staging database needs postgresql_max_connections: 80. (d) The PostgreSQL password of the reporting user in production. (e) A change to the postgresql_hba_clients expression so that it also accepts the load balancer network.
Exercise 2: detecting a duplicate
Someone adds nginx_worker_connections: 2048 to playbooks/group_vars/webservers.yml "so that all the web servers have the same value". (a) What value will the lab web servers have, and why? (b) How would you detect it before merging? (c) Propose how to automate that check in the CI.
Exercise 3: an ephemeral demo environment
The sales team wants a demo environment, the same as staging but with a single web server and version 1.3.0, which is created for a presentation and destroyed afterwards. List the files and directories you'd create and what would change in the code (playbooks and roles).
Solutions
Exercise 1. (a) inventories/production/hosts.yml (add prod-web4 under webservers) and inventories/production/host_vars/prod-web4.yml with aurora_lb_weight: 3: the common value 1 is in playbooks/group_vars/webservers.yml and the inventory's host_vars wins over it. (b) playbooks/group_vars/all/common.yml, in common_packages: it's the same in every environment. (c) inventories/staging/group_vars/dbservers.yml. (d) playbooks/group_vars/production/vault.yml, as vault_aurora_reporting_db_password, edited with ansible-vault edit and the production identity. (e) playbooks/group_vars/dbservers.yml: it's wiring, and the change applies to every environment at once (which means testing it first in lab and staging).
Exercise 2. (a) 2048: the group_vars next to the playbook (level 7) win over the inventory ones (level 6), so the lab's 1024 and production's 4096 are ignored. (b) With the comm -12 ... command from section 7.2, which would show nginx_worker_connections:. (c) A step in the lint job of ci.yml that repeats the check for each environment and fails if there's any output:
- name: Check that no variable is defined in two places
run: |
status=0
for env_dir in inventories/*/; do
repeated=$(comm -12 \
<(grep -rhoE '^[a-z0-9_]+:' playbooks/group_vars | sort -u) \
<(grep -rhoE '^[a-z0-9_]+:' "${env_dir}group_vars" | sort -u))
if [ -n "$repeated" ]; then
echo "Variables also defined in ${env_dir}: $repeated"
status=1
fi
done
exit $status
shell: bash(shell: bash is necessary because <( ) doesn't exist in sh.)
Exercise 3. New files: inventories/demo/hosts.yml (group structure with the demo root group, like staging), inventories/demo/group_vars/all/{aurora.yml, connection.yml} (aurora_env: demo, domain demo.aurora-store.example, user ubuntu and its key), inventories/demo/group_vars/webservers.yml (aurora_app_version: "1.3.0"), inventories/demo/group_vars/dbservers.yml, playbooks/group_vars/demo/vault.yml (demo identity), a Terraform project terraform/demo/ (or, better, turning terraform/staging into a reusable module with the environment name as a variable) and its variables (playbooks/vars/aws-demo.yml with web_count: 1). In playbooks/, generalize staging-provision.yml so that the environment is a variable (for example aurora_cloud_env) instead of duplicating it. In the roles, nothing: that's the proof that the structure is well designed. And .gitignore with its hosts-terraform.yml.
Conclusion
aurora-infra now has a structure designed to grow. Each environment (lab, staging and production) has its inventory with a root group that identifies it, its data (versions, sizes, addresses) and its own Vault identity, selected by that group, so that each person only needs the passwords of the environments they work with. The wiring between roles and the common data live just once in playbooks/group_vars/, under the rule that a variable is defined in a single place, and the new aurora_internal_ip separates the connection address from the internal communication address. The playbooks are in playbooks/ with site.yml as the entry point, staging finally gets the full configuration from the inventory that staging-provision.yml generates from the Terraform outputs, and production is described and protected. AWX, the CI and ansible-navigator point to the new paths, and the repository has a README.md, a CHANGELOG.md and a conventions table. A clear structure, however, doesn't protect anything by itself: the servers still accept passwords over SSH, the team's keys aren't managed, Docker and the Kubernetes cluster are used with administrator privileges, and the CI and Vault secrets have no rotation policy. In the next lesson, Security Best Practices, you'll review all those pending points and harden Aurora Store with Ansible.
