Pair your devices with a code and playback position follows you: pause on this device, hit resume on the other. Position is saved to the site every minute and on pause.
Open this panel on your other device and enter the same code.
Starts this lesson and continues through 7 more to the end of the course.
The Glue job from lesson 1, the Redshift workgroup from lesson 3, the alarm from lesson 4 — if any of them was clicked into existence in the console, nobody can reproduce, review, or roll it back. This lesson is the Terraform you need to own those definitions without losing state, locking yourself out, or destroying a warehouse by accident.
What the posting is really asking. "Provision and manage AWS infrastructure using Terraform" means: you can write the resources for the data stack (Glue, EMR, Lambda, Redshift, Lake Formation, KMS, CloudWatch), keep state safely in S3 with locking, run it through a PR-plan / merge-apply pipeline with no long-lived AWS keys, and refactor without destroying anything. Each of those is a section below.
Provider resource docs below were read from the AWS provider's
website/docs/r/*.html.markdownfiles on GitHubmain— the source the Terraform Registry renders. The registry pages themselves are client-rendered and did not return text tocurl. Argument names are copied verbatim.
The core workflow (verified 2026-10-30) is three steps: Write (author config), Plan (preview changes), Apply (provision). The commands you actually type:
terraform init # install providers/modules, configure backend, write lock file
terraform plan -out=tfplan # saved plan — the artefact you review
terraform apply tfplan # applies exactly that plan, no prompt
terraform destroy # plan + apply a full teardown
From the apply reference: with no plan
file, apply creates a fresh plan and prompts; with a saved plan it "performs the operations in the
saved plan without prompting you for confirmation" — "the two-step workflow when running Terraform in
automation". -auto-approve skips the prompt, with the documented warning that you should then make
sure no one changes infrastructure outside Terraform.
⚠️ The plan reference says plan files
should be treated "as potentially-sensitive artifacts". Don't upload tfplan as a public CI artefact.
State maps config addresses to real AWS objects. Lose it and Terraform wants to recreate everything. Share it without locking and two applies corrupt it. The S3 backend (verified 2026-10-30):
terraform {
backend "s3" {
bucket = "mybucket"
key = "path/to/my/key"
region = "us-east-1"
use_lockfile = true
encrypt = true
}
}
| Locking option | Status in docs | Notes |
|---|---|---|
use_lockfile = true |
Current | "Whether to use a lockfile for locking the state file. Defaults to false." Lock object is <key>.tflock |
dynamodb_table |
Deprecated | "DynamoDB-based locking is deprecated and will be removed in a future minor version." Table needs partition key LockID (String) |
Both can be set simultaneously "to support migration from older versions of Terraform". The IAM
permissions differ: with use_lockfile, the role needs s3:GetObject, s3:PutObject and
s3:DeleteObject on the .tflock object; s3:DeleteObject is not required on the state object
"as Terraform does not delete it". kms_key_id encrypts state and lock files and then needs
kms:Encrypt, kms:Decrypt, kms:GenerateDataKey. The docs say it is "highly recommended" to turn on
bucket versioning for recovery.
⚠️ If you still have dynamodb_table in a backend block, plan the migration now; the docs flag removal
in a minor version.
CLI workspaces are "separate
instances of state data inside the same Terraform working directory". With the S3 backend, non-default
workspaces land at <workspace_key_prefix>/<workspace_name>/<key>, prefix defaulting to env:. The
docs are blunt: "Workspaces are not appropriate for system decomposition or deployments requiring
separate credentials and access controls." The CLI workspaces page
gives the alternative: reusable modules for the common parts, and "each instance as a separate
configuration that instantiates those common elements in the context of a different backend".
| CLI workspaces | Directory per env | |
|---|---|---|
| Backend / credentials | Shared — one bucket, one role | Separate per env (prod state in prod account) |
| Config drift between envs | None — same files | Possible, mitigated by versioned modules |
Blast radius of a wrong select |
Apply dev config to prod | Low — different directory and role |
| Docs' verdict | Fine for "quickly switch between multiple instances" | Recommended for separate credentials and access controls |
Prefer directory-per-env for a data platform, because prod Redshift and Lake Formation grants should sit behind a different role than dev.
Module sources: registry
(source = "terraform-aws-modules/vpc/aws" plus a version constraint), Git
(git::https://example.com/vpc.git?ref=v1.2.0), object storage, local paths. Changing source or
version requires re-running terraform init; -upgrade moves installed modules to the newest allowed.
Variables precedence, highest
first: -var / -var-file on the command line (in order), then *.auto.tfvars (lexical order),
terraform.tfvars.json, terraform.tfvars, then the default. Environment variables use TF_VAR_name.
sensitive = true hides a value in CLI output but "Terraform still stores the values of sensitive
variables in your state"; the ephemeral argument omits it from state and plan files.
Outputs are how a child module
exposes attributes, and root outputs are what another configuration reads via terraform_remote_state.
Locals are named expressions reused within a module.
for_each vs countFrom for_each and count (verified 2026-10-30):
count |
for_each |
|
|---|---|---|
| Accepts | Numeric expression | Map or set of strings |
| Instance address | aws_glue_job.x[0] |
aws_glue_job.x["bronze"] |
| Remove the first element | Every later index shifts — replacements | Only that key is destroyed |
| Sensitive values | — | Not allowed as keys (keys are shown in UI) |
| Docs' rule | "nearly identical instances" | "distinct values that can't be directly derived from an integer index" |
Both must be known before any remote operation — neither can depend on an apply-time attribute. You
cannot use both in one block. For a list of Glue jobs, use for_each = toset(var.job_names).
lifecycle, verified 2026-10-30:
prevent_destroy = true — Terraform "rejects plans that would destroy" the object. ⚠️ It does
not protect you if you remove the resource block: "This rule doesn't prevent Terraform from
destroying a resource if you remove its configuration." Use it on Redshift and KMS keys, sparingly.ignore_changes = [tags] — share management with an external process (tagging agent, console
tweaks). all means Terraform can create/destroy but never proposes updates.create_before_destroy = true — replacement is created first. Opt-in because names must not collide;
it propagates to dependencies and is the one lifecycle rule recorded in state.replace_triggered_by — force replacement when a referenced managed resource changes.moved and importmoved renames an address without
destroying: Terraform "checks the state for an existing object at the address specified in the from
field" and renames it to to.
moved {
from = aws_glue_job.etl
to = aws_glue_job.jobs["etl"]
}
import blocks adopt console-built
resources; you can write only the import block and run terraform plan -generate-config-out=PATH
(documented as experimental) to generate the resource block. Copied from the provider docs:
import {
to = aws_glue_catalog_database.database
id = "123456789012:my_database" # catalog_id:name
}
Requirements: declare
source and a version constraint inside required_providers; ~> 1.0 is the documented form.
terraform init records the selected version in
.terraform.lock.hcl,
which you "should include in your version control repository". Terraform "will always re-select that
version" until you run terraform init -upgrade. ⚠️ The lock file records hashes for the platform
you ran on; for CI on Linux after developing on a Mac, run
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 so both validate.
Argument names copied from the provider docs listed in sources: (verified 2026-10-30).
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
}
resource "aws_kms_key" "lake" {
description = "Data lake key"
enable_key_rotation = true
deletion_window_in_days = 30 # 7–30, default 30
lifecycle { prevent_destroy = true }
}
resource "aws_glue_catalog_database" "silver" {
name = "silver" # lowercase letters, numbers, underscore only
}
resource "aws_glue_job" "etl_job" {
for_each = toset(["orders", "customers"])
name = "silver-${each.key}"
role_arn = aws_iam_role.glue_job_role.arn
glue_version = "5.0"
worker_type = "G.1X"
number_of_workers = 2
max_retries = 0
timeout = 2880 # minutes; default 2880 for glueetl
execution_class = "STANDARD" # or FLEX
command {
name = "glueetl"
script_location = "s3://${aws_s3_bucket.glue_scripts.bucket}/jobs/${each.key}.py"
python_version = "3"
}
default_arguments = {
"--enable-continuous-cloudwatch-log" = "true"
"--enable-metrics" = ""
}
execution_property { max_concurrent_runs = 1 }
}
resource "aws_emrserverless_application" "spark" {
name = "de4-spark"
release_label = "emr-7.0.0"
type = "spark"
auto_stop_configuration { idle_timeout_minutes = 15 } # default 15
}
resource "aws_lambda_function" "trigger" {
function_name = "de4-trigger"
role = aws_iam_role.lambda.arn
handler = "app.handler"
runtime = "python3.12"
timeout = 60 # seconds, 1–900, default 3
memory_size = 256 # MB, 128–32768, default 128
s3_bucket = aws_s3_bucket.artifacts.id
s3_key = "lambda/trigger.zip"
source_code_hash = var.trigger_zip_hash
}
resource "aws_redshiftserverless_workgroup" "analytics" {
namespace_name = aws_redshiftserverless_namespace.main.namespace_name
workgroup_name = "analytics"
base_capacity = 32 # RPUs
lifecycle { prevent_destroy = true }
}
resource "aws_lakeformation_permissions" "analyst_select" {
principal = aws_iam_role.analyst.arn
permissions = ["SELECT"]
table {
database_name = aws_glue_catalog_database.silver.name
wildcard = true
}
}
resource "aws_cloudwatch_metric_alarm" "glue_failed" {
alarm_name = "glue-silver-failed"
comparison_operator = "GreaterThanOrEqualToThreshold"
evaluation_periods = 1
metric_name = "glue.driver.aggregate.numFailedTasks"
namespace = "Glue"
period = 300
statistic = "Sum"
threshold = 1
alarm_actions = [aws_sns_topic.alerts.arn]
}
In the table block, "at least one of name or wildcard" is required; wildcard grants on every
table under the database. The alarm's metric name and namespace come from lesson 4 — this lesson
verified only the alarm arguments.
⚠️ The provider docs warn that "Lake Formation permissions are not in effect by default" and that
principal should not be a Lake Formation administrator or the role running Terraform (admins have
implicit permissions). IAM_ALLOWED_PRINCIPALS conflicts with per-principal grants — choose one model.
⚠️ aws_kms_key: configure the key policy either with policy here or with aws_kms_key_policy, never
both — "Configuring with both will cause inconsistencies and may overwrite configuration."
terraform plan refreshes state from AWS before diffing by default; a console change shows up as a
planned update. -refresh=false skips that and "could result in an incomplete or incorrect plan".
-refresh-only produces "a plan whose goal is only to update the Terraform state" to match changes
made outside Terraform — use it after incident-time console edits you intend to keep. For scheduled
drift checks, plan -detailed-exitcode returns 0 no changes, 1 error, 2 changes present.
The GitHub Actions tutorial
splits two workflows: terraform-plan.yml triggered on pull_request that comments the plan on the
PR, and terraform-apply.yml triggered on push to main, "which includes Pull Request merges to
main". (The tutorial runs through HCP Terraform; the trigger structure is the same with the CLI.) The
core-workflow page notes the plan "might be different when you merge", so apply still plans at merge
time.
Authentication without stored keys, copied from configure-aws-credentials ("OIDC, recommended"):
permissions:
id-token: write
steps:
- uses: aws-actions/configure-aws-credentials@v6.3.0
with:
role-to-assume: <Role ARN>
aws-region: us-east-1
The IAM role trust policy, from
GitHub's AWS OIDC page:
provider URL https://token.actions.githubusercontent.com, audience sts.amazonaws.com, action
sts:AssumeRoleWithWebIdentity, and a Condition on token.actions.githubusercontent.com:sub such as
repo:octo-org/octo-repo:ref:refs/heads/main or repo:ORG/REPO:environment:prod. ⚠️ IAM "recommends
that users evaluate" the sub condition — a trust policy without it lets any GitHub repo assume the
role. Give the plan role read-only access and the apply role write access, and bind the apply role's
sub to main or a protected environment.
dynamodb_table. What do the current docs say, and what replaces it?aws_redshiftserverless_workgroup block that had prevent_destroy = true. What happens on apply?aws_glue_job.etl to for_each. How do you avoid destroying the job?for_each over a map safer than count over a list when you delete the first job?plan -detailed-exitcode return when drift exists?use_lockfile = true on the S3 backend; the lock becomes <key>.tflock, and the role needs
s3:DeleteObject on that object. Both can coexist during migration.prevent_destroy only rejects plans while the block exists — it
"doesn't prevent Terraform from destroying a resource if you remove its configuration". Use
terraform state rm first if you want to stop managing it without deleting it.moved { from = aws_glue_job.etl to = aws_glue_job.jobs["etl"] } block. Terraform renames
the state entry and plans no destroy.count addresses are positional; removing index 0 shifts every later instance, so Terraform plans
replacements. for_each keys are stable, so only the removed key is destroyed.terraform plan -refresh-only (then apply) — it updates state to match the remote object; then
change the config to match so the next normal plan is clean.use_lockfile = true. Start an apply in one, run
plan in the other, show the lock error and the .tflock object in S3. Then show the IAM
s3:DeleteObject requirement by removing it and watching the unlock fail.prevent_destroy?" Push back on anyone who
says "all of them" — the docs say use it sparingly and it blocks terraform destroy entirely.prevent_destroy protects a resource whose block they
deleted. Have them do it to a aws_glue_catalog_database in a sandbox and read the plan.count over a list of job names, then deleting the first one. Show the cascade,
then fix it with for_each and moved.moved demos.