2.2.1.4. Composing & Deploying IaC Templates (AWS SAM, AWS CloudFormation, AWS CDK)
2.2.1.4. Composing & Deploying IaC Templates (AWS SAM, AWS CloudFormation)
Templates are the source code of your infrastructure. Writing maintainable templates requires the same discipline as writing application code — modularity, parameterization, and version control.
CloudFormation template structure:
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
Environment:
Type: String
AllowedValues: [dev, staging, prod]
Conditions:
IsProd: !Equals [!Ref Environment, prod]
Resources:
MyBucket:
Type: AWS::S3::Bucket
DeletionPolicy: !If [IsProd, Retain, Delete]
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: aws:kms
Outputs:
BucketArn:
Value: !GetAtt MyBucket.Arn
Export:
Name: !Sub "${Environment}-BucketArn"
Key CloudFormation features for the exam:
- Intrinsic functions:
!Ref,!Sub,!GetAtt,!If,!Select,!Split,!Join - Cross-stack references:
Export/Fn::ImportValueshare outputs between stacks - Nested stacks: Break large templates into reusable child stacks via
AWS::CloudFormation::Stack - Dynamic references:
{{resolve:ssm:param-name}}pulls values from Parameter Store at deploy time - Custom resources: CloudFormation sends Create/Update/Delete requests, each with a pre-signed
ResponseURL, to a Lambda function or SNS topic and waits for aSUCCESSorFAILEDresponse at that URL — the Lambda's own return value is ignored. A handler that finishes without responding, or crashes on any request type (Delete included), leaves the stack waiting until the custom resource timeout (default 1 hour, adjustable withServiceTimeout). CloudFormation invokes the function asynchronously, so Lambda's own retries only re-run a crashing handler; CloudFormation itself never retries or infers success. Send the response on every code path (cfnresponse,try/finally). - Creation signals: by default a resource is
CREATE_COMPLETEwhen its API call succeeds, not when its software is ready. ACreationPolicy(ResourceSignal: Count,Timeout) on an EC2 instance or Auto Scaling group makes CloudFormation wait forcfn-signalcalls sent from user data after the install finishes; aWaitCondition+WaitConditionHandle(the instancecurls the handle's pre-signed URL) is the older, general-purpose alternative.DependsOnonly orders creation — it never waits for software. - Modules: reusable template fragments registered in the CloudFormation registry (type names ending in
::MODULE); a stack declares a module like any resource, customizes it through the module's properties, and the fragment expands inline — publish a new module version and consuming stacks pick it up on their next update - Sections: only
Resourcesis required;AWSTemplateFormatVersion,Description,Metadata,Parameters,Rules,Mappings,Conditions,Transform, andOutputsare optional
SAM template shortcuts:
Transform: AWS::Serverless-2016-10-31
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: python3.12
Events:
Api:
Type: Api
Properties:
Path: /hello
Method: get
Deployed, this one resource expands into six: the function, its IAM role, a Lambda permission, and the implicit API's RestApi, Deployment, and Stage.
Exam Trap: Fn::ImportValue creates a hard dependency between stacks. You cannot delete or update the exporting stack's output while any other stack imports it. For loose coupling, use SSM Parameter Store to share values instead.