DependsOn and Creation Order
What You'll Learn
You'll learn how to explicitly control the order in which CloudFormation creates resources when the natural dependencies aren't enough.
Why Creation Order Matters
CloudFormation is smart about figuring out dependencies. When you use Ref or Fn::GetAtt to reference one resource from another, CloudFormation automatically knows to create the referenced resource first. But sometimes resources depend on each other in ways CloudFormation can't detect automatically.
Think of it like a recipe: CloudFormation knows you need eggs before making an omelet (because the omelet recipe references eggs), but it might not know you need to preheat the oven before baking—there's no explicit ingredient reference, just a timing requirement.
The DependsOn Attribute
The DependsOn attribute tells CloudFormation: "Don't create this resource until these other resources are completely created first." You add it directly to a resource definition.
When to use DependsOn:
- A resource needs another resource to exist, but doesn't reference it with
ReforFn::GetAtt - An EC2 instance needs an Internet Gateway attached before it can reach the internet
- An application server needs a database to be fully running before starting
- IAM roles need to exist before resources that assume them
Common Scenarios
You might need DependsOn when:
- Resources have implicit dependencies (like an EC2 instance needing a VPN gateway)
- Creation timing matters (a Lambda function needs a custom resource to run first)
- You're working with IAM policies that need time to propagate
Key Takeaway: Use DependsOn when CloudFormation can't automatically detect that one resource must be fully created before another begins—it's your manual override for the creation sequence.