Interview Prep/Real-World Interview/Write-Terraform tasks

Write Terraform for an IAM role that EC2 can assume, with a least-privilege S3 read policy.

IntermediateHands-onWrite-Terraform tasks
Answer
data "aws_iam_policy_document" "assume_ec2" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }
}

data "aws_iam_policy_document" "read_artifacts" {
  statement {
    actions   = ["s3:GetObject"]
    resources = ["${aws_s3_bucket.artifacts.arn}/*"]
  }
  statement {
    actions   = ["s3:ListBucket"]
    resources = [aws_s3_bucket.artifacts.arn]
  }
}

resource "aws_iam_role" "app" {
  name               = "app-ec2"
  assume_role_policy = data.aws_iam_policy_document.assume_ec2.json
}

resource "aws_iam_role_policy" "read" {
  role   = aws_iam_role.app.id
  policy = data.aws_iam_policy_document.read_artifacts.json
}

resource "aws_iam_instance_profile" "app" {
  name = "app-ec2"
  role = aws_iam_role.app.name
}

Key trick → ListBucket applies to the bucket ARN and GetObject to bucket/*. Mixing them up is the most common IAM bug. EC2 attaches roles through an instance profile, not directly.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-Terraform tasks