Sub topic 1
From Console Clicks to Declarative Infrastructure
Prerequisites
Assume you know basic AWS services such as S3 and IAM, can read YAML, and can run AWS CLI commands. CloudFormation templates describe the desired infrastructure. CloudFormation compares that description with the current stack and creates or changes resources to match it.
From Console Clicks to Declarative Infrastructure
A console workflow records actions in your memory. A CloudFormation template records them in a version-controlled file. You can review, reuse, and apply the same design in another account or Region.
A stack is a managed group of AWS resources created from one template. CloudFormation determines a dependency order, sends requests to AWS services, and reports each operation as a stack event.
Anatomy of a Template
A template can contain sections with different roles:
| Section | Purpose |
|---|---|
| Parameters | Values supplied when the stack runs |
| Resources | AWS objects that CloudFormation creates |
| Outputs | Values displayed or exported after deployment |
Mappings, Conditions, and Metadata are also available. Resources is the central section. The other sections configure or expose it.
Declaring Resources
Each resource has a logical ID, a CloudFormation type, and optional properties. The logical ID is stable within the template. Changing some properties updates a resource; changing others replaces it. Check the resource documentation before changing production infrastructure.
Parameterizing a Template
Parameters prevent environment-specific values from being hard-coded. This example accepts an environment name and a comma-separated list of Availability Zones.
AWSTemplateFormatVersion: "2010-09-09"
Description: Parameterized S3 bucket
Parameters:
EnvName:
Type: String
Default: dev
AllowedValues: [dev, prod]
AvailabilityZones:
Type: CommaDelimitedList
Resources:
AppBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "${AWS::StackName}-${EnvName}-${AWS::Region}"
Tags:
- Key: Environment
Value: !Ref EnvName
- Key: Placement
Value: !Join ["-", [!Ref EnvName, !Select [0, !Ref AvailabilityZones]]]
Outputs:
BucketArn:
Value: !GetAtt AppBucket.ArnPseudo Parameters and Intrinsic Functions
Pseudo parameters are values supplied automatically. AWS::Region is the current Region, and AWS::StackName is the stack's name. Other examples include AWS::AccountId and AWS::NoValue.
Intrinsic functions calculate values while CloudFormation processes the template:
Refreturns a parameter value or a resource's identifier.Fn::GetAttreturns a resource attribute, such as an ARN.Fn::Subsubstitutes variables inside a string.Fn::Joincombines values with a delimiter.Fn::Selectchooses an item by zero-based index.
Exercise
Which intrinsic function would you use to select the first item from a list parameter?
Show answer
Use Fn::Select with index 0, such as !Select [0, !Ref AvailabilityZones].