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

使用get_template()创建CFN栈遇参数验证错误,求解决方案

问题

调用CloudFormation的create_stack()时触发ParamValidationError,提示TemplateBody参数类型无效(要求为字符串,实际传入字典)。场景是通过get_template()获取现有栈模板后直接复用创建新栈。

错误信息

{
  "errorMessage": "参数验证失败:\nTemplateBody参数类型无效,值: {'TemplateBody': OrderedDict([('Resources', ...)]), 'ResponseMetadata': {...}}, 类型: <class 'dict'>, 有效类型: <class 'str'>",
  "errorType": "ParamValidationError",
  "requestId": "f879686f-2cbf-4b75-aa7e-b940535f0a7d",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 22, in lambda_handler\n    create_cfn_stack(stack_name, stack_id)\n",
    "  File \"/var/task/lambda_function.py\", line 43, in create_cfn_stack\n    cfn.create_stack(\n",
    "  File \"/var/runtime/botocore/client.py\", line 391, in _api_call\n    return self._make_api_call(operation_name, kwargs)\n",
    ...
  ]
}

原实现代码

def create_cfn_stack(stack_name, stack_id):
  try:
      template = cfn.get_template(StackName=stack_id)
      cfn.create_stack(
        StackName=stack_name,
        TemplateBody=template,
        Capabilities=['CAPABILITY_IAM']
      )
      logger.info("Success :: create_cfn_stack %s", stack_name)
  except ClientError as error:
      logger.error(error)
      return None
  return "created:OK"
问题根源
  • get_template()的返回值是一个完整的响应字典,实际的CloudFormation模板内容嵌套在TemplateBody字段下,且该字段的值是字典/OrderedDict类型
  • create_stack()的TemplateBody参数要求传入JSON格式的字符串,不能直接传入字典对象
修复代码

先提取嵌套的模板字典,再转换为JSON字符串,修改后的代码如下:

import json

def create_cfn_stack(stack_name, stack_id):
  try:
      template_response = cfn.get_template(StackName=stack_id)
      # 提取嵌套的模板字典
      template_dict = template_response['TemplateBody']
      # 转换为JSON字符串
      template_json = json.dumps(template_dict)
      cfn.create_stack(
        StackName=stack_name,
        TemplateBody=template_json,
        Capabilities=['CAPABILITY_IAM']
      )
      logger.info("Success :: create_cfn_stack %s", stack_name)
  except ClientError as error:
      logger.error(error)
      return None
  return "created:OK"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:21:56