For four modules, EcoMarket has been an honest simulation: the network, data and app modules exist, they have an interface, locals, tagging and semantic versioning, but what they produce are JSON files in an output/ directory. That decision was deliberate — learning HCL, state and composition without a bill attached — and it ends here. In this module the local_file becomes aws_vpc, aws_db_instance and aws_s3_bucket, and with that change everything the local provider was hiding from you shows up: credentials that grant access to a real account, resources that take twenty minutes to create, service quotas, intermittent API errors, irreversible operations and an hourly cost that keeps running even when nobody uses the platform. This lesson is the bridge. It does not teach specific resources from any cloud — that comes in the next three — but rather what the three have in common: how you authenticate, how the plan/apply cycle behaves when there are hundreds of resources and an API on the other side, how a large plan is read and audited, what to do when an apply breaks halfway through, and the cost discipline that separates somebody learning Terraform from somebody using it in production.

  1. From simulation to the cloud: what exactly changes

It is worth being precise about what changes and what does not. The language does not change. The resource block, for_each, lifecycle, expressions, modules, state: everything still works the same. What changes is the behaviour of the other side: instead of a provider that writes a file to your disk in microseconds with no possibility of failure, there is a remote API, authenticated, with limits, with latency and with billing.

Dimension local/random provider (modules 1-4) Cloud provider (AWS, Azure, GCP)
Creation latency Microseconds From 2 seconds (a firewall rule) to 25 minutes (a Multi-AZ database)
Cost Zero Per hour, per GB, per request, per IP address. It runs even when nobody uses the system
Authentication None Credentials that grant access to the whole account, subject to the principal's permissions
Quotas None Hard limits per region: VPCs, elastic IP addresses, vCPUs, database instances
Rate limits None The API rejects you with Throttling if you ask too fast
Partial failures Practically impossible Routine: 40 resources are created, the 41st fails, the 40 stay created
Irreversibility Deleting a file is deleting a file Destroying a database without a snapshot loses the data forever
Consistency Immediate Eventual: a freshly created IAM role may not be usable for a few seconds
Side effects None Public DNS records, IP addresses reachable from the Internet, security alerts
Who else sees it Nobody Your team, the security team, the finance team, and potentially the Internet

The three rows that change the way you work are the second, the seventh and the eighth. Cost turns every apply into a decision with economic consequences. Irreversibility turns reading the plan into an obligation rather than a habit. And partial failures mean that state and reality can diverge in the middle of an operation, which is exactly the scenario you studied in Understanding State and which now stops being theoretical.

There is a fourth difference that does not fit in the table and matters more than all of them: the local provider had no opinion about what you were doing. A cloud provider does. It will reject an overlapping CIDR, a bucket name already taken by another company somewhere in the world, a database instance whose class does not exist in that region, a subnet in a zone your account does not have enabled. A good share of the errors of the first few days are not Terraform errors: they are cloud errors that Terraform merely relays.

  1. Credentials and authentication: the rule that is not negotiable

You already saw the principle in Providers; here it applies with real consequences.

Absolute rule: no credentials in .tf files. Ever. Under no excuse.

The reason is not the usual one — "it ends up in Git" — although that too. It is that a .tf file is code that gets shared, copied between environments, published as an example, pasted into a ticket and eventually written to a pipeline log. A key in a .tf has a long half-life and an uncontrollable distribution. On top of that, the bots that scan GitHub looking for AWS keys take minutes, not days: there are documented cases of bills running into tens of thousands of euros generated within hours by cryptocurrency mining after a key was leaked.

The legitimate approaches, ordered from worst to best:

Method How it is configured When it is acceptable Main risk
Environment variables AWS_ACCESS_KEY_ID, ARM_CLIENT_SECRET, GOOGLE_CREDENTIALS Quick local development, ephemeral containers They stay in the shell history and in the environment of child processes
Profile with long-lived credentials ~/.aws/credentials, profile = "ecomarket-dev" Lab accounts, learning Permanent key on disk; it has to be rotated
Temporary session / SSO aws sso login, az login, gcloud auth login One person's daily work Nothing relevant: it expires on its own
Role assumption (assume_role) One role per environment, assumed from a base account Teams, dev/prod separation Misconfiguring the trust relationship
Machine identity EC2 instance profile, Azure managed identity, GCE service account Self-hosted runners The whole machine inherits the permissions
Federated OIDC in CI The pipeline exchanges a signed token for temporary credentials Production, always Misconfiguring the trust condition (see module 8)

The progression has a logic to it: each step reduces the lifetime of the secret and the number of places where it exists. The final destination, OIDC, removes the long-lived secret entirely: there is nothing to rotate because there is nothing stored. You will see it in detail in Integrating Terraform with CI/CD; here it is enough to know that it is the goal, and that static credentials in a pipeline are technical debt from day one.

This is how EcoMarket's provider looks for local work. Note that no secret appears anywhere:

# infra/app/providers.tf
provider "aws" {
  region = var.region

  # The profile is resolved against ~/.aws/config. Its contents are not in the repo.
  profile = var.aws_profile

  # Automatic tagging of everything this provider creates.
  default_tags {
    tags = {
      Project   = var.project
      ManagedBy = "terraform"
      Repo      = "ecomarket-infra"
    }
  }
}

And role assumption, the pattern EcoMarket adopts as soon as there is more than one account:

provider "aws" {
  region = var.region

  assume_role {
    # Fictional identifier: 123456789012 is the example account ID.
    role_arn     = "arn:aws:iam::123456789012:role/ecomarket-terraform-${var.environment}"
    session_name = "terraform-${var.environment}-${var.operator}"

    # External identifier: avoids the "confused deputy" problem.
    external_id = var.external_id
  }
}

Three details with practical consequences:

  • session_name shows up in CloudTrail. If every apply uses the same session name, the audit trail cannot tell who did what. Including the operator or the pipeline run identifier turns the log into something useful.
  • external_id is mandatory when a third party assumes the role (a SaaS tool, for instance). Between your own accounts it is optional, but it does no harm.
  • The base credential still exists: to assume a role you have to be authenticated as something. That "something" should be a user with no permissions beyond assuming roles, or an SSO session.

Security warning. The role Terraform uses is, in practice, the most powerful principal in the account: it creates networks, databases and IAM roles. Defining its permissions is a decision for the security team, not the platform team. At a minimum: one role per environment, with no cross-environment permissions, with prod restricted to the pipeline rather than to people, and with an explicit policy of which actions are forbidden even for it. This is covered in Security Best Practices.

  1. Region, account and the risk of pointing at the wrong place

With the local provider there was no way to apply in the wrong place. Now there are two, and both happen:

  1. Applying in the wrong account. Environment variables persist between terminals. AWS_PROFILE=ecomarket-prod exported yesterday is still exported today.
  2. Applying in the wrong region. The resources appear where nobody looks for them, they are invisible in the console because the region selector is somewhere else, and they keep billing.

EcoMarket's discipline is to verify before every working session what you are working against:

# AWS: who am I and in which account
aws sts get-caller-identity
# {
#     "UserId": "AROAEXAMPLEID:terraform-dev-jcosta",
#     "Account": "123456789012",
#     "Arn": "arn:aws:sts::123456789012:assumed-role/ecomarket-terraform-dev/terraform-dev-jcosta"
# }

# Azure: active subscription
az account show --query "{name:name, id:id, tenant:tenantId}" -o table

# GCP: active project and account
gcloud config list --format="value(core.project, core.account)"

And an automatic control that costs five lines and prevents a once-in-a-lifetime accident. It relies on data and on the preconditions you will see formally in Preconditions, Postconditions and check Blocks:

# infra/app/guards.tf
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}

locals {
  # Map of environment -> expected account. Fictional identifiers.
  expected_accounts = {
    dev     = "123456789012"
    staging = "123456789013"
    prod    = "123456789014"
  }
}

check "correct_account" {
  assert {
    condition = data.aws_caller_identity.current.account_id == local.expected_accounts[var.environment]
    error_message = format(
      "You are authenticated against account %s but the '%s' environment lives in %s. Check AWS_PROFILE.",
      data.aws_caller_identity.current.account_id,
      var.environment,
      local.expected_accounts[var.environment],
    )
  }
}

This check block warns on every plan without blocking. If you would rather it prevented the apply, the same condition as a precondition on a resource turns it into a hard error. For prod, make it a hard error.

  1. The plan/apply cycle revisited on real infrastructure

The cycle is the same one you have known since module 1, but it is worth looking at again knowing what sits behind each phase:

flowchart TD
    A["terraform plan"] --> B["1. Loads configuration<br/>and state"]
    B --> C["2. REFRESH<br/>one API call<br/>per managed resource"]
    C --> D["3. Resolves data sources<br/>read-only calls"]
    D --> E["4. Builds the graph<br/>and computes the diff"]
    E --> F{"Any changes?"}
    F -->|No| G["No changes.<br/>Done"]
    F -->|Yes| H["Shows the plan<br/>+, -, ~, -/+"]
    H --> I["terraform apply"]
    I --> J["5. Walks the graph<br/>in parallel<br/>respecting dependencies"]
    J --> K{"Did every<br/>operation succeed?"}
    K -->|Yes| L["State updated.<br/>Resources created"]
    K -->|No| M["State updated<br/>PARTIALLY<br/>+ tainted resources"]

    style C fill:#fef3c7,stroke:#d97706
    style J fill:#dbeafe,stroke:#2563eb
    style M fill:#fee2e2,stroke:#dc2626

The two coloured boxes are the ones that change in nature when you move to the cloud:

  • The refresh (step 2) stops being free. Every resource in state means at least one API call to ask "do you still exist and how are you doing?". With 20 resources it is imperceptible. With 300, it is 300 calls.
  • Execution (step 5) stops being instantaneous and stops being atomic. And the red box, the partial failure, did not exist before.

  1. Refreshing when there are 300 resources: -refresh=false and -parallelism

The refresh is what lets Terraform detect drift — somebody changed something by hand — as you studied in Understanding State. Its cost grows linearly with the number of resources:

State size Typical refresh duration How it feels
20 resources 2-5 seconds Unnoticeable
100 resources 15-30 seconds Annoying when iterating
300 resources 1-3 minutes Interrupts your workflow
1000+ resources 5-15 minutes, with a risk of throttling Unsustainable: the state has to be split

The last row is a diagnosis, not an inconvenience: if the refresh takes ten minutes, the problem is the size of the state, and the fix is to split it into per-component configurations, exactly as you did with network, data and app in 04-05. The flags that follow are painkillers, not a cure.

# Skip the refresh: use the state exactly as it is, without asking the API.
terraform plan -refresh=false

# Limit concurrent operations (10 by default).
terraform apply -parallelism=5

-refresh=false: when yes and when no.

Situation Use it? Reason
Iterating on a pure HCL change (renaming, reorganising) that you have just refreshed Yes Nothing has changed in the cloud in the last 30 seconds
A production plan that is going to be applied No You would be applying on assumptions; if there is drift, the apply will fail or overwrite changes
Huge state and you only want to validate syntax Yes, but terraform validate is better validate does not touch the state at all
After somebody has been in the console No That is precisely when the refresh is indispensable

The right way to see only the drift, without planning changes, is the one you already know:

terraform plan -refresh-only

-parallelism: when to lower it and when to leave it alone. The default, 10, is a reasonable balance. You lower it in two cases: when the API is throttling you (RequestLimitExceeded, TooManyRequestsException) and when you want to reduce the blast radius of an apply that might go wrong. Raising it rarely helps: the bottleneck is almost never Terraform's parallelism but the API or the graph's dependencies. And raising it increases the chance of throttling, which in turn slows everything down.

  1. -target: the emergency tool and its warnings

-target limits the operation to one resource and its dependencies:

terraform apply -target=module.data.aws_db_instance.main

Terraform prints this warning, and it is not decorative:

╷
│ Warning: Resource targeting is in effect
│
│ You are creating a plan with the -target option, which specifies a subset of
│ resources to include in the plan. The plan will not include changes for
│ excluded resources, and Terraform cannot guarantee that the resulting
│ infrastructure will be consistent with your configuration.
╵

What it is saying, in practical terms: the result can be an infrastructure that matches no version of the code at all. If the VPC's CIDR and the security group rules changed together and you only apply the security group, the result is neither the old thing nor the new one.

Use of -target Legitimate? Comment
Recovering a specific resource after a failed apply Yes This is the use case it exists for
Applying an urgent production change "to go faster" No It creates drift between code and infrastructure. Apply the full plan
Avoiding a resource the plan wants to destroy No The symptom is a bug in the code. Fix it, or use lifecycle
Debugging a suspicious dependency Yes, in dev Useful to see what a resource drags along with it
Routinely, because the full apply takes too long No That is the sign that the state needs splitting

The rule EcoMarket uses: -target may appear in a terminal, never in a pipeline. If it is used, the next apply must be complete and without -target, to confirm that no difference is left behind.

  1. -out=plan.tfplan: why production applies the exact file

This is the most important change of habit in the lesson.

# 1. Plan and save
terraform plan -out=plan.tfplan

# 2. Review (human, or automated)
terraform show plan.tfplan

# 3. Apply EXACTLY that plan
terraform apply plan.tfplan

When you run terraform apply with no argument, Terraform computes a new plan and asks you to confirm it. Between the plan you read and the one that gets applied, things can have changed:

Risk of apply without a plan file Consequence
Somebody else applied something while you were reading the plan You apply on a state different from the one you reviewed
A data source now returns a different value (a new AMI, for example) The applied plan replaces instances the reviewed plan did not touch
Somebody used the console The refresh detects drift and the plan changes
You changed an environment variable without noticing You apply with different values

With -out, the plan is an immutable contract: it contains the exact actions, the resolved values and the serial of the state it was computed against. If the state has moved on, apply refuses:

╷
│ Error: Saved plan is stale
│
│ The given plan file can no longer be applied because the state was changed
│ by another operation after the plan was created.
╵

That error is a feature, not an obstacle. It is the mechanism that stops you applying a plan reviewed twenty minutes ago against a different reality.

Three warnings about the plan file:

  • It contains sensitive values in the clear. The PostgreSQL password you passed through TF_VAR_db_password is inside it. Treat it as a secret: restrictive permissions, encrypted artefact in the pipeline, deleted after the apply. It never goes into Git and is never attached to a ticket.
  • It is tied to the Terraform and provider versions it was generated with. A plan created with AWS 5.40 will not apply with AWS 5.60.
  • In practice it expires. The more time passes between plan and apply, the more likely it is to be stale. EcoMarket's flow is: plan on the pull request, review the same day, apply after approval. If days go by, it is re-planned.

  1. Reading a complex plan: symbols, replacements and (known after apply)

The symbols are already familiar, but now each one has a price:

Symbol Action What it means in the cloud
+ create Billing starts. It can take minutes
- destroy Irreversible. The data is lost unless there is a backup
~ update in-place Modification through the API; the resource survives
-/+ replace Destroys and recreates: new IP, new identifier, data lost, downtime
+/- replace (create before destroy) Creates the new one before destroying the old one: no downtime, but both exist at once (momentary double cost)
<= read (data source) Read-only. Harmless
(no symbol, "will be read during apply") deferred data Its value depends on something that does not exist yet

The line to look for always before a production apply:

  # module.data.aws_db_instance.main must be replaced
-/+ resource "aws_db_instance" "main" {
      ~ id                    = "ecomarket-prod-db" -> (known after apply)
      ~ engine_version        = "15.4" -> "16.1"
      ~ identifier            = "ecomarket-prod-db" -> "ecomarket-prod-postgres" # forces replacement
      ~ endpoint              = "ecomarket-prod-db.abc123.eu-west-1.rds.amazonaws.com" -> (known after apply)
        # (32 unchanged attributes hidden)
    }

Plan: 1 to add, 0 to change, 1 to destroy.

Three things to read here, in order:

  1. # forces replacement. It marks the guilty attribute. Here, changing identifier forces the whole database to be recreated. engine_version could be upgraded in place; identifier cannot. A single attribute can destroy a production database, and the only defence is reading this label.
  2. (known after apply). It means the value is decided by the provider and Terraform cannot know it in advance: identifiers, ARNs, IP addresses, endpoints. It is not a problem in itself, but it hides information: if the endpoint is unknown, everything that depends on it will be unknown too, and the plan becomes less informative downstream. That is why a from-scratch creation plan is always more opaque than an incremental one.
  3. The final summary. 1 to add, 0 to change, 1 to destroy on a change that was meant to be a minor update is the alarm signal. The destroy count is the metric you never ignore.

And a warning about # (32 unchanged attributes hidden): by default Terraform hides what does not change, which is good for readability and bad for auditing. To see everything:

terraform show plan.tfplan          # readable, with everything relevant
terraform plan -no-color > plan.txt # to attach to a review

  1. Auditing a large plan with terraform show -json and jq

When a plan has 150 changes, reading it all is unrealistic and skimming it is worse than not reading it. The answer is to convert it to JSON and ask specific questions:

terraform show -json plan.tfplan > plan.json

The relevant structure is resource_changes[], where each element has address, type and a change object with actions (a list such as ["create"], ["delete"], ["delete","create"]) and the before and after values.

Query 1 — the most important question: what gets destroyed?

jq -r '
  .resource_changes[]
  | select(.change.actions | index("delete"))
  | "\(.change.actions | join("+"))\t\(.address)"
' plan.json
delete+create	module.data.aws_db_instance.main
delete	module.network.aws_nat_gateway.egress[0]

Two lines that demand explicit justification before going any further.

Query 2 — a count per action type, to compare against what you expected:

jq -r '
  [.resource_changes[] | .change.actions | join("+")]
  | group_by(.) | map({action: .[0], total: length})
  | .[] | "\(.total)\t\(.action)"
' plan.json
23	create
4	update
1	delete+create
2	no-op

This is the output a module's CHANGELOG should anticipate, as you saw in 04-05: "expect 23 creations and one replacement of the database".

Query 3 — which resources cost money, grouped by type:

jq -r '
  [ .resource_changes[]
    | select(.change.actions | index("create"))
    | .type ]
  | group_by(.) | map({type: .[0], n: length})
  | sort_by(-.n) | .[] | "\(.n)\t\(.type)"
' plan.json

Query 4 — an automatic control for the pipeline: fail if there are unapproved destructions.

#!/usr/bin/env bash
# scripts/check-plan.sh — runs after the plan in CI
set -euo pipefail

terraform show -json plan.tfplan > plan.json

destroyed=$(jq -r '
  [.resource_changes[] | select(.change.actions | index("delete")) | .address]
  | length' plan.json)

if [[ "$destroyed" -gt 0 && "${ALLOW_DESTROY:-no}" != "yes" ]]; then
  echo "ERROR: the plan destroys $destroyed resource(s):"
  jq -r '.resource_changes[] | select(.change.actions | index("delete")) | "  - " + .address' plan.json
  echo "If this is intentional, re-run with ALLOW_DESTROY=yes and a justification in the PR."
  exit 1
fi

echo "OK: the plan destroys nothing."

This script, at twenty lines, is the single control that prevents the most incidents in a team using Terraform. The full version of the flow in a pipeline arrives in module 8, and the formal policies (OPA, Sentinel) in 07-04.

  1. Time as a dimension: slow resources and timeouts blocks

Orders of magnitude worth internalising before your first real apply:

Resource Typical creation Typical destruction Note
Security group / firewall rule 1-3 s 1-3 s Immediate
Object bucket 2-5 s 2-5 s (if empty) Deletion fails if it has contents
VPC / virtual network 5-15 s 10-30 s Fast
NAT gateway 1-3 min 1-2 min Slow and expensive
Compute instance 30-90 s 30-60 s OS boot happens separately
Load balancer 2-4 min 2-5 min It has to propagate
Managed database (single zone) 5-10 min 3-8 min With a final snapshot, longer
Managed database (high availability) 10-25 min 5-15 min The slowest common case
Managed Kubernetes cluster 10-20 min 10-20 min Out of scope for this module

The operational consequence: a full apply of EcoMarket's prod environment takes between 15 and 30 minutes. That changes how a deployment window is planned, and explains why the per-component state separation you did in module 4 was not an organisational whim.

When the provider's default is not enough, there is the timeouts block:

resource "aws_db_instance" "main" {
  identifier     = "${var.base_name}-postgres"
  engine         = "postgres"
  engine_version = "16.3"
  instance_class = var.db_class
  # ... remaining attributes

  timeouts {
    create = "60m"   # restoring from a large snapshot can exceed 40 min
    update = "80m"   # a class change with high availability is slow
    delete = "60m"   # the final snapshot of a large DB takes time
  }
}

Four clarifications:

  • Not every resource supports timeouts, and those that do not always support all three actions. The resource documentation says so.
  • Extending a timeout does not speed anything up. It only stops Terraform giving up before the operation finishes.
  • An exhausted timeout leaves the resource half-done: created in the cloud but possibly not recorded in state. It is one of the roads to the orphan resources you will see in 09-03.
  • A timeout that is too long masks a real failure. If an operation that usually takes 8 minutes has been running for 55, it is almost never going to end well.

  1. When apply fails halfway: tainted resources and recovery

This scenario did not exist with the local provider and is routine in the cloud. Terraform applies 40 resources, the 41st fails, and the previous 40 are created and billing.

module.network.aws_vpc.main: Creation complete after 7s [id=vpc-0a1b2c3d4e5f67890]
module.network.aws_subnet.private["eu-west-1a"]: Creation complete after 3s [id=subnet-0abc...]
module.data.aws_db_instance.main: Still creating... [9m20s elapsed]
╷
│ Error: creating RDS DB Instance (ecomarket-dev-postgres): InvalidParameterValue:
│ Invalid DB engine version 16.9 for engine postgres
╵

Releasing state lock. This may take a few moments...

What Terraform guarantees at this point:

  1. The state is saved with whatever did get created. The record of the VPC and the subnets is not lost. That is why locking, which you saw in 03-04, is critical: an interrupted apply must release the state consistently.
  2. Resources that failed during creation are marked. Historically this was called tainted; the state records it with "status": "tainted" on the resource instance.
  3. Running apply again continues where it left off: it does not recreate what already exists, but it does replace what is tainted.

A tainted resource is one that was created but whose provisioning did not finish correctly — typically because a provisioner failed, which you will see in 05-05. Terraform treats it as suspect and destroys and recreates it on the next apply:

  # aws_instance.web is tainted, so must be replaced
-/+ resource "aws_instance" "web" {

The relevant commands, and their current status:

# MODERN form (Terraform 0.15.2+): mark for replacement in the next plan.
terraform plan  -replace="aws_instance.web"
terraform apply -replace="aws_instance.web"

# OLD form, discouraged: it modifies the state directly.
terraform taint   aws_instance.web    # deprecated
terraform untaint aws_instance.web    # still useful for clearing the mark

The difference is philosophical and it matters: taint modifies the state immediately; -replace is an instruction for the plan. With -replace you see the replacement in the plan before accepting it, you can save it with -out and you can back out without having touched anything. That is why taint was deprecated.

untaint does remain useful in one specific case: the resource was created correctly, a provisioner failed for an unrelated reason (a package repository was down), you fixed it by hand and you know the resource is healthy. Clearing the mark avoids destroying and recreating an instance that works. It requires being certain, because you are contradicting Terraform about the state of reality.

The worst case: created in the cloud, absent from state. This happens if the process dies between the API call and the state write (a double Ctrl+C, a network drop, an exhausted timeout). Terraform does not know that resource exists, so the next apply tries to create it again and fails with a duplicate-name error. The fix is terraform import (or the import block), covered in Importing Resources. What you need now is to recognise the symptom: "already exists" on a resource you believe you never created.

  1. Typical API errors and how Terraform reacts

Four families of error cover most of what you will see in the first month:

Family Typical message Does Terraform retry? What to do
Quota / limit VpcLimitExceeded, QuotaExceeded, Quota 'CPUS' exceeded No Request a quota increase, or ask for less. It can take days
Rate limit Throttling, RequestLimitExceeded, 429 Yes, with exponential backoff Lower -parallelism. If it persists, split the state
Permissions AccessDenied, UnauthorizedOperation, 403 No A permission is missing from the role. The message usually names the exact action
Eventual consistency InvalidGroup.NotFound on something just created Sometimes, depending on the provider Usually resolves itself on retry. If it is systematic, a dependency is missing

The middle two are worth dwelling on.

Rate limits are handled by the provider, not by Terraform. The AWS, Azure and GCP providers implement retries with exponential backoff and jitter inside the SDK. That is why an apply can take longer than expected without producing any error at all: it is waiting between retries. If the error does surface anyway, the provider has already exhausted its retries, and the right response is to reduce concurrency:

terraform apply -parallelism=3

Eventual consistency is the most baffling cause. A real, reproducible example: you create an IAM role and an instance that uses it through an instance profile. Terraform creates the role, and immediately afterwards creates the instance; the compute API replies that the instance profile does not exist. It does exist: it simply has not propagated to every service yet.

Mature providers have internal waits for the known cases. For the ones they do not cover, the way out is an explicit dependency or, in the worst case, a wait:

# Explicit dependency: it does not change the timing, but it guarantees the order.
resource "aws_instance" "web" {
  # ...
  depends_on = [aws_iam_role_policy_attachment.web]
}

# Explicit wait: a LAST resort, and always with a comment justifying it.
resource "time_sleep" "iam_propagation" {
  depends_on      = [aws_iam_role_policy_attachment.web]
  create_duration = "15s"
}

Tip. Before adding a time_sleep, check two things: that the error really is a propagation one (retrying the apply without changing anything works) and that you are not simply missing a reference that would create the right edge in the graph. A time_sleep is a confession that you could not express the dependency; sometimes it is the right answer, but it is almost never the first one.

  1. Cost: estimate before applying, allocate and destroy

This section is what separates a lab from a professional environment.

Estimate before applying. The plan tells you what gets created, not how much it costs. The most widely used tool for closing that gap is Infracost, which reads the plan in JSON and puts a price on it:

terraform plan -out=plan.tfplan
terraform show -json plan.tfplan > plan.json

infracost breakdown --path plan.json
 Name                                      Monthly Qty  Unit    Monthly Cost

 module.network.aws_nat_gateway.egress[0]
 ├─ NAT gateway                                    730  hours         $32.85
 └─ Data processed                                  50  GB             $2.25

 module.data.aws_db_instance.main
 ├─ Database instance (db.t3.small, Single-AZ)     730  hours         $26.28
 └─ Storage (gp3)                                   20  GB             $2.76

 OVERALL TOTAL                                                        $64.14

Two warnings about any estimate: it only covers what can be predicted (it cannot guess how many GB you will transfer) and prices change. All the figures in this module are orders of magnitude for eu-west-1 at the time of writing, not a price list. Always check your provider's official calculator.

Tag to allocate. EcoMarket's common tags are not decorative: they are the mechanism by which the finance team knows which part of the bill corresponds to what. The provider's default_tags is the most reliable way to guarantee that nothing slips through untagged:

provider "aws" {
  region = var.region

  default_tags {
    tags = {
      Project     = var.project         # ecomarket
      Environment = var.environment     # dev | staging | prod
      ManagedBy   = "terraform"
      CostCenter  = local.current.cost_center
      Owner       = "[email protected]"
    }
  }
}

Three nuances with consequences:

  • Not every resource supports tags (some associations and rules, for example). Tags cover most of the spend, not 100 % of the objects.
  • default_tags and tags are merged, and the resource's value wins over the provider's when the key matches.
  • Tagging is a decision subject to FinOps review. The tag schema (which keys, with which allowed values) is set by the organisation, not by each team. If EcoMarket has cost centres, their valid values should be enforced with a validation, not left to nobody mistyping them.

The destroy discipline. In a practice environment it is mandatory and non-negotiable:

terraform destroy

One concrete habit that saves money: at the end of every exercise in this module, destroy; and before closing your laptop, check that nothing is left:

# Is anything left in state?
terraform state list

# A check independent of state, in case there are orphans (AWS):
aws resourcegroupstaggingapi get-resources \
  --tag-filters Key=Project,Values=ecomarket \
  --query 'ResourceTagMappingList[].ResourceARN' --output table

That second check is the important one: terraform destroy only destroys what is in the state. Anything that was created and then lost (through a partial failure, a misused -target, a manual test) does not show up and keeps billing. The tag query finds it.

And two more habits, which are not Terraform's but belong in this lesson: set up a budget alert on your practice account (AWS Budgets, Azure Cost Management, Google Cloud Budgets) with a low threshold, 5 or 10 euros, and check the cost dashboard every morning for the first few days. The cost of learning in the cloud is real but small if it is measured; the stories about surprise bills are always stories about nobody looking.

  1. Deployment order and real dependencies

Terraform derives the order from the reference graph, and that does not change. What changes is that the order now has consequences in time and in failure, and that there are real dependencies that no reference expresses.

flowchart LR
    subgraph F0["Phase 0 — prerequisites"]
        API["APIs enabled<br/>(GCP)<br/>Sufficient quotas"]
    end
    subgraph F1["Phase 1 — network (5-8 min)"]
        VPC["VPC / VNet"] --> SUB["Subnets"]
        SUB --> RT["Route tables<br/>IGW / NAT"]
        RT --> SG["Security groups"]
    end
    subgraph F2["Phase 2 — data (10-25 min)"]
        DBS["Subnet group"] --> BD[("PostgreSQL")]
        BK["Images bucket"]
    end
    subgraph F3["Phase 3 — application (4-6 min)"]
        IAM["Role + instance<br/>profile"] --> LT["Launch<br/>template"]
        LT --> ASG["Auto Scaling<br/>group"]
        ASG --> LB["Load balancer"]
    end

    F0 --> F1
    F1 --> F2
    F2 --> F3

    style F0 fill:#f3f4f6,stroke:#6b7280
    style F2 fill:#fef3c7,stroke:#d97706
    style F3 fill:#dbeafe,stroke:#2563eb

This diagram is the reason for the module separation you already have: network → data → app is not just a way of organising the code, it is the physical order in which the cloud can build things. And it explains two operational decisions:

  • Phase 2 dominates the total time. If the full apply takes 25 minutes, 15 of them are the database. That is why it makes sense for data to live in its own state: application deployments, which are daily, should not wait for the refresh of a database that changes twice a year.
  • Phase 0 is not in Terraform's graph by default and is the source of the most baffling error in GCP: applying before the service API is enabled. It is solved with google_project_service and depends_on, and detailed in 05-04.

  1. Immutable versus mutable resources in the cloud

The last concept in the lesson is the one that explains half of all surprise replacements.

Every attribute of every resource is, as far as the provider is concerned, updatable in place or not. If it is not, it is internally flagged as ForceNew, and changing it produces a -/+ in the plan. This is not Terraform's decision: it reflects what the cloud API allows.

Change In place? Why
Tags on almost any resource Yes There is a specific API call for tagging
Database instance class Yes (with a restart) The API supports ModifyDBInstance
Major database engine version Yes (within a window) There is a managed upgrade
Identifier of a database No The name is part of the resource's identity
Availability zone of a subnet No A subnet physically belongs to one zone
CIDR of a VPC No You can add a range, not change the primary one
Type of a compute instance Yes (with a stop) The API supports changing the type while powered off
Image (AMI) of an instance No The boot disk is defined at creation time
Name of an object bucket No The name is the global identity
Rules of a security group Yes Rules are added and removed individually

Two useful patterns follow from this table:

1. Create before destroy, for the unavoidable replacements. If a resource has to be replaced and you cannot afford the downtime:

resource "aws_instance" "web" {
  # ...
  lifecycle {
    create_before_destroy = true
  }
}

With this, Terraform creates the replacement and only then destroys the original. Two warnings: during the transition both exist and you pay for both, and the pattern breaks if something is globally unique (a name, a fixed IP), because the new one cannot be created while the old one holds it. The fix in that case is a random suffix or a name_prefix, which is exactly what EcoMarket introduced random_pet.suffix for in module 4.

2. Protect the irreplaceable. For anything that must never be destroyed from Terraform:

resource "aws_db_instance" "main" {
  # ...
  deletion_protection = var.environment == "prod"   # barrier on the cloud side

  lifecycle {
    prevent_destroy = true                          # barrier on the Terraform side
  }
}

The two barriers are complementary and neither replaces the other:

Barrier Where it lives What it stops How it is bypassed
prevent_destroy In the Terraform code Any plan that destroys that resource, including terraform destroy By editing the code
deletion_protection In the cloud Any deletion, wherever it comes from (console, CLI, Terraform) By setting it to false and applying that first

The detail that surprises people: with deletion_protection = true, terraform destroy fails halfway, after having destroyed other things. Turning the protection off is a separate, deliberate apply beforehand. That friction is intentional.

Common Mistakes and Tips

Applying in the wrong account or region. It is the most expensive mistake of the first few days. Symptom: the resources "do not show up" in the console. Prevention: aws sts get-caller-identity before every session, the check block from section 3, and region always from a variable, never from an implicit default.

Skipping the plan because "it is a small change". 100 % of the databases destroyed by accident were in a plan somebody did not read. Always look for # forces replacement and the destroy count. If the plan has more than 30 changes, do not read it: query it with jq.

Trusting terraform destroy as your only cleanup. It only deletes what is in the state. After a failed apply or a -target, there can be resources created but not recorded. Always check by tag after destroying, and set up a budget alert.

Using -refresh=false on a plan that will be applied. It saves a minute and applies on assumptions. Accept it while you iterate on HCL; never on the plan that goes to production.

Turning -target into routine. Every use leaves a potential difference between code and infrastructure. Use it to recover from a failure, and always do a full apply afterwards to confirm nothing is left pending.

Applying without -out in production. The plan you reviewed and the one that gets applied can be different. Save it, review it, apply the file. And treat that file as a secret: it contains passwords in the clear.

Raising -parallelism to go faster. It almost never helps and usually causes throttling, which slows everything down. If the apply is slow, the problem is the size of the state or the latency of one specific resource.

Adding a time_sleep at the first strange error. First check whether retrying works (then it really is propagation) and whether a reference is missing that would create the right edge. A sleep with no comment justifying it is guaranteed debt.

Tip: start in dev and with the cheap things. The learning order in this module is deliberate: network first (almost free except for NAT), then storage (cents), then compute (free tier), and the database last. Never try out an expensive resource in an environment you cannot destroy.

Tip: put the destroy in your calendar. Literally. A daily reminder for as long as this module lasts. Most surprise bills come from resources created on a Friday.

Tip: anything that affects permissions, public networks or encryption is reviewed with the security team; anything that creates hourly resources is reviewed with FinOps. This is not bureaucracy: it is that neither of those two groups reads plan output on their own, and the code is the only opportunity for them to do so before it exists.

Exercises

Exercise 1: reading and auditing a complex plan

Starting from this (trimmed) plan.json fragment, answer without running anything:

{
  "resource_changes": [
    {
      "address": "module.network.aws_vpc.main",
      "type": "aws_vpc",
      "change": { "actions": ["no-op"] }
    },
    {
      "address": "module.network.aws_nat_gateway.egress[0]",
      "type": "aws_nat_gateway",
      "change": { "actions": ["create"] }
    },
    {
      "address": "module.data.aws_db_instance.main",
      "type": "aws_db_instance",
      "change": { "actions": ["delete", "create"] }
    },
    {
      "address": "module.app.aws_instance.web[2]",
      "type": "aws_instance",
      "change": { "actions": ["delete"] }
    },
    {
      "address": "module.data.aws_s3_bucket.images",
      "type": "aws_s3_bucket",
      "change": { "actions": ["update"] }
    }
  ]
}
  1. Write the summary line Terraform would print (Plan: X to add, Y to change, Z to destroy).
  2. Identify the change that demands explicit justification before applying in production and explain what would have to be checked beforehand.
  3. Write the jq query that lists only the addresses with some kind of delete action.
  4. Which of these changes increases the monthly bill the most, and why?

Exercise 2: designing EcoMarket's apply procedure

On paper, write a production apply procedure for ecomarket-infra that includes:

  1. The exact commands, in order, from the identity check to the confirmation afterwards.
  2. What gets checked between the plan and the apply, and who checks it.
  3. Where the plan file is kept, for how long and with what protection.
  4. A table with the three flags (-refresh=false, -target, -parallelism) stating whether they are allowed in prod and under what condition.
  5. How to handle an apply that fails halfway: the first three steps, in order, before touching anything.

Exercise 3: preparing the practice account

Before the next lesson, get a lab account ready in the cloud of your choice:

  1. Configure authentication without putting a single secret in a .tf file and verify the identity with the corresponding command.
  2. Create a budget alert with a €10 threshold and notification to your email.
  3. Write the check block (or precondition) that prevents applying against an account other than the expected one.
  4. Write the end-of-exercise checklist: the commands you will run every time you finish, including the search for orphans by tag.
  5. Find out and note down three default quotas for your account in eu-west-1: number of VPCs, of elastic IP addresses and of database instances.

Solution 1

1. Summary line. The actions are counted like this: no-op does not count; create is an add; delete+create counts at once as an add and a destroy (it is a replacement); delete alone is a destroy; update is a change.

Plan: 2 to add, 1 to change, 2 to destroy.

2. The change that demands justification is module.data.aws_db_instance.main with ["delete","create"]: a replacement of the production database. Before applying you have to check:

  • Which attribute carries # forces replacement in the readable output (terraform show plan.tfplan).
  • Whether there is an in-place alternative (there almost always is: renaming via moved, upgrading the engine version in a managed way, or reverting the identifier change).
  • Whether there is a recent, verified backup, and whether skip_final_snapshot is set to false.
  • How long the downtime lasts and whether there is an agreed window.
  • Whether prevent_destroy should have been enabled, because its absence is itself a finding.

Deleting module.app.aws_instance.web[2] deserves a second look for a different reason: a numeric index disappearing suggests a count was reduced, and you already know from 02-03 that this can shift instances around instead of removing the one you meant to remove.

3. jq query:

jq -r '.resource_changes[]
       | select(.change.actions | index("delete"))
       | .address' plan.json
module.data.aws_db_instance.main
module.app.aws_instance.web[2]

4. The one that raises the bill most is aws_nat_gateway. It is the only new resource with a continuous hourly cost and no free tier: around $0.045/hour (≈$33/month in eu-west-1) plus data processing, regardless of traffic. Replacing the database does not increase the recurring cost (the class is the same), although there may be momentary double cost during the replacement; deleting a web instance reduces it; and updating a bucket has no associated cost. The NAT gateway is, by some margin, the most frequent cost trap in development environments: it gets created "because we need Internet egress" and stays switched on for months.

Solution 2

1. Commands in order:

# a) Verify identity and environment
aws sts get-caller-identity
echo "Environment: ${TF_VAR_environment:?not set}"

# b) Initialise with the environment's backend
terraform init -backend-config=backend-prod.hcl -reconfigure

# c) Static checks before spending API time
terraform fmt -check -recursive
terraform validate

# d) Saved plan
terraform plan -var-file=common.auto.tfvars -var-file=prod.tfvars -out=plan.tfplan

# e) Automatic audit of the plan
terraform show -json plan.tfplan > plan.json
./scripts/check-plan.sh

# f) Human review
terraform show plan.tfplan | tee plan-readable.txt

# g) Applying the EXACT plan that was reviewed
terraform apply plan.tfplan

# h) Confirmation afterwards: no difference should remain
terraform plan -var-file=common.auto.tfvars -var-file=prod.tfvars -detailed-exitcode

Step (h) is the one most often forgotten and the most informative: -detailed-exitcode returns 0 if there are no changes and 2 if there are. A 2 immediately after an apply means something did not converge and it has to be investigated before calling the deployment good.

2. Between the plan and the apply four things are checked: the destruction count (automatically, with the script); that every # forces replacement has a written justification in the pull request; the cost estimate of the delta; and that the plan corresponds to the commit that was reviewed. The automatic check is done by the pipeline; the human review, by somebody other than whoever wrote the change. For prod, additionally, sign-off from security if the plan touches IAM, ingress rules or encryption.

3. The plan file is kept as an encrypted pipeline artefact, with short retention (24-48 hours), access restricted to the platform team, and deleted after the apply. Never in the repository, never attached to a ticket, never in a chat: it contains var.db_password in the clear.

4. Table of flags in prod:

Flag Allowed in prod? Condition
-refresh=false No The plan must reflect current reality. No exceptions
-target Only during incident recovery With an open incident, two people, and a full apply afterwards confirming convergence
-parallelism Yes, to lower it Lowering it is allowed when throttled. Raising it above the default is forbidden

5. Faced with a failed apply, the first three steps are:

  1. Do not run anything again. Read the full error and note how many resources completed and which one failed.
  2. Check that the lock was released (terraform force-unlock only with the checklist from 03-04, never out of habit) and that the remote state was saved: terraform state list should show what did get created.
  3. Run terraform plan to see what is still pending and what has been marked for replacement. Only after understanding that plan do you decide whether to retry, fix the code or roll back.

The order matters: retrying blindly on a state you have not inspected is how a recoverable failure turns into an incident.

Solution 3

1. Authentication with no secrets in .tf. The recommended option for a personal lab account is a profile with a temporary session:

# AWS with SSO / IAM Identity Center (preferred)
aws configure sso --profile ecomarket-lab
aws sso login --profile ecomarket-lab
export AWS_PROFILE=ecomarket-lab
aws sts get-caller-identity

In the code, the provider only references the profile through a variable: profile = var.aws_profile, with the value in dev.tfvars. If your account does not have SSO, a user with an access key in ~/.aws/credentials is acceptable for a lab, on two conditions: that the user has no billing or IAM permissions beyond what is needed, and that you rotate the key when you finish the module.

2. Budget alert. In AWS, Billing → Budgets → Create budget → Cost budget, amount €10, monthly period, alerts at 50 %, 80 % and 100 % of the forecast and also on actual spend. The Azure equivalent is a budget in Cost Management, and in GCP a budget with alerts in Billing. One detail that matters: configure the alert on forecast spend, not only actual, because it warns you sooner.

3. check block:

data "aws_caller_identity" "current" {}

variable "expected_account" {
  description = "ID of the account this environment must be applied to."
  type        = string

  validation {
    condition     = can(regex("^[0-9]{12}$", var.expected_account))
    error_message = "An AWS account ID is 12 digits."
  }
}

check "correct_account" {
  assert {
    condition     = data.aws_caller_identity.current.account_id == var.expected_account
    error_message = "Authenticated against ${data.aws_caller_identity.current.account_id}, expected ${var.expected_account}. Check AWS_PROFILE before continuing."
  }
}

For prod, use the same condition as a precondition on a central resource (the VPC, for example), so that it is a hard error and not a warning.

4. End-of-exercise checklist:

# 1. Destroy everything that is managed
terraform destroy -var-file=dev.tfvars

# 2. Confirm the state is empty
terraform state list        # should return nothing

# 3. Look for orphans by tag (what destroy does NOT cover)
aws resourcegroupstaggingapi get-resources \
  --tag-filters Key=Project,Values=ecomarket \
  --query 'ResourceTagMappingList[].ResourceARN' --output table

# 4. Check what survives by design and carries no tag
aws ec2 describe-addresses --query 'Addresses[].PublicIp'          # unassociated elastic IPs
aws rds describe-db-snapshots --snapshot-type manual --query 'DBSnapshots[].DBSnapshotIdentifier'
aws s3 ls                                                           # buckets with contents

# 5. Review the cost dashboard the next day

Points 3 and 4 are the ones that actually save money. Unassociated elastic IP addresses, manual snapshots and buckets with contents are exactly what survives a destroy and keeps billing quietly.

5. Default quotas in eu-west-1 (indicative values you should verify on your own account, because they vary):

# VPCs per region
aws service-quotas get-service-quota --service-code vpc --quota-code L-F678F1CE

# Elastic IPs per region
aws service-quotas get-service-quota --service-code ec2 --quota-code L-0263D0A3

# RDS instances per region
aws service-quotas get-service-quota --service-code rds --quota-code L-7B6409FD

The usual values are 5 VPCs, 5 elastic IP addresses and 40 database instances. The quota of 5 elastic IP addresses is the one that surprises people most: every NAT gateway consumes one, so three environments with two zones each are already brushing the limit. A quota increase is requested through Service Quotas and can take anything from minutes to days; it is worth asking before you need it.

Conclusion

This lesson has built the bridge between four modules of simulation and real deployment, and it has done so without touching a single cloud-specific resource, because everything above is common to all three:

  • What changes when you go to the cloud is not the language, it is the other side: latency, hourly cost, quotas, rate limits, eventual consistency, partial failures and irreversible operations.
  • Credentials never live in a .tf. The progression runs from environment variables to temporary sessions, role assumption and federated OIDC identity, and each step shortens the secret's lifetime until it disappears.
  • Verify account and region before every session with aws sts get-caller-identity and its equivalents, and encode that verification in a check so the mistake becomes impossible rather than unlikely.
  • The refresh costs one API call per resource. If it takes minutes, the diagnosis is that the state is too big; -refresh=false is an acceptable painkiller while iterating and forbidden on the plan that gets applied.
  • -target is an incident-recovery tool, not a way to go faster: it leaves the infrastructure at a point that matches no version of the code.
  • In production, the plan is saved with -out and that exact file is applied. It is an immutable contract, it refuses to apply if the state has moved on, and it contains secrets in the clear: treat it accordingly.
  • Reading a complex plan means looking for three things: # forces replacement, the destroy count and the (known after apply) values that obscure whatever comes next. Above thirty changes, the plan is not read: it is queried with terraform show -json and jq, and the deletion count becomes an automatic pipeline control.
  • Time is a real dimension: from 2 seconds for a firewall rule to 25 minutes for a highly available database. timeouts stop Terraform giving up too soon, they do not speed anything up, and an excessive one masks failures.
  • An apply can fail halfway, leaving created resources, resources marked for replacement and, in the worst case, existing resources outside the state. -replace supersedes the deprecated taint because you see it in the plan before it runs.
  • API errors fall into four families — quota, rate limit, permissions and eventual consistency — and each has a different answer; only the second is retried by the provider on its own.
  • Cost is estimated beforehand (Infracost over the JSON plan), allocated with tags (default_tags so nothing escapes) and controlled with destroy plus a search for orphans, because destroy only reaches what is in the state.
  • The order network → data → application is not code organisation: it is the physical order the cloud imposes, and the data phase dominates the total time.
  • Every attribute is either updatable in place or not, and the ones that are not produce replacements. create_before_destroy avoids downtime at the price of momentary double cost and demands unique names; prevent_destroy and deletion_protection are complementary barriers, one in the code and one in the cloud.

With that, EcoMarket is ready to go out for real. In the next lesson, Provisioning AWS Resources, the promise of module 4 is fulfilled: the network, data and app modules you wrote keep their interface, their locals, their tagging and their version, and inside them the local_file becomes aws_vpc, aws_subnet, aws_db_instance and aws_s3_bucket. You will see the VPC with its public and private subnets spread across zones, the NAT gateway with its cost warning in plain sight, PostgreSQL in private subnets with the password arriving through TF_VAR_db_password, the images bucket with its satellite resources for versioning and encryption, and the instance role that will let the web tier read the bucket without a single written credential. At the end, the endpoints output will stop containing paths to JSON files and will contain the real DNS name of a load balancer that responds.

© Copyright 2026. All rights reserved