AWS CloudFormation Best Practices

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

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

Importing Values

# 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.

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.

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.