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.
More on Write-Terraform tasks
Write Terraform for an S3 bucket with versioning, encryption and public access blocked.BeginnerWrite the remote backend configuration with S3 and state locking.BeginnerWrite a VPC with public and private subnets across 3 AZs using `count` or `for_each`.IntermediateWrite a reusable module for an EC2 instance with inputs, outputs and validation.AdvancedWrite a security group that allows HTTPS from anywhere and SSH only from an office CIDR.BeginnerCreate multiple IAM users from a list with `for_each`, and output their ARNs as a map.Beginner