如何在 Terraform 中按标签获取所有 AWS Lambda

ric*_*oon 1 amazon-web-services terraform devops terraform-provider-aws

我有带有 Name=product 标签的 Lambda。

我想使用 Terraform 获取它们,查看aws_lambda_function,我只能通过 function_name 获取单个 lambda

data "aws_lambda_function" "existing" {
   function_name = var.function_name
}
Run Code Online (Sandbox Code Playgroud)

tyr*_*ron 6

您可以使用aws_resourcegroupstaggingapi_resources检索没有更具体数据源的多个 AWS 资源的信息。

对于您的用例,考虑到Name=production,您可以使用:

data "aws_resourcegroupstaggingapi_resources" "existing" {
  resource_type_filters = ["lambda:function"]
  tag_filter {
    key    = "Name"
    values = ["production"]
  }
}

output "arns" {
  value = data.aws_resourcegroupstaggingapi_resources.existing.resource_tag_mapping_list.*.resource_arn
}
Run Code Online (Sandbox Code Playgroud)

更新:如评论中所述,上面的代码返回来自 的信息resource_tag_mapping_list,其中大部分是资源的合规信息和 ARN。但您可以将其与常规aws_lambda_function数据源配对,并使用 afor_each从 Lambda 函数检索所有信息:

# continuation of the code above
data "aws_lambda_function" "existing" {
  for_each = toset(data.aws_resourcegroupstaggingapi_resources.existing.resource_tag_mapping_list.*.resource_arn)
  function_name = each.value
}

output "functions" {
  value = data.aws_lambda_function.existing.*
}

# example of information available with this data source
output "functions_runtime" {
  value = {for fn, result in data.aws_lambda_function.existing: fn => result.runtime}
}

Run Code Online (Sandbox Code Playgroud)