AWS Terraform 提供程序的 aws_lambda_function 资源中没有“布尔开关”,您可以将其设置为 true,这将启用 Cloudwatch Lambda Insights。
幸运的是,您可以自己完成此操作。以下 Terraform 定义基于此 AWS 文档:Using the AWS CLI to enable Lambda Insights on an existing Lambda function
这个过程包括两个步骤:
- 为您的 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对于每个区域都是不同的。我在上面链接的文档有一个link 到它们的列表。此外,如果您的 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 init
terraform plan
terraform apply
除了部署所需的资源外,它还将创建一个包含handler.py 的zip 存档,这是aws_lambda_function 资源使用的部署工件。所以这是一个一体化的例子,不需要进一步压缩等。
handler.py
def lambda_handler(event, context):
return {
'message' : 'CloudWatch Lambda Insights Example'
}
main.tf
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"
}