Sub topic 2
Anatomy of a template
This chapter assumes you can read YAML, know what an S3 bucket is, and have the AWS CLI configured. It explains the sections of a CloudFormation template, which ones are required, and how they relate. Later chapters cover each section in depth.
What a template is
A template is a text file that describes the resources you want. CloudFormation reads it and creates, updates, or deletes AWS resources to match. You can write templates in YAML or JSON. Both formats support the same features. YAML allows comments and short function syntax such as !Ref, so most people prefer it.
A template is only a description. The running resources belong to a stack, which is created from the template. You can create many stacks from one template.
The top-level sections
A template is a map of top-level keys. Each key is a section.
| Section | Required | Purpose |
|---|---|---|
| `AWSTemplateFormatVersion` | No | Template format version. The only valid value is `"2010-09-09"`. |
| `Description` | No | Text describing the template. Maximum 1,024 bytes. |
| `Metadata` | No | Arbitrary data about the template, such as console parameter grouping. |
| `Parameters` | No | Values supplied when you create or update a stack. |
| `Rules` | No | Validation of parameter combinations at deploy time. |
| `Mappings` | No | Fixed lookup tables. |
| `Conditions` | No | Boolean expressions that switch resources or properties on and off. |
| `Transform` | No | Macros that process the template, such as `AWS::Serverless-2016-10-31`. |
| `Resources` | Yes | The AWS resources to provision. |
| `Outputs` | No | Values to show or export after deployment. |
Only Resources is required, and it must contain at least one resource. The order of sections does not affect behavior. CloudFormation works out the order in which to create resources from the references between them. Authors usually write sections in the order above because it reads from inputs to outputs.
A complete skeleton
This template uses the common sections. Save it as template.yaml.
AWSTemplateFormatVersion: "2010-09-09"
Description: Anatomy demo with one bucket
Metadata:
Purpose: Teaching example
Parameters:
EnvName:
Type: String
Default: dev
AllowedValues:
- dev
- prod
Mappings:
EnvSettings:
dev:
RetentionDays: 7
prod:
RetentionDays: 90
Conditions:
IsProd: !Equals [!Ref EnvName, prod]
Resources:
AppBucket:
Type: AWS::S3::Bucket
Properties:
VersioningConfiguration:
Status: !If [IsProd, Enabled, Suspended]
LifecycleConfiguration:
Rules:
- Id: ExpireOldObjects
Status: Enabled
ExpirationInDays: !FindInMap [EnvSettings, !Ref EnvName, RetentionDays]
Outputs:
BucketArn:
Description: ARN of the bucket
Value: !GetAtt AppBucket.ArnCheck the syntax without creating anything:
aws cloudformation validate-template --template-body file://template.yamlvalidate-template checks structure and syntax. It does not check that property values are acceptable to the service, so some errors appear only during deployment.
How the sections connect
Sections feed one another in one direction. Inputs (Parameters) and constants (Mappings) are read by Conditions and Resources. Resources produce values that Outputs report.
Two rules follow from this flow:
Mappingscannot contain functions or references. Values must be literal strings, numbers, or lists. If you need to compute a value, use a parameter or a condition instead.Outputscan read resources, but resources cannot read outputs from the same template. Other stacks can read exported outputs, which a later chapter covers.
Logical IDs and names
Every parameter, mapping, condition, resource, and output has a logical ID. This is the key under its section, such as AppBucket. Logical IDs must be alphanumeric (A-Za-z0-9) and unique within the template.
The logical ID is how CloudFormation tracks a resource between updates. If you rename AppBucket to DataBucket, CloudFormation sees a new resource. It creates the new one and deletes the old one. This is a common source of unplanned replacement.
The physical ID is the real name or identifier the service assigns, such as the generated bucket name. Leave out explicit names such as BucketName where you can. A fixed name stops CloudFormation from creating a replacement while the old resource still exists. It also prevents deploying the same template twice in one Region.
JSON equivalent and syntax gotchas
The same structure in JSON uses the long function names:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"AppBucket": {
"Type": "AWS::S3::Bucket"
}
},
"Outputs": {
"BucketName": {
"Value": { "Ref": "AppBucket" }
}
}
}In YAML, !Ref AppBucket is shorthand for Fn::Ref: AppBucket. Watch for these errors:
- Short forms cannot be nested directly without care.
!Suband!GetAttwork, but writing!Base64 !Sub ...is invalid in some contexts. Use the full formFn::Base64: !Sub ...when a short form fails. - Quote version strings such as
"2010-09-09"and values like"0123". Unquoted values may be parsed as dates or numbers. - Indentation matters in YAML. A resource's
TypeandPropertiesmust sit one level inside the logical ID.
Limits to know
| Limit | Value |
|---|---|
| Template body passed in the request | 51,200 bytes |
| Template body from S3 | 1 MB |
| Resources per template | 500 |
| Parameters per template | 200 |
| Mappings per template | 200 |
| Outputs per template | 200 |
Reaching these limits is a sign to split a template, which later chapters on nested stacks and cross-stack references cover.
Exercise
You rename the logical ID of a bucket from AppBucket to DataBucket and update the stack. The template is otherwise unchanged. What does CloudFormation do, and why?
Show answer
It creates a new bucket for DataBucket and deletes the old AppBucket. CloudFormation tracks resources by logical ID, so a renamed ID looks like one resource removed and another added. Data in the old bucket is lost unless a DeletionPolicy or similar protection keeps it.
Exercise
Can a Mappings entry use !Ref EnvName as one of its values? What would you use instead?
Show answer
No. Mappings accept only literal strings, numbers, and lists, not functions or references. Use a parameter, or a condition with !If, to choose between values.