Create AWS IAM Policy using Terraform

This post explains how to create IAM policy using Terraform. To follow steps described in this article you need have below prerequisites configured.

  • Terraform Installation
  • AWS CLI Installation
  • AWS Credentials Configuration
Follow Set up Terraform with AWS from scratch if you don't have these prerequisites configured.

IAM policy using Terraform

Write below configuration in main.tf and save the file.

   
terraform {
    required_providers {
        aws = {
        source  = "hashicorp/aws"
        version = "~> 3.27"
        }
    }

    required_version = ">= 0.14.9"
}

provider "aws" {
    profile = "default"
    region  = "us-east-1"
}

resource "aws_iam_policy" "policy" {
    name        = "test_iam_policy"
    path        = "/"
    description = "Test Policy"

    # Terraform's "jsonencode" function converts a
    # Terraform expression result to valid JSON syntax.
    policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
        {
        Action = [
            "ec2:Describe*",
            "s3:List*"
        ]
        Effect   = "Allow"
        Resource = "*"
        },
    ]
    })
}        
     

Run below commands in order.

  • terraform fmt
  • terraform validate
  • terraform apply

After terraform apply type yes in "Do you want to perform these actions" prompt.

On successful execution it will create a IAM policy named test_iam_policy.


Category: AWS