创建IAM角色并将策略附加到该角色时出错



我正在尝试创建一个lambda角色并将策略附加到它,以便它可以启动和停止ec2实例。我将使用cloudwatch触发lambda。

我收到以下错误:"错误:创建IAM角色lambdaRole时出错:格式不正确的PolicyDocument:JSON字符串不能有前导空格状态代码:400,请求id:d6a86c41-6601-43af-9040-81f6e6a76ec8

在iam.tf第11行,在资源"aws_iam_role"lambdaRole"中:11:resource"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}"
}

我也面临同样的错误。我直接从问题中复制了代码。

对我来说,它的工作方式是启动{,即在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.

好吧,我找到了这个问题的解决方案。我把json移到了不同的文件中,只是引用了这些文件。

像这样,policy="${file("lambda policy.json"(}">

这是我在"lambda policy.json"中看到的:{"版本":"2012-10-17","声明":[{"Sid":"VisualEditor0","效果":"允许","操作":["ec2:描述实例","ec2:StartInstances","logs:","ec2:StopInstances"],"资源":">"}]}

相关内容

  • 没有找到相关文章

最新更新