Lesson 12 intermediate

Terraform with AWS

Connect Terraform to AWS without access keys in code, use AWS provider 6 features such as per-resource regions and default tags, and build Orbit's upload bucket and a hardened web server you reach through Session Manager instead of SSH.

Everything so far ran against Docker on your machine. The same ideas apply unchanged to a cloud: only the provider and the resource types differ. In this lesson Orbit moves its uploads to S3 and its front end to an EC2 instance, using the AWS provider 6.x and the safe authentication options available in 2026.

Cost warning: the resources in this lesson cost a few cents per hour. Use a sandbox account, and run terraform destroy when you finish.

Authenticate without keys in code

Never put access keys in .tf files or tfvars. The AWS provider uses the same credential chain as the AWS CLI, so log in with the CLI and Terraform picks it up:

SituationHow to log in
Company with IAM Identity Center (SSO)aws sso login --profile orbit-sandbox
Personal or small accountaws login (AWS CLI 2.32+), which uses your console sign-in
CI pipelineOpenID Connect role, no stored keys (lesson 14)
Code running on EC2, ECS or LambdaThe attached IAM role, automatically
$ aws sso login --profile orbit-sandbox
$ export AWS_PROFILE=orbit-sandbox
$ aws sts get-caller-identity --query Account --output text
123456789012

All of these give short-lived credentials that expire on their own. Long-lived access keys in ~/.aws/credentials still work, but they are the main way AWS accounts get compromised.

The provider block

terraform {
  required_version = ">= 1.17.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region              = var.region
  allowed_account_ids = [var.account_id]

  default_tags {
    tags = {
      app         = "orbit"
      environment = var.environment
      managed_by  = "terraform"
      repo        = "github.com/orbit/infra"
    }
  }
}

Two habits worth copying:

  • allowed_account_ids makes Terraform refuse to run if your credentials point at a different account. It turns “I applied staging into production” into an error message.
  • default_tags adds the tags to every resource that supports them, so cost reports and cleanup scripts can find Orbit’s resources without anyone remembering to tag.

The upload bucket

S3 buckets are configured through several small resources, each owning one aspect:

data "aws_caller_identity" "current" {}

resource "aws_s3_bucket" "uploads" {
  bucket = "orbit-${var.environment}-uploads-${data.aws_caller_identity.current.account_id}"
}

resource "aws_s3_bucket_public_access_block" "uploads" {
  bucket                  = aws_s3_bucket.uploads.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

resource "aws_s3_bucket_versioning" "uploads" {
  bucket = aws_s3_bucket.uploads.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "uploads" {
  bucket = aws_s3_bucket.uploads.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "aws:kms"
    }
    bucket_key_enabled = true
  }
}

resource "aws_s3_bucket_lifecycle_configuration" "uploads" {
  bucket = aws_s3_bucket.uploads.id
  rule {
    id     = "expire-old-versions"
    status = "Enabled"
    filter {}
    noncurrent_version_expiration {
      noncurrent_days = 30
    }
  }
}

New buckets already block public access and encrypt by default, but stating it in code documents the intent and protects against someone changing it in the console: the next plan would show the drift. The account ID in the name keeps bucket names globally unique without guessing.

A second region without a second provider

Before provider 6.0, putting a resource in another region meant a second provider "aws" block with an alias. Provider 6 adds a region argument to almost every regional resource:

resource "aws_s3_bucket" "uploads_backup" {
  region = "eu-central-1"
  bucket = "orbit-${var.environment}-uploads-backup-${data.aws_caller_identity.current.account_id}"
}

One provider configuration, one plugin process, less memory. Global services such as IAM, CloudFront and Route 53 have no region argument. When importing a resource from another region, add the region to the ID: id = "orbit-old-bucket@eu-central-1".

A web server you never SSH into

The front end runs on a small EC2 instance. Instead of opening port 22 and managing keys, the instance gets an IAM role for Systems Manager Session Manager, and you connect through the AWS API.

data "aws_vpc" "default" {
  default = true
}

data "aws_ssm_parameter" "al2023" {
  name = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"
}

data "aws_iam_policy_document" "ec2_assume" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "web" {
  name               = "orbit-${var.environment}-web"
  assume_role_policy = data.aws_iam_policy_document.ec2_assume.json
}

resource "aws_iam_role_policy_attachment" "web_ssm" {
  role       = aws_iam_role.web.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}

resource "aws_iam_instance_profile" "web" {
  name = "orbit-${var.environment}-web"
  role = aws_iam_role.web.name
}

The security group allows HTTP in and everything out. A security group created by Terraform starts with no outbound rule (Terraform removes AWS’s default one), so the egress rule is needed for the instance to download packages:

resource "aws_security_group" "web" {
  name   = "orbit-${var.environment}-web"
  vpc_id = data.aws_vpc.default.id
}

resource "aws_vpc_security_group_ingress_rule" "web_http" {
  security_group_id = aws_security_group.web.id
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "tcp"
  from_port         = 80
  to_port           = 80
}

resource "aws_vpc_security_group_egress_rule" "web_all" {
  security_group_id = aws_security_group.web.id
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "-1"
}

resource "aws_instance" "web" {
  ami                    = data.aws_ssm_parameter.al2023.value
  instance_type          = "t3.micro"
  iam_instance_profile   = aws_iam_instance_profile.web.name
  vpc_security_group_ids = [aws_security_group.web.id]

  metadata_options {
    http_tokens = "required"
  }

  user_data_replace_on_change = true
  user_data = <<-EOT
    #!/bin/bash
    dnf install -y docker
    systemctl enable --now docker
    docker run -d --restart unless-stopped -p 80:80 --name orbit-web nginx:${var.web_image_tag}
  EOT

  tags = {
    Name = "orbit-${var.environment}-web"
  }
}

output "web_url" {
  value = "http://${aws_instance.web.public_dns}"
}

output "connect" {
  value = "aws ssm start-session --target ${aws_instance.web.id}"
}

Details that matter:

  • http_tokens = "required" forces IMDSv2, which blocks a whole class of credential-theft attacks through the instance metadata service.
  • user_data_replace_on_change = true replaces the instance when the startup script changes. Without it, a changed script is saved but never runs, which is a common source of confusion.
  • The AMI comes from the SSM parameter, so a new apply picks up the latest patched Amazon Linux. Combine it with lifecycle { ignore_changes = [ami] } if you would rather roll instances on your own schedule.

Apply, check, connect, destroy

$ terraform init
$ terraform plan -var-file=sandbox.tfvars -out=aws.tfplan
Plan: 13 to add, 0 to change, 0 to destroy.
$ terraform apply aws.tfplan
Outputs:
connect = "aws ssm start-session --target i-0a1b2c3d4e5f67890"
web_url = "http://ec2-3-250-10-20.eu-west-1.compute.amazonaws.com"
$ curl -s "$(terraform output -raw web_url)" | grep title
<title>Welcome to nginx!</title>
$ terraform destroy -var-file=sandbox.tfvars

The page may take a minute to answer while user data installs Docker. Session Manager needs the AWS CLI’s Session Manager plugin on your machine.

Quick reference

TaskSyntax or command
Log in with SSOaws sso login --profile orbit-sandbox
Check which account you are usingaws sts get-caller-identity
Refuse the wrong accountallowed_account_ids = ["123456789012"]
Tag everythingdefault_tags { tags = { ... } }
Resource in another region (provider 6)region = "eu-central-1" on the resource
Import from another regionid = "<id>@eu-central-1"
Latest Amazon Linux AMIdata "aws_ssm_parameter" with /aws/service/ami-amazon-linux-latest/...
Shell on an instance without SSHaws ssm start-session --target <instance-id>

Exercise

Your credentials point at the production account by mistake while you run the sandbox configuration. Which provider setting stops the apply?

  1. default_tags
  2. allowed_account_ids
  3. region
  4. assume_role
Show answer

Answer: B. allowed_account_ids makes the provider check the account of the current credentials and fail before any change if it is not in the list.

Exercise

With AWS provider 6, how do you create one S3 bucket in a second region inside the same configuration?

  1. A second provider “aws” block with alias, then provider = aws.backup
  2. Set region = “eu-central-1” on the bucket resource
  3. Run terraform apply twice with different AWS_REGION values
  4. S3 buckets are global, so the region cannot be chosen
Show answer

Answer: B. Provider 6 adds a region argument to regional resources. Aliased providers still work, but one provider block with per-resource regions is simpler and uses less memory.

Key takeaways

  • Authenticate with SSO, aws login or OIDC; never put access keys in Terraform files.
  • allowed_account_ids and default_tags belong in every AWS provider block.
  • AWS provider 6 adds a region argument per resource, replacing most aliased providers.
  • Configure S3 buckets with separate resources for access, versioning, encryption and lifecycle.
  • Reach instances through Session Manager and enforce IMDSv2 instead of opening SSH.
  • Set user_data_replace_on_change so changed startup scripts actually run.

FAQ

Do I need to upgrade to AWS provider 6?

Version 5 still works with existing configurations, but new features and fixes land in 6. Upgrade by pinning ~> 6.0, running terraform init -upgrade, reading the upgrade guide and looking for unexpected changes in the plan before applying.

Why does my S3 bucket name fail with “BucketAlreadyExists”?

Bucket names are global across every AWS account. Add something unique, such as the account ID, to the name, as in this lesson.

Should I use the community VPC module or write my own?

For production networks, the terraform-aws-modules/vpc/aws module is well maintained and covers subnets, NAT gateways and endpoints in one call. Write your own once you understand what it builds and need fewer options.

How do I keep costs under control while learning?

Use a sandbox account with a budget alert, keep everything tagged (default_tags makes that automatic) and run terraform destroy at the end of each session. The plan is also a cost review: read what it creates.

↑ ↓ navigate Enter open Esc close