我正在尝试创建一个lambda角色并为其附加策略,以便它可以启动和停止ec2实例。我将使用cloudwatch触发lambda。
我收到此错误: “错误:创建IAM角色lambdaRole时发生错误:MalformedPolicyDocument:JSON字符串不得包含前导空格 状态码:400,请求ID:d6a86c41-6601-43af-9040-81f6e6a76ec8
在iam.tf第11行的资源“ aws_iam_role”“ lambdaRole”中: 11:资源“ aws_iam_role”“ lambdaRole” {“
terraform {
backend "s3" {
region = "us-west-2"
bucket = "gitlegionbucket"
key = "ec2/terraform.tfstate"
dynamodb_table = "tf-state-lock"
}
}
resource "aws_iam_role" "lambdaRole" {
name = "lambdaRole"
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"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:Start*",
"ec2:Stop*"
],
"Resource": "*"
}
]
}
EOF
}
resource "aws_iam_role_policy_attachment" "attach-policies" {
role = "${aws_iam_role.lambdaRole.name}"
policy_arn = "${aws_iam_policy.policy.arn}"
}
答案 0 :(得分:1)
我也面临着同样的错误。我直接从问题中复制了代码。
对我来说,它的工作方式是启动{
,即在EOF
行之后立即开始策略,没有任何空格。
resource "aws_iam_role" "lambdaRole" {
name = "lambdaRole"
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"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:Start*",
"ec2:Stop*"
],
"Resource": "*"
}
]
}
EOF
}
resource "aws_iam_role_policy_attachment" "attach-policies" {
role = "${aws_iam_role.lambdaRole.name}"
policy_arn = "${aws_iam_policy.policy.arn}"
}
地形输出:
aws_iam_role.lambdaRole: Creating...
aws_iam_role.lambdaRole: Creation complete after 2s [id=lambdaRole]
aws_iam_role_policy_attachment.attach-policies: Creating...
aws_iam_role_policy_attachment.attach-policies: Creation complete after 1s [id=lambdaRole-20191107141649610400000001]
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
答案 1 :(得分:0)
好的,我找到了解决此问题的方法。我将json移到了不同的文件中,而只是引用了这些文件。
像这样,policy =“ $ {file(” lambda-policy.json“)}”“
这是我在“ lambda-policy.json”中的内容: { “ Version”:“ 2012-10-17”, “声明”:[ { “ Sid”:“ VisualEditor0”, “效果”:“允许”, “动作”:[ “ ec2:DescribeInstances”, “ ec2:StartInstances”, “日志:”, “ ec2:StopInstances” ], “资源”:“ ” } ] }