AWS CloudFormation Best Practices

On this page

Even with tools like CDK, understanding the underlying CloudFormation mechanics is crucial. Improperly structured stacks can lead to circular dependencies, update rollbacks, and stuck resources. This guide covers nested stacks, cross-stack references, and drift detection.

Cross-Stack References vs Nested Stacks

FeatureCross-Stack Refs (Export/Import)Nested Stacks
CouplingLoose (Independent lifecycles)Tight (Parent controls Child)
UpdatesCan block updates if exported value is in useUpdated as a single unit
Use CaseSharing VPC, Security Groups across appsBreaking up large app templates (Limit 200 resources)

Exporting Values

YAML6 lines
# Networking Stack
Outputs:
  PrivateSubnetId:
    Value: !Ref PrivateSubnet
    Export:
      Name: !Sub "${AWS::StackName}-PrivateSubnet"

Importing Values

YAML6 lines
# App Stack
Resources:
  MyInstance:
    Type: AWS::EC2::Instance
    Properties:
      SubnetId: !ImportValue Networking-PrivateSubnet

Preventing Zombie Resources

Use `CreationPolicy` and `cfn-signal` for EC2 instances to ensure the bootstrap script (UserData) completed successfully before marking the stack as CREATE_COMPLETE.

YAML9 lines
Properties:
  UserData:
     Fn::Base64: !Sub |
       #!/bin/bash
       yum install -y httpd
       /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource WebServer --region ${AWS::Region}
CreationPolicy:
  ResourceSignal:
    Timeout: PT5M

Key Takeaways

  • Use **Nested Stacks** to overcome the 200 resource limit.
  • Avoid modifying Exported Outputs; it requires deleting all importing stacks first.
  • Use **Change Sets** to preview operations before execution.

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.