我有一个aws_iam_role
要添加策略的。通常,我会创建一个策略aws_iam_role
并将其附加到角色aws_iam_role_policy_attachment
。
但是,我看过一些文档aws_iam_role_policy
,在我看来,这些文档似乎在做同样的事情。
我是正确的还是有我遗漏的细微差别?
我有一个aws_iam_role
要添加策略的。通常,我会创建一个策略aws_iam_role
并将其附加到角色aws_iam_role_policy_attachment
。
但是,我看过一些文档aws_iam_role_policy
,在我看来,这些文档似乎在做同样的事情。
我是正确的还是有我遗漏的细微差别?
区别在于托管策略和内联策略
创建 时aws_iam_policy
,这是一个托管策略,可以重复使用。
当您创建aws_iam_role_policy
内联策略时
对于给定角色,aws_iam_role_policy资源与使用
aws_iam_role
resourceinline_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
}