Skip to main content

Infrastructure as code · Advanced · 26 min

Catch drift in Relay on a schedule, then tear the whole environment down

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · OpenTofu 1.13.10 · hashicorp/aws 6.74 · actionlint 1.7.12

You will add a nightly GitHub Actions check that opens an issue when Relay's plan finds changes made outside OpenTofu, settle two hand-made changes, then destroy the whole environment and prove with the AWS CLI that nothing billable is left.

On this page

Relay is finished: a VPC, a web server built by cloud-init, a private assets bucket, encrypted state in S3, a tested network module and a pipeline that plans every pull request and applies on merge. One gap is left. The pipeline only looks at AWS when someone changes the code. If a colleague fixes something in the console at two in the morning, or a script you forgot about changes a setting, nothing tells you until the next unrelated pull request shows a surprise in its plan.

That difference between the code, the state and what really exists is called drift. In the first half of this part you add a nightly check that runs tofu plan -detailed-exitcode and opens a GitHub issue when the plan exits with 2. Then you cause drift yourself with the AWS CLI, watch it get caught, and settle each change: one you undo with an apply, one you keep by writing it into the code.

The second half is the series clean-up. You empty and delete the assets bucket, destroy Relay with a plan you read first, remove the CI roles and the GitHub settings, delete the state bucket last, and run a short audit that proves nothing from Relay is left in the account. Do the second half even if you stop early: the instance, its disk and its public IPv4 address bill for as long as they exist.

Step 1 · Confirm a clean starting point

A drift check is only useful if a plan with no drift really is empty. Go to the project, point the AWS CLI at the Region in your dev values, and run a plan that reports through its exit code:

Bash
cd ~/relay-demo
export AWS_REGION=$(sed -n 's/^region *= *"\(.*\)"$/\1/p' dev.tfvars)
echo "Region: $AWS_REGION"
tofu plan -var-file=dev.tfvars -detailed-exitcode && code=0 || code=$?
echo "exit code: $code"

-detailed-exitcode gives the plan three answers instead of two:

  • 0: the plan succeeded and there is nothing to change.
  • 1: the plan failed, for example because credentials expired or the passphrase is wrong.
  • 2: the plan succeeded and wants to change something.

The && code=0 || code=$? part keeps the number without stopping your shell, so you can print it and act on it. A script that only checks success or failure would treat drift and a broken plan the same way, which is the mistake this part avoids.

If your plan exits with 2 before you have changed anything, find out why first. It may be a merged pull request whose apply failed in part 7, or drift that is already there. Settle it as in step 5, then come back.

Check it worked

The plan ends with No changes. Your infrastructure matches the configuration., then Region: eu-west-1 (or your Region) and exit code: 0 are printed.

Step 2 · Write the drift check as a script

Keep the logic in a script in the repository rather than inside the workflow. You can run it on your laptop, read it in a pull request and test the failure paths before GitHub ever runs it. Create ci/drift-check.sh:

Bash
mkdir -p ci
cat > ci/drift-check.sh <<'SH'
#!/usr/bin/env bash
# Plan against the real account and report drift as a GitHub issue.
# Usage: ci/drift-check.sh dev.tfvars
# Exit codes: 0 no drift, 2 drift found and reported, 1 the plan failed.
set -euo pipefail

var_file="${1:?usage: ci/drift-check.sh <environment>.tfvars}"
env_name="$(basename "$var_file" .tfvars)"
title="Drift in Relay (${env_name})"

# -lock-timeout=5m: wait for an apply to release the state lock, as part 7's plan does.
tofu plan -input=false -no-color -lock-timeout=5m -detailed-exitcode -var-file="$var_file" \
  > drift-plan.txt 2>&1 && code=0 || code=$?
cat drift-plan.txt

case "$code" in
  0)
    echo "No drift in ${env_name}."
    exit 0
    ;;
  2) ;;
  *)
    echo "tofu plan failed with exit code ${code}; no issue opened."
    exit 1
    ;;
esac

{
  echo "The scheduled plan for ${env_name} wants to change resources, so something changed outside OpenTofu."
  echo
  echo "Run: ${RUN_URL:-a local run}"
  echo
  echo "Resources the plan would touch:"
  echo
  grep -E '^  # |^Plan:' drift-plan.txt | sed 's/^/    /' || true
  echo
  echo "For each change, either revert it with tofu apply or adopt it in code, then close this issue."
} > drift-issue.md

gh label create drift --color B60205 --description "Changes made outside OpenTofu" --force
existing="$(gh issue list --state open --label drift --json number,title \
  --jq "map(select(.title == \"${title}\")) | .[0].number // empty")"
if [ -n "$existing" ]; then
  gh issue comment "$existing" --body-file drift-issue.md
else
  gh issue create --title "$title" --label drift --body-file drift-issue.md
fi
exit 2
SH
chmod +x ci/drift-check.sh
printf '%s\n' drift-plan.txt drift-issue.md >> .gitignore

What the choices are for:

  • One issue per environment, updated rather than repeated. If nobody fixes the drift on Monday, Tuesday's run adds a comment to the open issue instead of opening a second one. A week of ignored drift is one issue with seven comments, not seven issues.
  • Only the resource lines go in the issue. The lines starting with # ` name each resource and what would happen to it, and the `Plan: line gives the totals. The full plan stays in the run log. OpenTofu hides values marked sensitive, but a plan still shows resource IDs, names and settings, so keep this repository private.
  • -lock-timeout=5m. The check takes the state lock like any other plan. Part 7 gave the plan role its inline relay-state-lock policy for exactly this: it may write and delete the .tflock object and nothing else in the bucket. If an apply holds the lock when the check starts, the plan waits up to five minutes for it instead of failing at once.
  • Exit 1 opens no issue. A failed plan is a broken check, not drift. It shows up as a failed run, and GitHub notifies whoever is set to receive workflow failures.

Run it once on your laptop. With no drift it never reaches the gh lines:

Bash
ci/drift-check.sh dev.tfvars

Now check the failure path with a passphrase that cannot open the state. It is longer than 16 characters, so it fails on decryption rather than on a length check:

Bash
TF_VAR_state_passphrase='this-is-not-the-relay-passphrase' ci/drift-check.sh dev.tfvars > wrong-key.log 2>&1 && code=0 || code=$?
echo "exit code: $code"
tail -n 2 wrong-key.log
rm wrong-key.log

Check it worked

The first run ends with No drift in dev.. The second prints exit code: 1 and its last line is tofu plan failed with exit code 1; no issue opened. Neither run created an issue in your repository.

Step 3 · Schedule the check with GitHub Actions

Write the workflow. It uses the same read-only plan role, repository variables and passphrase secret as the pull request workflow from part 7. If you named yours differently there, change the three names here to match:

Bash
mkdir -p .github/workflows
cat > .github/workflows/relay-drift.yml <<'YAML'
name: Relay drift check

on:
  schedule:
    # 03:17 UTC every day. Avoid minute 0, when GitHub is busiest.
    - cron: "17 3 * * *"
  workflow_dispatch:

permissions:
  contents: read
  id-token: write
  issues: write

# Its own group, not part 7's relay-apply: sharing that group could cancel
# a merged apply that is waiting its turn. The state lock keeps the check
# from reading the state while an apply is running.
concurrency:
  group: relay-drift
  cancel-in-progress: false

jobs:
  drift:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false

      - uses: opentofu/setup-opentofu@v2
        with:
          tofu_version: 1.13.10
          tofu_wrapper: false

      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.RELAY_PLAN_ROLE_ARN }}
          aws-region: ${{ vars.AWS_REGION }}

      - name: Initialise
        run: tofu init -input=false

      - name: Plan and report drift
        run: ci/drift-check.sh dev.tfvars
        env:
          TF_VAR_state_passphrase: ${{ secrets.STATE_PASSPHRASE }}
          GH_TOKEN: ${{ github.token }}
          RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
YAML

Some points about schedules that catch people out:

  • Cron times are in UTC. 17 3 * * * is 03:17 in London in winter, 04:17 in Lagos and 05:17 in Nairobi.
  • A scheduled run starts from the latest commit on the default branch, and only from there. A workflow on a feature branch never runs on schedule.
  • GitHub may start scheduled runs late when it is busy, especially at the start of each hour. Drift detection does not need to the minute.
  • In a public repository, GitHub disables scheduled workflows after 60 days with no activity. Another reason to keep this repository private.
  • tofu_wrapper: false stops the setup action wrapping tofu in a script, so the script sees the real exit code and output.
  • The check has its own concurrency group, relay-drift. It could share part 7's relay-apply group so it never runs beside an apply, but GitHub keeps only one waiting run per group and cancels the older waiting one when a newer one arrives. A check queued at 03:17 behind a running apply would cancel a second merge's apply that was waiting, and that change would never reach AWS. With separate groups, the state lock does the job instead: if an apply holds it, the plan waits up to five minutes (-lock-timeout=5m), and if the apply takes longer the run fails with exit 1 and opens no issue.

The job uses no environment, on purpose. A job that names one gets an OIDC token whose subject is repo:<owner>/<repo>:environment:<name>. Without one, a scheduled run on main gets repo:<owner>/<repo>:ref:refs/heads/main. Part 7's plan role trusts only repo:<owner>/<repo>:pull_request, so add the main branch to it. Open iam/plan-trust.json from part 7 and turn the sub value inside StringEquals into a list of two subjects, with your owner and repository in both. The Condition block becomes:

JSON
"Condition": {
  "StringEquals": {
    "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
    "token.actions.githubusercontent.com:sub": [
      "repo:your-github-user/relay-demo:pull_request",
      "repo:your-github-user/relay-demo:ref:refs/heads/main"
    ]
  }
}

A list inside StringEquals matches if the token's subject equals any one of the entries. Apply the edited file to the role with an admin profile, as in part 7:

Bash
aws iam update-assume-role-policy --role-name relay-plan --policy-document file://iam/plan-trust.json
aws iam get-role --role-name relay-plan --query 'Role.AssumeRolePolicyDocument.Statement[0].Condition'

The role still trusts no other branch and no environment, and it still can only read, plus write its own lock object.

Lint the workflow before it reaches GitHub. actionlint checks the syntax, the expressions and the permissions. On Linux, install the pinned release; on macOS, brew install actionlint does the same job. The binary comes from GitHub, not from apt, so it gets no security updates: to upgrade, run these lines again with a newer version number.

Bash
ACTIONLINT=1.7.12
case "$(uname -m)" in
  x86_64) AL_ARCH=amd64 ;;
  aarch64 | arm64) AL_ARCH=arm64 ;;
esac
cd "$(mktemp -d)"
curl -fsSLO "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT}/actionlint_${ACTIONLINT}_linux_${AL_ARCH}.tar.gz"
curl -fsSLO "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT}/actionlint_${ACTIONLINT}_checksums.txt"
sha256sum --ignore-missing -c "actionlint_${ACTIONLINT}_checksums.txt"
tar -xzf "actionlint_${ACTIONLINT}_linux_${AL_ARCH}.tar.gz" actionlint
sudo install -m 0755 actionlint /usr/local/bin/actionlint
cd ~/relay-demo
actionlint --version
actionlint .github/workflows/relay-drift.yml

Then send the two files through a pull request, as you would any change to Relay. Part 7's workflow plans it and finds nothing to change in AWS:

Bash
git switch -c add-drift-check
git add ci/drift-check.sh .github/workflows/relay-drift.yml .gitignore
git commit -m "Add a nightly drift check"
git push -u origin add-drift-check
gh pr create --fill

Merge it once the checks pass. The workflow runs from GitHub's machines, so the nightly download of OpenTofu and the AWS provider uses none of your own data allowance.

Check it worked

sha256sum prints OK for the tarball and actionlint .github/workflows/relay-drift.yml prints nothing, which means no problems were found. After the merge, the Actions tab of your repository lists Relay drift check, with a Run workflow button from workflow_dispatch.

Step 4 · Change Relay by hand and watch the plan catch it

Make two changes outside OpenTofu, the way they happen in real teams. Do this only in dev:

  1. Someone suspends versioning on the assets bucket to try something and forgets to turn it back on. Objects already in the bucket keep their versions, but new overwrites and deletes are no longer recoverable.
  2. Finance tags the web server's role with a cost centre, so the role's cost shows up in their report.
Bash
ASSETS=$(tofu output -raw assets_bucket_name)
WEB_ROLE=$(aws iam list-roles --query "Roles[?starts_with(RoleName, 'relay-dev-web-')].RoleName | [0]" --output text)
echo "Bucket: $ASSETS  Role: $WEB_ROLE"
aws s3api put-bucket-versioning --bucket "$ASSETS" --versioning-configuration Status=Suspended
aws iam tag-role --role-name "$WEB_ROLE" --tags Key=CostCentre,Value=web-ops

Plan again:

Bash
tofu plan -var-file=dev.tfvars -detailed-exitcode && code=0 || code=$?
echo "exit code: $code"

The plan has two parts. First, a note that objects have changed outside OpenTofu, showing what it found when it refreshed: the versioning status is now Suspended, and the role's tags include CostCentre. Then the changes it proposes to make AWS match the code again: set versioning back to Enabled, and remove the CostCentre tag from the role.

Now let the workflow find it. Trigger the check by hand rather than waiting for 03:17, then follow the run:

Bash
gh workflow run relay-drift.yml
gh run watch "$(gh run list --workflow relay-drift.yml --limit 1 --json databaseId --jq '.[0].databaseId')"
gh issue list --label drift

The run finishes red, because the script exits with 2, and a new issue appears.

A drift check has blind spots, and it is better to know them now. The plan compares only the objects in its state and the arguments your code sets. A security group rule someone adds by hand is a new object OpenTofu has never heard of, so it shows up nowhere. A change to a setting your code leaves at the provider default may not either. The check catches edits to what you manage; it does not replace AWS Config or a regular look at the console.

Check it worked

The local plan ends with Plan: 0 to add, 2 to change, 0 to destroy. and exit code: 2. On GitHub, gh issue list --label drift shows one open issue titled Drift in Relay (dev), and its body lists aws_iam_role.web will be updated in-place and aws_s3_bucket_versioning.assets will be updated in-place. If the run failed at the AWS credentials step instead, the plan role's trust policy does not yet accept the main branch: check that the get-role command in the previous step lists both subjects.

Step 5 · Revert one change and adopt the other

Every drift needs a decision, and there are only two good ones:

  • Revert: the code was right and the change was a mistake. Apply, and OpenTofu puts AWS back. Suspended versioning is this kind: the code says versioning is on because the page assets must be recoverable.
  • Adopt: the change was right and the code is behind. Write the change into the code, so the next plan has nothing to do. The cost centre tag is this kind: finance needs it, and it harms nothing.

Two other tools look like answers and usually are not. tofu apply -refresh-only writes what AWS has into the state, but the code still disagrees, so the next normal plan proposes the same change again. lifecycle { ignore_changes = [...] } tells OpenTofu to stop caring about an attribute, which is right only when another system owns it for good, such as tags written by a company-wide tagging tool.

Adopt first, so the apply that follows reverts only what you mean to revert. Open iam.tf and add the tag to aws_iam_role.web. Before:

HCL
resource "aws_iam_role" "web" {
  name_prefix        = "${local.name_prefix}-web-"
  assume_role_policy = data.aws_iam_policy_document.web_assume.json
}

After:

HCL
resource "aws_iam_role" "web" {
  name_prefix        = "${local.name_prefix}-web-"
  assume_role_policy = data.aws_iam_policy_document.web_assume.json

  tags = {
    CostCentre = "web-ops"
  }
}

The provider merges these tags with default_tags, so the role ends up with Project, Environment, ManagedBy, Owner and CostCentre, which is exactly what AWS has now. Save a plan and check that it touches only versioning:

Bash
tofu fmt -check iam.tf
tofu plan -var-file=dev.tfvars -out=revert.tfplan
tofu show -json revert.tfplan | jq -r '.resource_changes[] | select(.change.actions != ["no-op"]) | .address'

Apply that plan, then confirm the bucket and the code agree with AWS again:

Bash
tofu apply revert.tfplan
rm revert.tfplan
aws s3api get-bucket-versioning --bucket "$ASSETS"
tofu plan -var-file=dev.tfvars -detailed-exitcode && code=0 || code=$?
echo "exit code: $code"

On a team, put the iam.tf change through a pull request instead of applying from your laptop. Part 7's workflow shows the same one-line plan in the pull request and applies it on merge, which reverts versioning and records the decision in Git. Then close the issue with a note of what you did, replacing the number:

Bash
gh issue close <issue-number> --comment "Versioning reverted by apply; CostCentre tag adopted in iam.tf."

Check it worked

The JSON check prints one address, aws_s3_bucket_versioning.assets. After the apply, get-bucket-versioning shows "Status": "Enabled", the last plan says No changes. and exit code: 0 is printed. The next scheduled run ends green and opens nothing.

Step 6 · Stop the schedule and empty the assets bucket

From here on, you take Relay apart. Turn off the workflows first. Otherwise the drift check would report the whole environment as missing tonight, and a merge would make part 7's workflow try to apply into an account with no state. List the workflows, then disable both. Part 7's workflow is .github/workflows/relay.yml; if you renamed it, use your file name in the last line:

Bash
gh workflow list --all
gh workflow disable relay-drift.yml
gh workflow disable relay.yml

Now the assets bucket. Its versioning matters here. Deleting an object from a versioned bucket does not remove it: S3 adds a delete marker on top and keeps every earlier version, and a bucket cannot be deleted while any version or marker is left. See what is there:

Bash
aws s3api list-object-versions --bucket "$ASSETS" \
  --query '[length(Versions || `[]`), length(DeleteMarkers || `[]`)]' --output text

The two numbers are versions and delete markers. If you want a copy of the current files, take it now with aws s3 sync "s3://$ASSETS" ~/relay-assets-backup. Earlier versions are not included.

Warning: the next command permanently deletes every version of every object in the bucket you pass it. Check that $ASSETS holds the dev assets bucket name before you run it; the first line stops the block if it is empty (if so, tofu output lists your output names). The function lists up to 500 versions and markers at a time (a single delete call takes at most 1,000 keys), deletes them by version ID, and repeats until nothing is left:

Bash
: "${ASSETS:?set ASSETS to the assets bucket name first}"
echo "About to empty: $ASSETS"
empty_versioned_bucket() {
  while :; do
    aws s3api list-object-versions --bucket "$1" --max-items 500 --output json \
      | jq -s '(.[0] // {}) | {Objects: [(.Versions // [])[], (.DeleteMarkers // [])[] | {Key, VersionId}], Quiet: true}' \
      > /tmp/relay-delete.json
    if [ "$(jq '.Objects | length' /tmp/relay-delete.json)" -eq 0 ]; then
      break
    fi
    aws s3api delete-objects --bucket "$1" --delete file:///tmp/relay-delete.json > /dev/null
  done
  rm -f /tmp/relay-delete.json
  echo "Emptied $1"
}
empty_versioned_bucket "$ASSETS"
aws s3api list-object-versions --bucket "$ASSETS" \
  --query '[length(Versions || `[]`), length(DeleteMarkers || `[]`)]' --output text

Dev has force_destroy_assets = true from part 1, so tofu destroy would also have emptied this bucket. Emptying it yourself means you see what goes, and it is the only way for prod, where force_destroy_assets is false and the destroy stops with a BucketNotEmpty error. Keep the function in this terminal: you use it again on the state bucket.

Check it worked

gh workflow list --all shows both workflows as disabled_manually. The first count prints two numbers, versions then delete markers, such as 3 1. The function prints Emptied relay-dev-assets-... with your account number, and the second count prints 0 0.

Step 7 · Destroy Relay with a plan you read first

tofu destroy builds a destroy plan and asks you to type yes. Saving the destroy plan to a file instead gives you something to read, and the apply does exactly that and no more. This uses dev.tfvars and the relay/dev state; if you also built prod, repeat this step and the previous one with prod.tfvars and prod's backend afterwards.

Bash
tofu plan -destroy -var-file=dev.tfvars -out=destroy.tfplan
tofu show -json destroy.tfplan | jq -r '.resource_changes[] | select(.change.actions == ["delete"]) | .address'

Read the list. It should name only Relay's resources: the assets bucket and its settings, the network module's objects, the IAM role, its policy and instance profile, and the instance. Warning: the apply below deletes all of them, and the web server's disk goes with it. The page goes offline at once and cannot be recovered except by applying the code again.

Bash
tofu apply destroy.tfplan
rm destroy.tfplan
tofu state list

The instance takes a minute or two to terminate, so this apply is slower than the others. If it stops with an error, read which resource failed, fix the cause (an object someone added by hand to the VPC or the bucket is the usual one), and run the two plan and apply commands again. The state still lists whatever is left, so a second run picks up where the first stopped.

Check it worked

The apply ends with Apply complete! Resources: 0 added, 0 changed, N destroyed., with N equal to the number of addresses in the list you read. tofu state list prints nothing. The state object in S3 still exists, now encrypted and empty, which is why the state bucket comes last.

Step 8 · Remove the CI access and the state bucket

Delete what part 7 set up on GitHub: the passphrase secret, the role variables and the production environment, with its required reviewer and any environment secrets. The {owner} and {repo} placeholders are filled in by gh from the repository you are in. Replace the variable names if yours differ:

Bash
gh secret delete STATE_PASSPHRASE
gh variable delete RELAY_PLAN_ROLE_ARN
gh variable delete RELAY_APPLY_ROLE_ARN
gh variable delete AWS_REGION
gh api --method DELETE "repos/{owner}/{repo}/environments/production"

Then the two IAM roles GitHub used. Part 7 named them relay-plan and relay-apply; replace the names in the last two lines if yours differ. AWS refuses to delete a role that still has policies, so the function removes its inline policies and detaches its managed ones first:

Bash
delete_role() {
  for arn in $(aws iam list-attached-role-policies --role-name "$1" --query 'AttachedPolicies[].PolicyArn' --output text); do
    aws iam detach-role-policy --role-name "$1" --policy-arn "$arn"
  done
  for name in $(aws iam list-role-policies --role-name "$1" --query 'PolicyNames[]' --output text); do
    aws iam delete-role-policy --role-name "$1" --policy-name "$name"
  done
  aws iam delete-role --role-name "$1"
  echo "Deleted role $1"
}
delete_role relay-plan
delete_role relay-apply

Part 7 gave relay-plan the AWS-managed ReadOnlyAccess policy and an inline relay-state-lock policy, and gave relay-apply an inline policy, so the function above removed everything it set up. If you created a customer-managed policy of your own for Relay and attached it to either role, detaching it left the policy behind. List any customer-managed policies whose names start with relay-. After part 7 as written it prints nothing; delete each one it does print, replacing the ARN:

Bash
aws iam list-policies --scope Local --query "Policies[?starts_with(PolicyName, 'relay-')].Arn" --output text
Bash
aws iam delete-policy --policy-arn <policy-arn>

The GitHub OIDC identity provider is shared by every repository in the account that deploys with OIDC. List the providers, and delete GitHub's only if Relay was its last user:

Bash
aws iam list-open-id-connect-providers
Bash
aws iam delete-open-id-connect-provider --open-id-connect-provider-arn <provider-arn>

If you switched Relay's state to a KMS key in step 8 of part 4, schedule that key for deletion too. AWS waits between 7 and 30 days before deleting it, and you can cancel during that time:

Bash
aws kms schedule-key-deletion --key-id <key-arn> --pending-window-in-days 7

Last, the state bucket. Warning: emptying it deletes every saved version of Relay's state, so do it only after the destroy above finished and tofu state list printed nothing. List what the bucket holds first. If you see a key other than relay/dev/terraform.tfstate, such as a prod state, stop here: that environment still exists.

Bash
cd ~/relay-demo/bootstrap
STATE_BUCKET=$(tofu output -raw state_bucket)
aws s3 ls "s3://$STATE_BUCKET" --recursive
empty_versioned_bucket "$STATE_BUCKET"
tofu plan -destroy -out=destroy.tfplan
tofu apply destroy.tfplan
rm destroy.tfplan

The bootstrap configuration keeps its own encrypted state on your disk, which is why it can delete the bucket the other state lived in.

Check it worked

Both delete_role calls print Deleted role .... The bootstrap apply ends with Apply complete! Resources: 0 added, 0 changed, 5 destroyed.: the bucket, its versioning, public access block, default encryption and TLS-only policy from part 4. aws s3 ls "s3://$STATE_BUCKET" now fails with NoSuchBucket.

Step 9 · Prove nothing billable is left

Go back to your home folder and ask AWS directly, rather than trusting any state file. Each query prints IDs only if something matching Relay is still there:

Bash
cd ~
left=$(
  aws ec2 describe-instances \
    --filters Name=tag:Project,Values=relay Name=instance-state-name,Values=pending,running,stopping,stopped \
    --query 'Reservations[].Instances[].InstanceId' --output text
  aws ec2 describe-volumes --filters Name=status,Values=available --query 'Volumes[].VolumeId' --output text
  aws ec2 describe-addresses --query 'Addresses[].PublicIp' --output text
  aws ec2 describe-vpcs --filters Name=tag:Project,Values=relay --query 'Vpcs[].VpcId' --output text
  aws s3api list-buckets --query "Buckets[?starts_with(Name, 'relay-')].Name" --output text
  aws iam list-roles --query "Roles[?starts_with(RoleName, 'relay-')].RoleName" --output text
)
if [ -n "$(printf '%s' "$left" | tr -d '[:space:]')" ]; then
  printf 'Still there:\n%s\n' "$left"
  false
else
  echo "Nothing from Relay is left in $AWS_REGION, S3 or IAM."
fi

What each line looks for:

  • Instances tagged Project = relay that are not terminated. A terminated instance stays visible for a while and costs nothing, so it is filtered out.
  • Unattached EBS volumes. They bill until deleted, and a root volume can be left behind if delete_on_termination was ever turned off. This line checks the whole Region, so it may also list volumes that are not Relay's.
  • Elastic IP addresses, which bill while they exist, and the VPC.
  • S3 buckets and IAM roles whose names start with relay-. S3 and IAM are not tied to one Region, so these two lines cover the whole account.

The EC2 lines only look in $AWS_REGION. If you ever built Relay in another Region, such as the af-south-1 (Cape Town) copy from part 5, run the block again with AWS_REGION set to that Region. Billing data lags behind by up to a day, so check the Bills page in the Billing console tomorrow: you will still see the charges for hours already used, and nothing new after today.

Finally, clear up your own machine. Warning: this deletes the local project, including the bootstrap state. Your code is safe in the GitHub repository; archive it there with gh repo archive if you want to keep it read-only. Then remove the passphrase from your password manager as well:

Bash
rm -rf ~/relay-demo
rm -f ~/.config/relay/state-passphrase
rmdir ~/.config/relay 2>/dev/null || true
unset TF_VAR_state_passphrase

If you set up the provider cache from part 1 and have no other OpenTofu projects, rm -rf ~/.terraform.d/plugin-cache frees the space the AWS provider took, about 174 MB as a download for each version you used.

Check it worked

The block prints Nothing from Relay is left in eu-west-1, S3 or IAM., with your Region. If it prints Still there: and a list instead, delete each item it names (for an instance or VPC, the console shows which resource is holding it), then run the block again until it is clean. ls ~/relay-demo reports No such file or directory.

Next steps

  • Look back at how the pipeline you just switched off planned and applied each change: /tutorials/plan-relay-changes-in-pull-requests-with-github-actions.
  • Practise drift, plans and destroy again with local providers only, at no cost: /tutorials/manage-infrastructure-with-opentofu.
  • Revisit state encryption and the bootstrap pattern before building the next environment: /tutorials/store-relay-state-remotely-with-encryption.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.