How to write least-privilege IAM roles on AWS
Write tightly scoped AWS IAM roles and policies using explicit resources, conditions, and trust policies. Includes auditing with IAM Access Analyzer.
Least privilege means a workload gets exactly the permissions it needs and nothing more. Over-broad IAM policies (Action: "*", Resource: "*") are a leading cause of cloud breaches. AWS IAM lets you scope by action, resource ARN, and condition keys.
Prerequisites
- An AWS account and Terraform.
- A clear idea of what your workload does (which buckets, tables, queues).
Steps
1. Identify required actions
List the concrete API calls your code makes, for example s3:GetObject and s3:PutObject against one bucket. Resist adding s3:*.
2. Write a scoped policy
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::reports-bucket/*"
}]
}
Name resources explicitly. Separate read and write statements if only some objects need writes.
3. Add conditions
Narrow further with condition keys, for example require TLS and a specific prefix:
"Condition": {
"Bool": { "aws:SecureTransport": "true" },
"StringLike": { "s3:prefix": "daily/*" }
}
4. Create the role and trust
The trust policy controls who can assume the role. For a Lambda function:
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = { Service = "lambda.amazonaws.com" }
Action = "sts:AssumeRole"
}]
})
5. Attach and test
Attach the policy to the role, assign the role to the workload, and exercise the workload. Permission errors tell you exactly what is missing, add it deliberately.
6. Audit with Access Analyzer
IAM Access Analyzer reviews CloudTrail to recommend a policy based on actually used actions:
aws accessanalyzer start-policy-generation --policy-generation-details ...
Verification
Use the IAM Policy Simulator to confirm allowed and denied actions match expectations. Run the workload end to end and confirm no AccessDenied errors remain for legitimate calls.
Next Steps
Adopt permission boundaries for delegated admins, rotate credentials with short-lived STS tokens, and schedule periodic Access Analyzer reviews to prune unused permissions.
Prerequisites
- AWS account
- Understanding of IAM basics
- Terraform installed
Steps
- 1Identify required actions
- 2Write a scoped policy
- 3Add conditions
- 4Create the role and trust
- 5Attach and test
- 6Audit with Access Analyzer