IAM roles and policies in Terraform

Intermediate · 11 min

Write trust and permissions policies with aws_iam_policy_document, catch typos early, and see how a wildcard like s3:Put* expands against AWS's action list.

Before thisData sources

cloudonaut · 11 min

IAM roles and policies in Terraform

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by cloudonautReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A role has a trust policy (who may assume it) and a permissions policy (what it may do); in Terraform they are separate arguments and resources.
  • aws_iam_policy_document gives a schema, so terraform validate catches misspelled arguments that a heredoc or jsonencode string hides; it does not check that an action exists.
  • Wildcards hide scope: s3:Put* expanded to 40 actions, 12 of them permission-management such as PutBucketPolicy.
  • Scope iam:PassRole to specific role ARNs, and decide which Terraform resource owns a role's attachments, since exclusive resources remove unlisted policies.

The policy with a typo in it

You need a service to read and write one S3 bucket. You write the policy as JSON in a heredoc, because that is what the AWS docs show. You typo one action as s3:GetObjects. Terraform does not complain: to Terraform the policy is a string. AWS may not complain at create time either. The service starts, and the first time it reads from the bucket, the request is denied, and you spend an hour looking at the bucket policy.

Identity and access management is the part of AWS where the cost of an error is highest and the tooling to catch it is weakest. This lesson is about writing roles and policies in Terraform so that mistakes show up early, and so that the policy you wrote is the narrow one you meant. The concepts, roles and trust, least privilege, come from the devops lessons on cloud identity and least privilege. Here we write them.

Two policies on every role

An IAM role has two separate policies, and mixing them up is the most common beginner error:

  • The trust policy (assume_role_policy) says who may become the role: an EC2 service, a Lambda, an OIDC identity from CI, another account.
  • The permissions policy says what the role can do once someone has it.

In Terraform they are different resources and arguments. The pattern that works, from the AWS provider docs and not run by me:

data "aws_iam_policy_document" "trust" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ecs-tasks.amazonaws.com"]
    }
  }
}

data "aws_iam_policy_document" "logs_rw" {
  statement {
    actions   = ["s3:GetObject", "s3:PutObject"]
    resources = ["${aws_s3_bucket.logs.arn}/*"]
  }
  statement {
    actions   = ["s3:ListBucket"]
    resources = [aws_s3_bucket.logs.arn]
  }
}

resource "aws_iam_role" "app" {
  name               = "notes-app"
  assume_role_policy = data.aws_iam_policy_document.trust.json
}

resource "aws_iam_role_policy" "logs_rw" {
  name   = "logs-rw"
  role   = aws_iam_role.app.id
  policy = data.aws_iam_policy_document.logs_rw.json
}

Notice the two resource ARNs. Object actions apply to bucket/*. s3:ListBucket applies to the bucket itself. Mixing them up is a common reason a policy that “looks right” still denies.

Why aws_iam_policy_document

There are three ways to produce the JSON: a heredoc, jsonencode() and the aws_iam_policy_document data source. The cloudonaut video, the embed here, walks through all three, from its chapter list: EOF, jsonencode, data resource, and why you should use data resources. Its argument, from the description, is that with the data source terraform validate can tell you about typos before you apply, and your editor gets better autocompletion. That is because the data source has a schema: actions, resources, principals are arguments, so acitons is an error at validate time, whereas a heredoc is just text. It also composes. Use source_policy_documents or override_policy_documents to merge pieces, and references like ${aws_s3_bucket.logs.arn} are checked for existence.

The data source checks the shape of the policy, not whether s3:GetObjects is a real action. That is a second layer.

Checking action names against AWS’s own list

AWS publishes a machine-readable Service Authorization Reference at servicereference.us-east-1.amazonaws.com, listing every action per service with annotations. I wrote a short Python script that loads the S3 reference (version v1.5, 180 actions when I fetched it on 28 November 2026), expands wildcard patterns against it and counts what each statement would grant. It uses real AWS data; the script is mine, and AWS action matching is case-insensitive where mine is not:

$ python3 -I actions.py
stmt 1: s3:GetObject     resource=scoped  -> 1 action(s), 0 write, 0 permission-management
stmt 1: s3:PutObject     resource=scoped  -> 1 action(s), 1 write, 0 permission-management
stmt 2: s3:GetObjects    resource=scoped  -> UNKNOWN ACTION
stmt 3: s3:Put*          resource=scoped  -> 40 action(s), 40 write, 12 permission-management
stmt 4: s3:*             resource=*       -> 180 action(s), 96 write, 27 permission-management
stmt 5: iam:PassRole     resource=*       -> 1 action(s), 1 write, 0 permission-management

Three things jump out. The typo is caught: s3:GetObjects matches nothing. A harmless-looking s3:Put* is 40 actions, 12 of which change who has access, including PutBucketPolicy, PutBucketAcl and PutBucketPublicAccessBlock. A role that can only “write logs” can rewrite the bucket’s own policy. And s3:* on * is 180 actions on every bucket in the account. This is why wildcards in actions deserve a comment in review: the name sounds narrow and the expansion is not. A step like this in CI, or the AWS-provided IAM Access Analyzer, turns “least privilege” from a slogan into a check.

iam:PassRole and other quiet escalations

iam:PassRole lets a principal hand a role to a service, such as ECS or Lambda. With Resource = "*", as in statement 5 above, it can pass any role in the account to a service that runs code, which may include one far more powerful than its own. Scope it to specific role ARNs, and use the iam:PassedToService condition to say which service may receive them. I did not run this condition against a real account; it is from AWS’s IAM documentation, which I know but did not re-read for this lesson.

Attachments and the “who owns this” problem

Terraform has several ways to attach policies, and they can fight each other. aws_iam_role_policy is an inline policy, and aws_iam_role_policy_attachment adds one managed policy. The provider docs for aws_iam_role_policy_attachments_exclusive say it “takes exclusive ownership over managed IAM policies attached to a role,” including removing any that are not configured. That is right for a locked-down role and a surprise on a shared one. Decide per role who owns its permissions, and make Terraform the only writer.

Where the roles live

Roles for CI and roles for applications belong in different states, applied by different people. A role for the pipeline that can create IAM roles is the highest-privilege thing in the account. Use a permissions boundary, a managed policy that caps what any role it is attached to can ever do, to limit how far a pipeline can escalate, and review the pipeline’s own role more carefully than any application role.

About the video

The embed is cloudonaut’s “Defining IAM Policies with Terraform in AWS”, 10 minutes 46 seconds, August 2021. Its chapters are intro, the setup, EOF, jsonencode, data resource, why you should use data resources in Terraform, and wrap up. It is from 2021, so the HCL is from the 0.13 to 1.x era and still valid, but it covers only the policy-writing part and not trust policies, PassRole or the exclusive attachment resources. English was judged from the title, description, channel and its English auto-caption track. It is the only candidate I kept for this lesson.

Where this fits

A network and a role are the ingredients. Compute and load balancing puts a service in the network, running as the role.

Check yourself

  1. 01Why did s3:GetObjects not fail terraform validate?

    Terraform treats the policy as a string or document without knowing real action names. Only a check against AWS's action list catches it.

  2. 02Why does s3:ListBucket use the bucket ARN while s3:GetObject uses bucket/* ?

    ListBucket acts on the bucket itself and GetObject on objects inside it, so the resource ARNs differ.

  3. 03What does aws_iam_role_policy_attachments_exclusive do that aws_iam_role_policy_attachment does not?

    It takes exclusive ownership of a role's managed policies and removes any not configured, where the plain attachment only adds one.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark