DependsOn attribute to enforce an explicit creation order between resources. The sample template ensures a public-read bucket policy is attached only after the corresponding Amazon S3 bucket has been created. While CloudFormation usually infers correct ordering, explicit dependencies are required in some situations (for example, when a bucket policy references a bucket name supplied by a parameter or when using custom resources). Without DependsOn, you can see errors like “bucket does not exist” if the policy is applied before the bucket is available.
CloudFormation typically determines creation order automatically when resources reference each other using intrinsic functions (
!Ref, !GetAtt, etc.). Use DependsOn only when that implicit dependency is insufficient—such as when a policy references a bucket by name or ARN built from parameters or strings.MyS3Bucket is referenced by DependsOn in the bucket policy:
DependsOn here?
- Implicit dependencies: CloudFormation infers ordering when a resource references another resource’s logical ID via intrinsic functions (for example,
!Ref MyS3Bucketor!GetAtt MyS3Bucket). In those cases, explicitDependsOnis not needed. - When implicit links are missing: If both the bucket and the policy use the same parameter value (for example,
InputBucketName) or a constructed ARN/string, CloudFormation may not infer a relationship between the resources. The policy can end up being created before the bucket. AddingDependsOn: MyS3Bucketensures the bucket is created (or updated) first and prevents errors where the policy references a non-existent bucket.
Avoid overusing
DependsOn. Adding many explicit dependencies can unnecessarily serialize resource creation, making stack creations and updates slower. Also take care to avoid creating circular dependencies.| Template Section | Purpose | Example |
|---|---|---|
| Mappings | Static lookups used by the template | DevMap mapping for developer -> environment |
| Parameters | Values supplied when creating the stack | InputBucketName, InputDeveloperName |
| Conditions | Conditional logic to detect environments | IsProd checks mapped environment equals “Production” |
| Resources | The actual AWS resources created | MyS3Bucket (S3 bucket) and MyS3BucketPolicy (Bucket policy with DependsOn) |
- Prefer implicit dependencies via intrinsic functions when possible.
- Use
DependsOnwhen resources must be created in a strict order but do not have intrinsic references (e.g., resource name/ARN provided via a parameter). - Keep dependency graphs simple to avoid long-running updates and circular references.
- CloudFormation — Learn KodeKloud course
- Amazon S3 — Learn KodeKloud course
- AWS CloudFormation Documentation
DependsOn attribute listing the logical name(s) of resources it must wait for. In this example, MyS3BucketPolicy will only be applied after MyS3Bucket has been successfully created.