Updating Infrastructure as Code (IaC) Templates: AWS SAM & CloudFormation
Update existing IaC templates (for example, AWS SAM templates, CloudFormation templates)
Updating Infrastructure as Code (IaC) Templates: AWS SAM & CloudFormation
This study guide focuses on the critical skill of modifying and evolving existing cloud infrastructure using AWS CloudFormation and the AWS Serverless Application Model (SAM). Managing updates effectively ensures environment consistency and minimizes downtime during the deployment lifecycle.
Learning Objectives
After studying this guide, you should be able to:
- Identify the differences between Update-in-Place and Replacement behaviors in CloudFormation.
- Utilize Change Sets to preview the impact of template modifications before execution.
- Update AWS SAM templates to modify Lambda functions, APIs, and event sources.
- Manage environment-specific configurations using Parameters and Mappings.
- Perform safe rollbacks and handle update failures within a CI/CD pipeline.
Key Terms & Glossary
- IaC (Infrastructure as Code): The process of managing and provisioning computer data centers through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools.
- Change Set: A preview of the changes CloudFormation will make to your stack, allowing you to see which resources will be created, updated, or deleted.
- Drift Detection: A feature that identifies whether a stack's actual configuration has diverged from its expected template configuration due to manual changes.
- Intrinsic Function: Special functions (e.g.,
Ref,Fn::GetAtt) used in templates to assign values to properties that are not available until runtime. - SAM Transform: A macro (declared as
Transform: AWS::Serverless-2016-10-31) that converts SAM syntax into standard CloudFormation syntax during deployment.
The "Big Idea"
In a modern DevOps environment, the infrastructure is treated with the same rigor as application code. Updating IaC templates allows teams to evolve their architecture—adding capacity, tightening security, or deploying new features—while maintaining a "source of truth." By updating the template instead of the live resources, you ensure that every environment (Dev, Test, Prod) remains synchronized and reproducible.
Formula / Concept Box
CloudFormation Update Behaviors
| Update Type | Impact | Example Resource Property |
|---|---|---|
| Update with No Interruption | Resource updated without any downtime. | Changing an S3 Bucket's VersioningConfiguration. |
| Updates with Some Interruption | Resource remains, but service may be briefly unavailable. | Changing an EC2 InstanceType. |
| Replacement | The old resource is deleted and a new one is created. | Changing the DBInstanceIdentifier of an RDS instance. |
[!WARNING] Always check the AWS Resource Property reference. If an update requires Replacement, the Physical ID of the resource will change, and any data not backed up or stored externally may be lost.
Hierarchical Outline
- CloudFormation Update Workflow
- Template Modification: Editing the JSON/YAML source code.
- Change Set Creation: Generating a summary of proposed actions.
- Execution: Applying the Change Set to the stack.
- AWS SAM Specific Updates
- Template.yaml: Modifying
AWS::Serverlessresource types. - SAM CLI (
sam deploy): Automating the update process and managing the S3 deployment bucket.
- Template.yaml: Modifying
- Advanced Update Techniques
- Parameters & Mappings: Using
!Refand!FindInMapto change values across environments without changing logic. - Stack Sets: Updating templates across multiple AWS accounts and regions simultaneously.
- Parameters & Mappings: Using
- Handling Failures
- Rollback Configuration: Automatically returning to the last known stable state on error.
- Termination Protection: Preventing accidental deletion of critical stacks during updates.
Visual Anchors
The Change Set Workflow
Infrastructure Layering
This TikZ diagram visualizes how a template update interacts with the stack layers.
\begin{tikzpicture}[node distance=1.5cm, every node/.style={fill=white, font=\footnotesize}] % Layers \draw[thick, fill=blue!10] (0,0) rectangle (6,1) node[midway] {Resources (EC2, S3, RDS)}; \draw[thick, fill=green!10] (0,1.2) rectangle (6,2.2) node[midway] {Stack Logic (Mappings, Outputs)}; \draw[thick, fill=orange!10] (0,2.4) rectangle (6,3.4) node[midway] {Input Parameters (InstanceType, Env)};
% Update Arrow \draw[->, ultra thick, red] (7, 3.4) -- (7, 0) node[midway, right] {Update Propagation}; \node[align=left] at (3, 4) {\textbf{CloudFormation Stack Structure}}; \end{tikzpicture}
Definition-Example Pairs
- Parameter: A way to pass custom values to your template at runtime.
- Example: Defining an
InstanceTypeparameter so you can uset3.microin Dev andm5.largein Prod using the same template.
- Example: Defining an
- Mapping: A look-up table within the template to provide values based on a key.
- Example: A map that provides different AMI IDs for the
us-east-1andeu-west-1regions.
- Example: A map that provides different AMI IDs for the
- Update Policy: Defines how CloudFormation handles updates for specific resources, like an Auto Scaling Group.
- Example: Using
AutoScalingRollingUpdateto ensure a minimum number of instances remain online while the group is being updated.
- Example: Using
Worked Examples
Scenario 1: Updating a SAM Lambda Function
Goal: Update an existing AWS SAM template to increase the memory of a Lambda function and add an environment variable.
Original Template snippet:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs18.xUpdated Template snippet:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs18.x
MemorySize: 512 # Added property
Environment:
Variables:
STAGE: !Ref StageName # Added dynamic referenceSteps to execute:
- Save the changes to
template.yaml. - Run
sam buildto prepare the artifacts. - Run
sam deployto create a Change Set and update the CloudFormation stack.
Scenario 2: Adding a Parameter to CloudFormation
Goal: Make the S3 bucket name configurable instead of hardcoded.
Change:
- Add a
Parameterssection. - Use
!Refin theResourcessection.
Parameters:
AppBucketName:
Type: String
Default: my-default-app-bucket
Resources:
S3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Ref AppBucketNameCheckpoint Questions
- What is the main benefit of using a Change Set before updating a production stack?
- If you change the
AllocatedStorageof an Amazon RDS instance in a CloudFormation template, does it result in a replacement of the instance? - Which command is used in the SAM CLI to synchronize local template changes with the AWS cloud environment?
- How does CloudFormation behave if one resource fails to update during a multi-resource stack update?
- True/False: You can use
!Refto refer to a value defined in theMappingssection of a template.