Terraform中如何在aws_appsync_resolver引用aws_appsync_function的function_id
问题根因
- 你为
aws_appsync_resolver资源错误配置了for_each = var.appsync_function,会导致每创建一个AppSync函数就对应生成一个重复的Resolver,和你仅需创建单个Pipeline Resolver的需求不符。 pipeline_config.functions要求传入Function ID的数组格式,你原有代码的三目运算返回的是单个字符串/空字符串,类型不匹配,条件逻辑无法生效。
正确实现方案
方案1:硬编码指定目标函数(适用明确绑定固定key的函数场景)
直接移除Resolver上多余的for_each配置,直接引用对应函数的function_id并封装为数组即可:
#---- Create AppSync Functions ----- resource "aws_appsync_function" "appsync_functions" { for_each = var.appsync_function name = each.value.name api_id = aws_appsync_graphql_api.appsync.id data_source = each.value.data_source request_mapping_template = file(each.value.request_template_path) response_mapping_template = file(each.value.response_template_path) description = each.value.description } #---- Create AppSync Resolvers ----- resource "aws_appsync_resolver" "appsync_pipeline_resolver" { type = "Query" api_id = aws_appsync_graphql_api.appsync.id field = var.appsync_resolver.trailheadItemById.name request_template = file(var.appsync_resolver.trailheadItemById.request_template_path) response_template = file(var.appsync_resolver.trailheadItemById.response_template_path) kind = "PIPELINE" pipeline_config { functions = [aws_appsync_function.appsync_functions["trailheadItemById"].function_id] } }
方案2:动态匹配函数(适用需按名称规则匹配函数的场景)
如果不想硬编码函数的key,可以用for表达式过滤出符合名称要求的函数ID:
pipeline_config { functions = [ for func in aws_appsync_function.appsync_functions : func.function_id if func.name == var.appsync_resolver.trailheadItemById.name ] }
这个写法会自动筛选所有名称和Resolver名称匹配的函数,支持同时绑定多个符合规则的函数到Pipeline中。
内容的提问来源于stack exchange,提问作者sudhir tataraju
相关产品推荐
相关产品推荐

