Skill 3.3.3

Use infrastructure as code (IaC) templates (for example, CloudFormation templates, AWS SAM templates).

Key Concepts

CloudFormation templates declare resources, parameters, conditions and outputs, and CloudFormation works out the order of creation from references between them. AWS SAM adds compact serverless resource types and is deployed with sam build and sam deploy, while the AWS CDK lets you define the same infrastructure in programming languages and synthesises CloudFormation templates with cdk synth before cdk deploy.

Templates can be validated with cfn-lint and aws cloudformation validate-template, and Lambda code can be packaged and uploaded to S3 with sam package or aws cloudformation package. In a pipeline, CodePipeline's CloudFormation actions create or execute change sets.

Depending on the property changed, CloudFormation updates a resource with no interruption, with some interruption, or by replacement, creating a new resource and deleting the old one. Replacing a database or a resource with a custom name can lose data or fail, so you should review a change set before executing it.

Stack policies protect critical resources from updates, DeletionPolicy and UpdateReplacePolicy retain or snapshot data, and failed updates roll back automatically. Drift detection shows resources that were changed manually since the last deployment.

With AWS SAM, sam deploy creates or updates a CloudFormation stack. Using a different stack name and parameter values, for example sam deploy --stack-name app-staging --parameter-overrides Stage=staging, or a named environment in samconfig.toml (--config-env staging), deploys an independent copy.

Updates to an existing stack are applied through change sets, which you can review first. Templates should use parameters and conditions rather than hard-coded names so resources from different environments do not clash.