gpt4 book ai didi

amazon-web-services - Terraform - 如何为 AWS Lambda 创建 IAM 角色并部署两者?

转载 作者:行者123 更新时间:2023-12-03 14:01:03 26 4
gpt4 key购买 nike

我正在学习地形。我正在尝试创建一个新的 Lambda 函数。我意识到我还需要创建一个 IAM 角色。所以我正在尝试使用 Terraform 来做这两项工作。但它不允许我创建角色。

这是我的 Terraform 文件

provider "aws" {
profile = "default"
region = "eu-west-1"
}

data "aws_iam_policy" "AWSLambdaBasicExecutionRole" {
arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}

resource "aws_iam_role" "terraform_function_role" {
name = "terraform_function_role"
assume_role_policy = "${data.aws_iam_policy.AWSLambdaBasicExecutionRole.policy}"
}

resource "aws_lambda_function" "terraform_function" {
filename = "terraform_function.zip"
function_name = "terraform_function"
handler = "index.handler"
role = "${aws_iam_role.terraform_function_role.id}"
runtime = "nodejs8.10"
source_code_hash = "${filebase64sha256("terraform_function.zip")}"
}

这是我得到的错误
Error creating IAM Role terraform_function_role: MalformedPolicyDocument: Has prohibited field Resource
status code: 400

我该如何解决?

最佳答案

IAM 角色的信任关系(或代入角色策略)定义了可以代入角色的资源/服务。在这里,我们没有定义 Resource 字段。因此,我们无法附加IAM策略或按原样使用该策略。信任关系的正确格式是:

{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}]
}

在这种情况下,您账户中的所有 Lambda 函数都可以担任此角色。

您可以引用 this AWS链接以获取更多示例。

编辑: 基于@ydaetskcoR 评论,这是一个工作示例:
provider "aws" {
profile = "default"
region = "eu-west-1"
}

data "aws_iam_policy_document" "AWSLambdaTrustPolicy" {
statement {
actions = ["sts:AssumeRole"]
effect = "Allow"
principals {
type = "Service"
identifiers = ["lambda.amazonaws.com"]
}
}
}

resource "aws_iam_role" "terraform_function_role" {
name = "terraform_function_role"
assume_role_policy = "${data.aws_iam_policy_document.AWSLambdaTrustPolicy.json}"
}

resource "aws_iam_role_policy_attachment" "terraform_lambda_policy" {
role = "${aws_iam_role.terraform_function_role.name}"
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}

resource "aws_lambda_function" "terraform_function" {
filename = "terraform_function.zip"
function_name = "terraform_function"
handler = "index.handler"
role = "${aws_iam_role.terraform_function_role.arn}"
runtime = "nodejs8.10"
source_code_hash = "${filebase64sha256("terraform_function.zip")}"
}

您的代码中的更改包括以下内容:
  • 更新了代入角色权限的 aws_iam_policy_document 资源
  • 将 aws_iam_role 资源更改为使用上述策略文档
  • 创建了 aws_iam_role_policy_attachment 以附加 LambdaBasicExecution 策略(允许记录到 CloudWatch)
  • 更新了 aws_lambda_function 资源以使用 IAM 角色的 ARN 而不是 Id,因为 Lambda 函数需要 ARN
  • 关于amazon-web-services - Terraform - 如何为 AWS Lambda 创建 IAM 角色并部署两者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57288992/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com