如何阻止Terraform每次部署时重新创建AWS REST API?
问题描述
使用Terraform创建AWS REST API时,无论配置是否有变更,每次执行Terraform都会重新创建该API,需要解决这个问题。
现有配置
REST API资源配置
resource "aws_api_gateway_rest_api" "rest_api" { name = "${var.resource_prefix}-rest-api" description = "REST API" body = data.template_file.open_api_spec.rendered endpoint_configuration { types = ["REGIONAL"] } lifecycle { create_before_destroy = true } tags = var.common_tags }
模板文件资源配置
data "template_file" "open_api_spec" { template = file("openapi-spec.json") vars = { x = "1234" y = "${var.resource_prefix}-api-authorizer-${var.resource_suffix}" z = "arn:aws:lambda:${var.aws_region}:${var.aws_account_id}:function:${var.resource_prefix}-api-authorizer-${var.resource_suffix}" aws_region = var.aws_region allowed_cors_origin = var.allowed_cors_origin } }
解决方案
这个问题核心是渲染后的OpenAPI JSON存在无意义格式差异(比如空格、换行、引号排版不一致),导致Terraform误判body字段有变更,进而触发API重建。可以通过以下方法解决:
改用内置
templatefile函数替代template_file数据源template_file是旧版数据源,内置的templatefile函数渲染结果更稳定,能避免多数格式差异。修改REST API配置如下,同时删除原template_file数据源:resource "aws_api_gateway_rest_api" "rest_api" { name = "${var.resource_prefix}-rest-api" description = "REST API" body = templatefile("openapi-spec.json", { x = "1234" y = "${var.resource_prefix}-api-authorizer-${var.resource_suffix}" z = "arn:aws:lambda:${var.aws_region}:${var.aws_account_id}:function:${var.resource_prefix}-api-authorizer-${var.resource_suffix}" aws_region = var.aws_region allowed_cors_origin = var.allowed_cors_origin }) endpoint_configuration { types = ["REGIONAL"] } lifecycle { create_before_destroy = true } tags = var.common_tags }标准化渲染后的JSON格式
如果必须保留template_file,可以用jsondecode+jsonencode对渲染结果做标准化,消除格式差异:resource "aws_api_gateway_rest_api" "rest_api" { name = "${var.resource_prefix}-rest-api" description = "REST API" body = jsonencode(jsondecode(data.template_file.open_api_spec.rendered)) endpoint_configuration { types = ["REGIONAL"] } lifecycle { create_before_destroy = true } tags = var.common_tags }排查变量隐式变更
执行terraform plan查看body字段的具体变更内容,确认allowed_cors_origin等变量是否存在环境传递、动态生成的隐式变化,确保所有变量替换后的结果完全一致。
内容的提问来源于stack exchange,提问作者Remotec
相关产品推荐
相关产品推荐

