如何在Terraform中配置CloudWatchLambdaInsights
我需要使用 Terraform 为 lambda 启用“CloudWatch Lambda Insights”,但找不到文档。我如何在 Terraform 中做到这一点?
注意:这个问题如何将 CloudWatch Lambda Insights 添加到无服务器配置?可能是相关的。
回答
aws_lambda_function您可以将 AWS Terraform 提供程序的资源设置为的资源中没有“布尔开关” true,这将启用 Cloudwatch Lambda Insights。
幸运的是,您可以自己完成此操作。以下 Terraform 定义基于此 AWS 文档:使用 AWS CLI 在现有 Lambda 函数上启用 Lambda Insights
该过程包括两个步骤:
- 为您的 Lambda添加一个层
- 将 AWS策略附加到您的 Lambdas 角色。
Terraform 定义如下所示:
resource "aws_lambda_function" "insights_example" {
[...]
layers = [
"arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:14"
]
}
resource "aws_iam_role_policy_attachment" "insights_policy" {
role = aws_iam_role.insights_example.id
policy_arn = "arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy"
}
重要提示:arn每个地区的图层都不同。我上面链接的文档有一个指向它们列表的链接。此外,如果您的 Lambda 位于 VPC 中,则需要一个额外的步骤,您可以在文档中阅读。所描述的“VPC 步骤”也可以放入 Terraform。
对于未来的读者:我的示例中该层的版本是14. 这会随着时间而改变。所以请不要只是复制和粘贴那部分。按照提供的链接查找该层的当前版本。
最小、完整和可验证的示例
测试:
Terraform v0.14.4
+ provider registry.terraform.io/hashicorp/archive v2.0.0
+ provider registry.terraform.io/hashicorp/aws v3.24.0
在文件夹中创建以下两个文件(handler.py和main.tf)。然后运行以下命令:
terraform initterraform planterraform apply
除了部署所需的资源外,它还将创建一个 zip 存档,handler.py其中包含aws_lambda_function资源使用的部署工件。所以这是一个多合一的例子,不需要进一步的压缩等。
处理程序
def lambda_handler(event, context):
return {
'message' : 'CloudWatch Lambda Insights Example'
}
主文件
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_lambda_function" "insights_example" {
function_name = "insights-example"
runtime = "python3.8"
handler = "handler.lambda_handler"
role = aws_iam_role.insights_example.arn
filename = "${path.module}/lambda.zip"
layers = [
"arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:14"
]
depends_on = [
data.archive_file.insights_example
]
}
resource "aws_iam_role" "insights_example" {
name = "InsightsExampleLambdaRole"
assume_role_policy = data.aws_iam_policy_document.lambda_assume.json
}
resource "aws_iam_role_policy_attachment" "insights_example" {
role = aws_iam_role.insights_example.id
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
resource "aws_iam_role_policy_attachment" "insights_policy" {
role = aws_iam_role.insights_example.id
policy_arn = "arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy"
}
data "aws_iam_policy_document" "lambda_assume" {
statement {
effect = "Allow"
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["lambda.amazonaws.com"]
}
}
}
data "archive_file" "insights_example" {
type = "zip"
source_file = "${path.module}/handler.py"
output_path = "${path.module}/lambda.zip"
}
THE END
二维码