"jsonencode"只期望 1 个参数



我正在尝试改造一个AWS角色。我遵循了这个例子,他们只附加了一个json策略:

resource "aws_iam_policy" "policy" {
name        = "test_policy"
path        = "/"
description = "My 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*",
]
Effect   = "Allow"
Resource = "*"
},
]
})
}

但是,我想附加两个策略。我试着在两者之间加一个逗号:

resource "aws_iam_role" "name" {
name = "name"
assume_role_policy = jsonencode(
{
"Version" : "2012-10-17",
"Statement" : [
{
"Effect" : "Allow",
"Action" : [
"s3:*",
"s3-object-lambda:*"
],
"Resource" : "*"
}
]
},
{
"Version" : "2012-10-17",
"Statement" : [
{
"Effect" : "Allow",
"Action" : [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource" : "*"
}
]
}
)
然而,这会给出一个错误:
Function "jsonencode" expects only 1 argument(s).

我还可以如何附加多个策略?

这是因为你的策略json格式错误。您需要将这两个策略封装在一个数组中,如下所示。

resource "aws_iam_role" "name" {
name = "name"
assume_role_policy = jsonencode(
[
{
"Version" : "2012-10-17",
"Statement" : [
{
"Effect" : "Allow",
"Action" : [
"s3:*",
"s3-object-lambda:*"
],
"Resource" : "*"
}
]
},
{
"Version" : "2012-10-17",
"Statement" : [
{
"Effect" : "Allow",
"Action" : [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource" : "*"
}
]
}
]
)

assume_role_policy参数只期望一个单个IAM策略文档,但是如果您需要在不同的资源上声明多个效果,该文档可能包含多个语句

请注意,assume_role_policy仅用于指定允许哪些其他IAM主体承担该角色。它没有指定角色本身授予的访问权限。因此,在假设角色策略中声明sts:AssumeRolests:AssumeRoleWithSAMLsts:AssumeRoleWithWebIdentity以外的操作的策略是没有用的。

(我在之前的问题的回答中写了更多关于AssumeRole的细节。)

给定您共享的策略内容,我希望您的意图是将策略与两个语句与角色关联起来,以便假设角色将授予该访问权限。要做到这一点,您需要在aws_iam_role旁边使用aws_iam_role_policy资源类型,首先声明角色,然后声明与之关联的策略:

resource "aws_iam_role" "example" {
name = "name"
# You will also need to set assume_role_policy to declare
# what can assume this role, but there isn't enough
# information in your question to know what policy would
# be appropriate for that.
}
resource "aws_iam_role_policy" "example" {
name = aws_iam_role.example.name
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect   = "Allow"
Action   = [
"s3:*",
"s3-object-lambda:*",
]
Resource = "*"
},
{
Effect   = "Allow"
Action   = [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
]
Resource = "*"
},
]
})
}
output "role_arn" {
value = aws_iam_role.example.arn
# The role ARN won't be fully usable until
# the policy is attached to it, so we must
# declare this additional dependency to get
# correct ordering of operations.
depends_on = [aws_iam_role_policy.example]
}
注意,aws_iam_role_policy.example中的policy表达式只有一个策略文档,但是该文档有两个语句,每个语句独立地允许一组操作。在这种情况下,相当于将所有这些操作放在一个单独的语句中,但我假设您将它们分开,因为在实践中它们彼此并不那么相似。

为同一个角色声明多个aws_iam_role_policy也是有效的,如果您希望将角色的声明从授予不同的策略中分离出来,这可能很有用,但在这种情况下(同一模块无论如何都声明了这两个),没有理由增加这种复杂性。

相关内容

  • 没有找到相关文章

最新更新