You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Terraform创建AWS API Gateway资源策略时JSON变量未替换异常

解决Terraform API Gateway策略模板变量不替换的问题

方案1:改用内置templatefile函数(推荐)

template_file数据源在Terraform 0.12+版本中已被内置的templatefile函数取代,后者语法更简洁且渲染更可靠。直接替换原有配置即可:

resource "aws_api_gateway_rest_api_policy" "example_policy" {
  rest_api_id = aws_api_gateway_rest_api.example.id
  policy      = templatefile("apgi_policy_private_vpc.json.tmpl", {
    region           = var.region
    aws_account_id   = var.aws_account_id
    api_id           = aws_api_gateway_rest_api.example.id
    vpc_endpoint_id  = var.vpc_endpoint_id
  })
}

你的JSON模板无需修改,templatefile函数完全兼容${变量名}的引用格式。

方案2:修复template_file数据源的使用(兼容旧版本)

若必须保留template_file,需检查以下几点:

  • 确认模板路径正确:apgi_policy_private_vpc.json.tmpl需与Terraform配置文件同目录,或使用绝对路径指定。
  • 验证变量定义:确保var.region、var.aws_account_id等变量已在variables.tf中正确声明,示例:
variable "region" {
  type = string
}

variable "aws_account_id" {
  type = string
}

variable "vpc_endpoint_id" {
  type = string
}
  • 强制刷新渲染:执行terraform refresh后重新运行terraform apply,确保数据源重新生成模板内容。

额外注意事项

  • 保证JSON语法合法:变量值不能包含破坏JSON结构的字符(如未转义的双引号),如有特殊字符需提前转义。
  • 验证最终策略:部署完成后可通过AWS控制台查看API策略,确认变量已替换为实际值。

内容的提问来源于stack exchange,提问作者DSR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 08:50:58