How to Create IAM Policy with Terraform: Simple Guide
To create an IAM policy in Terraform, use the
aws_iam_policy resource with a JSON policy document in policy. Define permissions inside the JSON and apply the Terraform configuration to create the policy in AWS.Syntax
The aws_iam_policy resource defines an IAM policy in Terraform. It requires a name for the policy and a policy which is a JSON string describing permissions.
- name: The name of the IAM policy.
- policy: The JSON formatted string that specifies allowed or denied actions and resources.
terraform
resource "aws_iam_policy" "example" { name = "example_policy" policy = jsonencode({ Version = "2012-10-17", Statement = [ { Action = ["s3:ListBucket"], Effect = "Allow", Resource = "arn:aws:s3:::example_bucket" } ] }) }
Example
This example creates an IAM policy that allows listing an S3 bucket named example_bucket. It uses jsonencode to convert the policy map to JSON format.
terraform
provider "aws" { region = "us-east-1" } resource "aws_iam_policy" "list_s3_bucket" { name = "ListS3BucketPolicy" policy = jsonencode({ Version = "2012-10-17", Statement = [ { Effect = "Allow", Action = ["s3:ListBucket"], Resource = "arn:aws:s3:::example_bucket" } ] }) }
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Common Pitfalls
Common mistakes when creating IAM policies in Terraform include:
- Writing the policy JSON as a plain string without
jsonencode, which can cause syntax errors. - Forgetting to specify the correct
Versionor using an invalid policy structure. - Using incorrect or incomplete
ActionorResourcevalues, leading to permission errors.
Always validate your JSON policy and test permissions carefully.
terraform
resource "aws_iam_policy" "wrong" { name = "WrongPolicy" policy = "{\"Version\": \"2012-10-17\", \"Statement\": [{\"Effect\": \"Allow\", \"Action\": [\"s3:ListBucket\"], \"Resource\": \"arn:aws:s3:::example_bucket\"}]}" # This is error-prone } # Correct way uses jsonencode: resource "aws_iam_policy" "correct" { name = "CorrectPolicy" policy = jsonencode({ Version = "2012-10-17", Statement = [ { Effect = "Allow", Action = ["s3:ListBucket"], Resource = "arn:aws:s3:::example_bucket" } ] }) }
Quick Reference
Remember these tips when creating IAM policies with Terraform:
- Use
aws_iam_policyresource. - Write policy JSON as a Terraform map and convert with
jsonencode. - Always specify
VersionandStatementcorrectly. - Test your policy permissions after deployment.
Key Takeaways
Use the aws_iam_policy resource with jsonencode to create IAM policies in Terraform.
Define permissions clearly in the policy JSON with Version, Statement, Effect, Action, and Resource.
Avoid writing raw JSON strings; use Terraform maps and jsonencode for safety.
Check your policy syntax and test permissions after deployment.
Naming your policy clearly helps manage multiple policies.