构建AWS Service Catalog Terraform模板报Invalid template body错误
问题描述
构建AWS Service Catalog产品的Terraform配置如下:
resource "aws_servicecatalog_product" "data-ml-pipeline-service-catalog-product" { name = "data-ml-pipeline-service-catalog-product" owner = "data-ml" type = "CLOUD_FORMATION_TEMPLATE" provisioning_artifact_parameters { template_url = "https://s3.amazonaws.com/cf-templates-ozkq9d3hgiq2-us-east-1/temp1.json" type = "CLOUD_FORMATION_TEMPLATE" }
按照参考配置编写后,执行时报错:Error: error creating Service Catalog Product: InvalidParametersException: Invalid templateBody. Please make sure that your template is valid
当前使用的CloudFormation模板为YAML格式,内容如下:
--- ModelBuildCodeCommitRepository: Properties: Code: BranchName: main S3: Bucket: sagemaker-servicecatalog-seedcode-us-west-2 Key: toolchain/image-build-model-building-workflow-v1.0.zip RepositoryDescription: ? "Fn::Sub" : "SageMaker Model building workflow infrastructure as code for the Project ${SageMakerProjectName}" RepositoryName: ? "Fn::Sub" : "sagemaker-${SageMakerProjectName}-${SageMakerProjectId}-modelbuild" Type: "AWS::CodeCommit::Repository" Parameters: SageMakerProjectId: Description: "Service-generated id of the project" NoEcho: true Type: String SageMakerProjectName: AllowedPattern: "^[a-zA-Z](-*[a-zA-Z0-9])*" Description: "Name of the project" MaxLength: 32 MinLength: 1 NoEcho: true Type: String
报错根因
报错是CloudFormation模板本身存在语法和结构错误,和Terraform资源配置无关,具体问题如下:
- 缺少CloudFormation模板必填的顶级字段
AWSTemplateFormatVersion,该字段是CFN识别模板格式的强制声明,固定值为"2010-09-09" - 资源层级错误:所有AWS资源必须定义在顶级
Resources字段下,当前模板直接把ModelBuildCodeCommitRepository资源放在了顶级,和Parameters平级,CFN解析时无法识别资源定义 - 内置函数语法错误:
Fn::Sub的写法错误使用了YAML复杂键标记?,该标记仅用于键名是复杂结构(比如映射、列表)的场景,普通字符串键直接写Fn::Sub即可,不需要加?前缀
修复方案
- 修正CloudFormation模板,补全必填字段、调整资源层级、修正内置函数写法,修正后的模板内容如下:
AWSTemplateFormatVersion: "2010-09-09" Parameters: SageMakerProjectId: Description: "Service-generated id of the project" NoEcho: true Type: String SageMakerProjectName: AllowedPattern: "^[a-zA-Z](-*[a-zA-Z0-9])*" Description: "Name of the project" MaxLength: 32 MinLength: 1 NoEcho: true Type: String Resources: ModelBuildCodeCommitRepository: Type: "AWS::CodeCommit::Repository" Properties: Code: BranchName: main S3: Bucket: sagemaker-servicecatalog-seedcode-us-west-2 Key: toolchain/image-build-model-building-workflow-v1.0.zip RepositoryDescription: Fn::Sub: "SageMaker Model building workflow infrastructure as code for the Project ${SageMakerProjectName}" RepositoryName: Fn::Sub: "sagemaker-${SageMakerProjectName}-${SageMakerProjectId}-modelbuild"
- 将修正后的模板上传到S3对应路径,确保Terraform配置里的
template_url和模板实际存放路径一致,且该S3路径和Service Catalog部署区域匹配,跨区域存放模板可能出现访问权限问题。 - 重新执行Terraform plan/apply即可正常创建Service Catalog产品。
内容的提问来源于stack exchange,提问作者awscoder
相关产品推荐
相关产品推荐

