- Published on
IAM
- Authors
- Name
- Bowen Y
How to create a IAM role with proper policy using terraform?
- Trust Policy: Defines who can assume the role.
- Role: Defines the role itself.
- Permissions Policy: Defines what the role can do by specifying actions and resources.
- Policy Attachment: Attaches the permissions policy to the role.
# Step 1: Define the trust policy
data "aws_iam_policy_document" "assume_role" {
statement {
effect = "Allow"
principals {
type = "Service"
identifiers = ["lambda.amazonaws.com"]
}
actions = ["sts:AssumeRole"]
}
}
# Step 2: Define the role
resource "aws_iam_role" "iam_for_lambda" {
name = "iam_for_lambda"
assume_role_policy = data.aws_iam_policy_document.assume_role.json
}
# Step 3: Define the permissions policy
data "aws_iam_policy_document" "lambda_policy" {
statement {
effect = "Allow"
actions = [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
]
resources = ["arn:aws:logs:*:*:*"]
}
}
# Step 4: Attach the policy to the role
resource "aws_iam_policy" "lambda_policy" {
name = "lambda_policy"
policy = data.aws_iam_policy_document.lambda_policy.json
}
resource "aws_iam_role_policy_attachment" "lambda_policy_attachment" {
role = aws_iam_role.iam_for_lambda.name
policy_arn = aws_iam_policy.lambda_policy.arn
}