# Case Study: Multi-Environment Inventory

Ansible has no built-in concept of dev, staging, or production. You model environments with **one inventory directory per environment**, each holding its own hosts file and `group_vars/`, and choose the environment at run time with `-i`:

```bash
ansible-playbook -i inventories/dev/hosts.ini        playbooks/site.yml
ansible-playbook -i inventories/staging/hosts.ini    playbooks/site.yml
ansible-playbook -i inventories/production/hosts.ini playbooks/site.yml -e confirm_env=production
```

The roles and playbooks stay identical. Only the inventory changes, so production can't be targeted unless someone names the production inventory. The rest of this page builds that layout, plus a preflight check that refuses a production run without `-e confirm_env=production`.

## Problem

Three environments — dev, staging, production — need the same roles applied with different variables (different database hosts, different replica counts, different feature flags), and a mistake in one environment must not be able to reach another.

## Requirements

- One set of roles, reused unmodified across all three environments
- Environment-specific variables cleanly separated
- Structurally impossible (not just "please be careful") to target production by accident

## Architecture

```
flowchart TD
    R[Shared roles/] --> D[inventories/dev]
    R --> S[inventories/staging]
    R --> P[inventories/production]
    D --> DR[ansible-playbook -i inventories/dev]
    S --> SR[ansible-playbook -i inventories/staging]
    P --> PR[ansible-playbook -i inventories/production]
```

## Repository Structure

```text
ansible-project/
├── inventories/
│   ├── dev/
│   │   ├── hosts.ini
│   │   └── group_vars/all.yml
│   ├── staging/
│   │   ├── hosts.ini
│   │   └── group_vars/all.yml
│   └── production/
│       ├── hosts.ini
│       └── group_vars/all.yml
├── playbooks/site.yml
└── roles/app/
```

## Inventory and Variables Per Environment

inventories/dev/hosts.ini

```ini
[app]
dev-app01 ansible_host=10.10.1.10
```

inventories/dev/group\_vars/all.yml

```yaml
env_name: dev
db_host: dev-db.internal
replica_count: 1
feature_new_dashboard: true
```

inventories/production/hosts.ini

```ini
[app]
prod-app01 ansible_host=10.20.1.10
prod-app02 ansible_host=10.20.1.11
prod-app03 ansible_host=10.20.1.12
```

inventories/production/group\_vars/all.yml

```yaml
env_name: production
db_host: prod-db.internal
replica_count: 3
feature_new_dashboard: false
```

Notice `dev-app01` and `prod-app01` are different hostnames in entirely separate files — there is no shared inventory with an `env:` variable to get wrong.

## Playbook (Identical Across Every Environment)

playbooks/site.yml

```yaml
---
- name: Refuse production runs without confirmation
  hosts: all
  gather_facts: false
  any_errors_fatal: true
  tasks:
    - name: Require -e confirm_env=production for production
      ansible.builtin.assert:
        that: env_name != 'production' or (confirm_env | default('')) == 'production'
        fail_msg: "This inventory is production. Re-run with -e confirm_env=production"
        quiet: true

- name: Configure application servers
  hosts: app
  become: true
  roles:
    - app
```

## Execution

```bash
# Dev — safe to run freely
ansible-playbook -i inventories/dev/hosts.ini playbooks/site.yml

# Production — same playbook, same roles, different inventory, explicit confirmation
ansible-playbook -i inventories/production/hosts.ini playbooks/site.yml --check --diff -e confirm_env=production
ansible-playbook -i inventories/production/hosts.ini playbooks/site.yml -e confirm_env=production
```

`env_name` comes from each inventory's `group_vars/all.yml`, so the preflight play knows which environment it's pointed at without any extra flag. Dev and staging runs pass straight through. A production run without the confirmation stops before any host is touched.

## Expected Output

```text
$ ansible-playbook -i inventories/production/hosts.ini playbooks/site.yml --check --diff -e confirm_env=production
PLAY [Refuse production runs without confirmation] ***
TASK [Require -e confirm_env=production for production] ***
ok: [prod-app01]
ok: [prod-app02]
ok: [prod-app03]

PLAY [Configure application servers] ***
TASK [app : Deploy application config] ***
--- before: /etc/app/config.yml
+++ after: config.yml.j2
@@ -1,3 +1,3 @@
-db_host: dev-db.internal
+db_host: prod-db.internal
changed: [prod-app01]
```

`--check --diff` against production shows exactly what would change — including confirming `db_host` resolved to the **production** database, not dev's, before anything is actually applied.

## Failure Scenario (Near Miss, Caught)

An engineer means to test a change against dev and runs:

```bash
ansible-playbook -i inventories/dev/hosts.ini playbooks/site.yml --limit app01
```

`--limit app01` matches nothing — `app01` doesn't exist in the dev inventory (it's `dev-app01`) — so Ansible reports zero hosts matched and the run does nothing, rather than silently matching a same-named host in a different environment. Compare this to a single shared inventory using generic hostnames like `app01` across environments distinguished only by a variable: the same typo there could easily have matched a host in the *wrong* environment and applied a change silently.

> [!NOTE]
>
> **Real incident: GitLab.com, January 2017**
>
> An engineer fighting a replication problem wiped a PostgreSQL data directory on the primary, believing it was the secondary. The backups turned out not to work, GitLab.com was down for about 18 hours, and roughly six hours of data was lost. Separate inventories stop the wrong *environment*; for destructive steps, also ask the host what it is (`pg_is_in_recovery()`, a cluster role, a hostname check) right before acting. [The guard](<https://computecentral.in/ansible/case-studies/08-automation-outages-and-guardrails/index.md#gitlabcom-2017-the-right-command-on-the-wrong-server>) is in Automation Outages.

## Troubleshooting

```bash
ansible-inventory -i inventories/production/hosts.ini --graph
```

confirms exactly which hosts a given inventory file resolves to, before running anything against it — the fastest sanity check before any production run.

## Production Hardening

- Add a CI gate requiring `--check --diff` output to be reviewed (as a PR comment or artifact) before any production apply is allowed to run.
- Name hosts with an environment prefix (`dev-`, `prod-`) even though they already live in separate files — a second layer of defense against a copy-pasted `--limit` pattern.
- Restrict which CI credentials/runners can even reach the production inventory's target network, so a wrong `-i` flag fails at the network layer too, not just the inventory layer.

## Check Yourself

> [!NOTE]
>
> **The flag nobody passed**
>
> An engineer runs the production inventory without `-e confirm_env=production`. With the preflight play above, what happens?
>
> - [ ] Ansible prompts for confirmation
> - [x] The preflight assertion fails and `any_errors_fatal` stops the run before any host is changed
> - [ ] Only the first host is changed, then the run stops
>
> The preflight play runs first against every host. Its assertion fails, and `any_errors_fatal: true` ends the play everywhere, so the configuration play never starts.

> [!NOTE]
>
> **A same-named host**
>
> Both environments share one inventory and use the hostname `app01`, with `env: dev` or `env: production` as a variable. What's the risk?
>
> - [ ] None, as long as `env` is set correctly
> - [x] `--limit app01` can match a production host when you meant dev, and nothing stops it
> - [ ] Ansible refuses duplicate hostnames
>
> Separate inventory directories and environment-prefixed hostnames make a wrong `--limit` match nothing, which is the safe failure.

## Interview Questions

- Why is separate inventory directories per environment safer than one inventory with an `env:` variable?
- What would `ansible-playbook -i inventories/dev/hosts.ini site.yml --limit app01` do if `app01` doesn't exist in that inventory, and why is that the safe behavior?

## What You Learned

Environment isolation that depends on "remembering to pass the right flag" is not isolation — structuring inventory so the wrong flag simply can't match a real host is.
