我有一个 aws_iam_role
,想要添加一个策略。通常情况下,我会使用 aws_iam_role_policy_attachment
创建一个与 aws_iam_role
相关的策略,并将其附加到该角色上。
但是,我看到一些文档使用了 aws_iam_role_policy
,我认为它似乎做了同样的事情。
我的理解正确吗?还是我漏掉了一些微妙的区别?
我有一个 aws_iam_role
,想要添加一个策略。通常情况下,我会使用 aws_iam_role_policy_attachment
创建一个与 aws_iam_role
相关的策略,并将其附加到该角色上。
但是,我看到一些文档使用了 aws_iam_role_policy
,我认为它似乎做了同样的事情。
我的理解正确吗?还是我漏掉了一些微妙的区别?
区别在于托管策略和内联策略
创建aws_iam_policy
时,这是一个托管策略,可重复使用。
创建aws_iam_role_policy
时,这是一个内联策略
对于给定的角色,aws_iam_role_policy资源与使用
aws_iam_role
资源inline_policy
参数不兼容。当同时使用此资源和参数时,两者都将尝试管理角色的内联策略,Terraform将显示永久差异。
重现上述状态的代码:
resource "aws_iam_role_policy" "test_policy" {
name = "test_policy"
role = aws_iam_role.test_role.id
# Terraform's "jsonencode" function converts a
# Terraform expression result to valid JSON syntax.
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = [
"ec2:Describe*",
]
Effect = "Allow"
Resource = "*"
},
]
})
}
resource "aws_iam_role" "test_role" {
name = "test_role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Sid = ""
Principal = {
Service = "ec2.amazonaws.com"
}
},
]
})
}
resource "aws_iam_role" "role" {
name = "test-role1"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
resource "aws_iam_policy" "policy" {
name = "test-policy"
description = "A test policy"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"ec2:Describe*"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
EOF
}
resource "aws_iam_role_policy_attachment" "test-attach" {
role = aws_iam_role.role.name
policy_arn = aws_iam_policy.policy.arn
}