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

如何用Terraform自动生成并下载API Gateway SDK?

问题:Terraform生成API Gateway SDK后无法保存为有效ZIP文件

我通过Terraform的aws_api_gateway_sdk数据源生成API Gateway的JavaScript SDK,代码如下:

data "aws_api_gateway_sdk" "example" {
  rest_api_id = aws_api_gateway_stage.example.rest_api_id
  stage_name  = aws_api_gateway_stage.example.stage_name
  sdk_type    = "javascript"
}

tfstate文件中该数据源的输出如下:

{
  "mode": "data",
  "type": "aws_api_gateway_sdk",
  "name": "example",
  "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
  "instances": [
    {
      "schema_version": 0,
      "attributes": {
        "body": "PK\u0003\u0004\..........00",
        "content_disposition": "attachment; filename=\"null-2023-04-18T22:00:16Z-javascript.zip\"",
        "content_type": "application/octet-stream",
        "id": "REST_ID:dev:javascript",
        "parameters": null,
        "rest_api_id": "REST_ID",
        "sdk_type": "javascript",
        "stage_name": "dev"
      },
      "sensitive_attributes": []
    }
  ]
}

尝试用local-exec、archive_file、local_file等方式提取保存body内容,始终无法得到本地可正常解压的SDK ZIP文件。


解决方法

核心问题是:aws_api_gateway_sdk返回的body是Base64编码的二进制ZIP数据,直接写入文件会把Base64字符串当作文本保存,导致ZIP文件损坏,必须先解码再写入。

方法1:使用local_file资源(推荐)

利用Terraform内置的base64decode()函数解码二进制内容,直接写入文件:

resource "local_file" "api_gateway_sdk" {
  content         = base64decode(data.aws_api_gateway_sdk.example.body)
  filename        = "./api-gateway-javascript-sdk.zip"
  file_permission = "0644"
}

方法2:使用local-exec配合命令行解码

如果需要用命令行处理,要在命令中加入Base64解码步骤:

  • Linux/macOS环境:
resource "null_resource" "save_sdk" {
  triggers = {
    # 当SDK内容变化时重新执行
    sdk_content = data.aws_api_gateway_sdk.example.body
  }

  provisioner "local-exec" {
    command = "echo '${data.aws_api_gateway_sdk.example.body}' | base64 -d > ./api-gateway-sdk.zip"
  }
}
  • Windows环境:
resource "null_resource" "save_sdk" {
  triggers = {
    sdk_content = data.aws_api_gateway_sdk.example.body
  }

  provisioner "local-exec" {
    command = "echo ${data.aws_api_gateway_sdk.example.body} > temp.b64 && certutil -decode temp.b64 api-gateway-sdk.zip && del temp.b64"
  }
}

关键说明

  • tfstate中body字段的PK\u0003\u0004是ZIP文件的标准起始标识,说明原始内容确实是ZIP二进制数据,只是被Base64编码后存储。
  • Terraform 0.12及以上版本都支持base64decode()函数,确保你的Terraform版本符合要求。

内容的提问来源于stack exchange,提问作者Luka Klarić

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:37:42