模板结构
AWSTemplateFormatVersion、Resources、Outputs。
35 分钟
模板结构
CloudFormation 模板是 JSON 或 YAML 文档,顶层块描述版本、参数、资源与输出。Resources 是唯一必填段——没有资源就没有 Stack。
学习目标
- 读懂
AWSTemplateFormatVersion、Description、Resources、Outputs - 写最小可部署的 YAML 模板
- 对照 tf-hcl 的 block 结构
最小模板
AWSTemplateFormatVersion: '2010-09-09'
Description: CodeRoadMap CFN 最小示例
Resources:
LogsBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: coderoadmap-cfn-logs-demo
Tags:
- Key: Project
Value: coderoadmap
Outputs:
BucketName:
Description: S3 桶名
Value: !Ref LogsBucket
Export:
Name: !Sub '${AWS::StackName}-LogsBucket'
| 顶层键 | 作用 |
|---|---|
AWSTemplateFormatVersion | 模板语言版本,通常 2010-09-09 |
Description | 人类可读说明 |
Resources | 必填,要创建的 AWS 资源 |
Outputs | 部署后暴露的值,可跨 Stack 导出 |
内置函数(Intrinsic Functions)
# !Ref → 引用 Parameter 或 Resource
# !GetAtt → 读资源属性(如 VPC ID)
# !Sub → 字符串替换 ${Var}
# !Join / !Split / !Select → 列表与字符串操作
与 HCL 的 var.xxx、resource.xxx.attr 对应;CFN 在 YAML 内嵌函数,TF 在 表达式 里引用。
与 Terraform 文件对照
| CloudFormation | Terraform |
|---|---|
template.yaml | *.tf 根模块 |
Resources | resource block |
Outputs | output block |
| Stack | terraform apply 一次完整变更 |
CodeRoadMap 仓库若已有 infra/*.tf,可并行写 cfn/template.yaml 对照学习,生产仍以 TF 为准。