How to add policy to iam role in aws using terraform

To add an IAM policy to an IAM role in Terraform, you can use the aws_iam_policy resource and the aws_iam_policy_attachment resource.

Here’s an example of how you might do this:

add policy to iam role

resource "aws_iam_policy" "example_policy" {
  name        = "example_policy"
  description = "An example policy"
  policy      = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::example-bucket",
      "Effect": "Allow"
    }
  ]
}
EOF
}

resource "aws_iam_policy_attachment" "example_attachment" {
  name       = "example_attachment"
  roles      = ["${aws_iam_role.example_role.name}"]
  policy_arn = "${aws_iam_policy.example_policy.arn}"
}

This will create an IAM policy and attach it to the specified IAM role.

Note that this example creates the policy and attachment resources separately. If you want to create both at the same time, you can use the aws_iam_role_policy resource, which combines both the policy and the attachment into a single resource.

Here’s an example of how you could use the aws_iam_role_policy resource:

resource "aws_iam_role_policy" "example_policy" {
  name   = "example_policy"
  role   = "${aws_iam_role.example_role.name}"
  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::example-bucket",
      "Effect": "Allow"
    }
  ]
}
EOF
}

This will create both the policy and the attachment in a single step.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *