CloudFormation "Circular Dependency Between Resources": Find the Loop With cfn-lint, the S3-to-Lambda Fix, Security Groups, Log Groups, API Gateway, Cognito, SAM, and the CDK "Would Create a Cyclic Reference" Error
"Circular dependency between resources: [A, B]" is CloudFormation telling you that it cannot decide which of those resources to create first, because A needs something from B and B needs something from A. Every !Ref, !GetAtt and !Sub in a template is a silent "create that one first," and DependsOn is a loud one; a loop in those arrows stops the stack before it creates anything. The fix is almost never another DependsOn. It is replacing one reference with a value you can write down yourself: a bucket name built from the account ID, a function name built from the stack name, an ARN assembled as a string. Here is the surprise behind the most common version, an S3 bucket that triggers a Lambda function: the bucket depends on the function's permission, because CloudFormation checks that S3 may invoke the function at the moment it creates the bucket, so the permission, the function, its role and the bucket chase each other in a ring. This page shows how to read the list in the message, how to find the loop in ten seconds with a free tool that runs on your laptop, the fix for each of the nine shapes this error takes (S3 to Lambda, security groups, log groups, API Gateway, Cognito, OpenSearch, EC2 instance roles, SAM and the Serverless Framework), and the CDK version of the same problem, "would create a cyclic reference," with the one-line fix that worked in a two-stack test.
Jake runs a phone repair shop. Customers upload photos of broken screens through the shop's website, and Ethan, Jake's developer friend, had written a small function to resize them. He put the bucket, the function and the permission in one CloudFormation template so the whole thing could be rebuilt in a minute. The first deploy did not create a thing. It came back with a list of four names in square brackets and the words "circular dependency." Jake, reading over his shoulder, asked the obvious question: "If the bucket needs the function and the function needs the bucket, how does anyone ever set this up?" This page is Ethan's answer, including the two places where the first fix he tried made the loop longer.
New to CloudFormation? Our plain-English guide to stacks explains templates, resources and what "create" really does in about ten minutes. You can follow this page without it.
What "circular dependency between resources" means
CloudFormation does not create the resources in your template top to bottom. It builds a map of who needs what, then creates everything it can in parallel, waiting only where a resource needs a value from another one. Three things add an arrow to that map:
- Intrinsic references: a
!Ref,!GetAttor!Subwith${Name}in a resource's properties means "create that resource first, because I need its ID, ARN or name." These are the implicit dependencies, and they are everywhere in a real template. - DependsOn: the explicit version. "Create that one first" even when no value flows between them.
- Behind the scenes checks: a few resource types check something about another resource while they are being created. The S3 bucket notification is the famous one: when CloudFormation creates a bucket with a notification configuration, it checks that the bucket is allowed to invoke the function or publish to the topic. If that permission does not exist yet, the bucket fails. So the bucket has to come after the permission, whether you say so or not.
You should know that those same arrows run the other way on delete (a resource is deleted before the one it references) and on update (the referenced resource updates first). A loop breaks all three.
When the arrows form a ring, there is no first resource, and CloudFormation refuses the template before touching your account. You see the refusal in one of four wrappers, depending on how you deploy:
| Where you deploy | What the message looks like |
|---|---|
Console or aws cloudformation create-stack | Template contains errors.: Circular dependency between resources: [MyBucket, MyPermission] |
SAM, aws cloudformation deploy, change sets | Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Circular dependency between resources: [LambdaPerm] |
| Serverless Framework | The CloudFormation template is invalid: Circular dependency between resources: [...] |
CDK (cdk synth or cdk deploy) | Error: 'StorageStack' depends on 'ComputeStack' (...). Adding this dependency (...) would create a cyclic reference. |
Nothing was created, nothing was billed, and nothing is stuck. That makes this one of the kinder CloudFormation errors. The stack never reaches ROLLBACK_COMPLETE, so there is nothing to delete before you try again. The whole job is editing the template.
Jake: "So it's like two people at a door, each saying 'after you'?"
Ethan: "Exactly that. And CloudFormation won't guess. It stands there until one of them stops saying it."
Read the list, then let cfn-lint find the loop
The names in the brackets are the resources CloudFormation found in the ring, and sometimes the ones hanging off it. With two or three names you can see the loop by eye. With eight, as in one widely read question about an Auto Scaling template ("[WebServerScaleDownPolicy, WebServerScaleUpPolicy, LaunchConfig, ElasticLoadBalancer, CPUAlarmHigh, MySecurityGroup, CPUAlarmLow, WebServerGroup]"), you cannot, and the person who asked had already tried the thing everyone tries first: "I tried adding DependsOn, but that doesn't help." It cannot help. DependsOn adds an arrow; the problem is too many arrows.
The fast way is cfn-lint, the free template checker from AWS. It runs on your machine, needs no AWS credentials, and its rule E3004 reports every resource in a loop together with the resource it loops through:
pip install cfn-lint
cfn-lint template.yaml
On the S3-to-Lambda template from the top of this page, version 1.57.2 printed this (file names and line numbers trimmed):
E3004 Circular Dependencies for resource UploadsBucket. Circular dependency with [InvokePermission]
E3004 Circular Dependencies for resource InvokePermission. Circular dependency with [ResizeFunction]
E3004 Circular Dependencies for resource ResizeRole. Circular dependency with [UploadsBucket]
E3004 Circular Dependencies for resource ResizeFunction. Circular dependency with [ResizeRole]
Read it as a chain: the bucket waits for the permission, the permission waits for the function, the function waits for the role, and the role waits for the bucket. That is the whole loop, in order, in one second, before any deploy. On Kali or any Linux with a managed Python, put cfn-lint in a virtual environment first (python3 -m venv .venv && source .venv/bin/activate) or install it with pipx; on Windows, pip install cfn-lint in a normal terminal works.
Once you can see the chain, pick the weakest arrow: the one reference you can replace with a value you are able to write down before anything exists. Names you choose yourself, ARNs you can assemble from the account ID and Region, and pseudo parameters like ${AWS::StackName} are all available before creation. Resource IDs that AWS generates (an instance ID, a generated bucket name, an API ID) are not. Every fix on this page is that one move, applied to a different shape.
The nine shapes of this error, and the fix for each
| Shape | The loop | The fix |
|---|---|---|
| S3 bucket triggers Lambda | bucket → permission → function → role → bucket | Compute the bucket name; strings for SourceArn and the policy; DependsOn on the bucket |
| Security group references itself or its twin | group → group | Separate SecurityGroupIngress resources |
| Lambda function and its log group | function → log group → function | Set FunctionName; build the log group name from it |
| API Gateway policy or a function that needs the API's ID | API → API, or API → function → API | execute-api:/* in the policy; read the API ID from the event at runtime |
| Cognito user pool trigger that needs the pool ID | pool → function → pool | Read userPoolId from the trigger event |
| OpenSearch domain policy that names its own ARN | domain → domain | Set DomainName; write the ARN as a string |
| EC2 instance role that names the instance | instance → profile → role → instance | Wildcard resource plus a stack-name tag condition |
| Two DependsOn attributes pointing at each other | A → B → A, explicitly | Delete one |
| CDK: two stacks that need each other | stack A exports to B, B exports to A | Import by name in one stack; attach the notification there |
S3 bucket triggering Lambda: the full loop and the template that works
This is the shape behind the most-read question on this error and behind the SAM and Serverless Framework versions too. Here is the natural way to write it, and it fails with the four E3004 lines shown above:
Resources:
UploadsBucket:
Type: AWS::S3::Bucket
DependsOn: InvokePermission
Properties:
NotificationConfiguration:
LambdaConfigurations:
- Event: s3:ObjectCreated:*
Function: !GetAtt ResizeFunction.Arn
InvokePermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref ResizeFunction
Principal: s3.amazonaws.com
SourceArn: !GetAtt UploadsBucket.Arn
ResizeRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement: [{Effect: Allow, Principal: {Service: lambda.amazonaws.com}, Action: sts:AssumeRole}]
Policies:
- PolicyName: read-uploads
PolicyDocument:
Version: '2012-10-17'
Statement: [{Effect: Allow, Action: s3:GetObject, Resource: !Sub '${UploadsBucket.Arn}/*'}]
ResizeFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.13
Handler: index.handler
Role: !GetAtt ResizeRole.Arn
Code: {ZipFile: "def handler(e, c):\n return 'ok'\n"}
Follow the arrows and you will see it. The bucket needs the function's ARN (and, through DependsOn, the permission). The permission needs the bucket's ARN for SourceArn. The role's policy needs the bucket's ARN too. The function needs the role. Role to bucket to permission to function to role: a ring. Two of those arrows point at the bucket, and both of them only want the bucket's name inside an ARN. The bucket's name is the thing you can decide in advance.
The version that passes cfn-lint and deploys:
Resources:
UploadsBucket:
Type: AWS::S3::Bucket
DependsOn: InvokePermission
Properties:
BucketName: !Sub 'uploads-${AWS::AccountId}-${AWS::Region}'
NotificationConfiguration:
LambdaConfigurations:
- Event: s3:ObjectCreated:*
Function: !GetAtt ResizeFunction.Arn
InvokePermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref ResizeFunction
Principal: s3.amazonaws.com
SourceAccount: !Ref AWS::AccountId
SourceArn: !Sub 'arn:${AWS::Partition}:s3:::uploads-${AWS::AccountId}-${AWS::Region}'
ResizeRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement: [{Effect: Allow, Principal: {Service: lambda.amazonaws.com}, Action: sts:AssumeRole}]
Policies:
- PolicyName: read-uploads
PolicyDocument:
Version: '2012-10-17'
Statement: [{Effect: Allow, Action: s3:GetObject, Resource: !Sub 'arn:${AWS::Partition}:s3:::uploads-${AWS::AccountId}-${AWS::Region}/*'}]
ResizeFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.13
Handler: index.handler
Role: !GetAtt ResizeRole.Arn
Code: {ZipFile: "def handler(e, c):\n return 'ok'\n"}
Four things changed, and each one matters:
- BucketName is computed, not generated.
uploads-${AWS::AccountId}-${AWS::Region}is unique across accounts and Regions without being hardcoded, which is the objection people raise to naming buckets. Bucket names must be globally unique, lowercase, 3 to 63 characters, so keep the prefix short and lowercase. If you need the same template twice in one account and Region, add${AWS::StackName}as well. - SourceArn and the policy are strings built from that name, not
!GetAtt UploadsBucket.Arn. The arrows that pointed at the bucket are gone. - DependsOn: InvokePermission stays on the bucket. This is the one place DependsOn is the cure rather than the cause. CloudFormation checks that S3 can invoke the function while it creates the bucket; without the permission in place first, the bucket fails with "Unable to validate the following destination configurations," which our S3-notification troubleshooting page covers in full. The DependsOn is safe now because nothing in the permission points back at the bucket.
- SourceAccount is set alongside SourceArn. cfn-lint flags its absence (W3663), and the reason is real: bucket names can be deleted by one owner and recreated by another, so the permission should name your account as well as the bucket.
You have two alternatives, and both are supported ways to do it. Create, then update: deploy the template without the NotificationConfiguration block and without DependsOn, let CloudFormation generate the bucket name, then add the notification block and update the stack. It works, it keeps generated names, and it means every fresh deploy is two steps, which rules it out for most pipelines. Put an SNS topic in the middle: the bucket publishes to a topic, the function subscribes to the topic, and the topic policy carries the bucket's name as a string; the person behind the most-read question on this error settled on that because they also needed the function to know another resource that depended on the bucket. The topic policy must exist before the bucket, so the bucket gets DependsOn on the policy.
If the bucket already exists and is not part of the stack, none of the above applies: a bucket resource cannot be declared twice. The way in is a small custom resource that calls PutBucketNotification on the existing bucket. One warning before you use it: it replaces any notification configuration the bucket already has.
Jake: "So you named the bucket yourself, and then everything else could be written down before it existed."
Ethan: "That's the whole trick. A name you choose is a fact. A name AWS makes up is a promise, and CloudFormation won't build on a promise that's waiting on another promise."
Security groups: the rule that references its own group
The simplest ring has one resource in it: a security group with an inbound rule that allows traffic from members of the same group. It is a common and sensible rule, "all the web servers may talk to each other on port 80," and written inline it is a loop:
WebSG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: web tier
VpcId: !Ref VpcId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
SourceSecurityGroupId: !Ref WebSG # the group needs its own ID before it exists
cfn-lint: E3004 Circular Dependencies for resource WebSG. Circular dependency with [WebSG]. The fix is to create the group first and add the rule afterward, as its own resource:
WebSG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: web tier
VpcId: !Ref VpcId
WebSelfRule:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: !Ref WebSG
IpProtocol: tcp
FromPort: 80
ToPort: 80
SourceSecurityGroupId: !Ref WebSG
Now the rule depends on the group, and nothing depends on the rule. The same move fixes the two-group version, an application tier and a database tier that each allow the other: two groups with no inline rules, then two SecurityGroupIngress resources, one per direction. The pair with inline rules fails on both groups; the four-resource version passes. One older answer suggests replacing the group reference with a CIDR block instead. That also removes the loop, but it widens the rule to every address in the subnet, so prefer the separate-resource fix. If security groups are new to you, our security groups guide explains what the group reference in a rule actually matches.
Lambda functions and their log groups
A newer shape, because it comes from a newer feature. Lambda's LoggingConfig lets you point a function at a log group you create yourself, which is how you set retention instead of keeping logs forever. The obvious template references in both directions:
FnLogs:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${Fn}' # needs the function's name
RetentionInDays: 14
Fn:
Type: AWS::Lambda::Function
Properties:
LoggingConfig: {LogGroup: !Ref FnLogs} # needs the log group's name
...
Each needs the other's name. Decide the function's name yourself and both sides can be written as strings:
FnLogs:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${AWS::StackName}-resize'
RetentionInDays: 14
Fn:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub '${AWS::StackName}-resize'
LoggingConfig: {LogGroup: !Ref FnLogs}
...
The log group keeps no reference to the function; the function still references the log group, which is the order you want (log group first). The cost of a fixed FunctionName is the usual one: some future changes to the function will need a replacement, and a replacement of a named resource can collide with itself. Keep the name derived from the stack name, as above, so two stacks never fight over it.
API Gateway: a policy that names its own API, and a function that needs the API's ID
Two different loops hide behind API Gateway. The first is a resource policy on a REST API that restricts who may call it, which needs the API's own ARN, which contains the API's ID, which does not exist until the API is created. Writing !GetAtt or !Ref to the API inside its own Policy property is the one-resource ring again. The documented fix is to leave the ID out: the policy's Resource is execute-api:/*, joined from the two strings "execute-api:/" and "*". API Gateway fills in the rest because the policy can only ever apply to the API it sits on. In the CDK the same line is Fn.join('', ['execute-api:/', '*']).
The second is a function that wants to know the API it serves: an environment variable such as API_GATEWAY: !Ref MyApi on a function that the API integrates with. The API needs the function's ARN for the integration, the function needs the API's ID for the variable, and in SAM the deployment and stage resources join the ring, which is why those messages list six or seven names. Three ways out, best first:
- Read it at runtime. Every request event already carries
requestContext.apiId,requestContext.domainNameandrequestContext.stage. A function that needs its own URL can build it from the event, and the environment variable disappears. - Use a custom domain name for the API, which you know in advance, and put that in the variable.
- Pass it after creation through an SSM parameter written by a separate resource, if the function truly needs it before the first request.
Cognito: a trigger function that needs the user pool ID
Same pattern, different service. A user pool declares its Lambda triggers (pre-sign-up, post-confirmation, custom message), so the pool depends on the function. The function wants COGNITO_USER_POOL_ID: !Ref UserPool in its environment to call the Cognito API, so the function depends on the pool. The way out is the same as for API Gateway: every Cognito trigger event includes userPoolId at the top level, so the handler reads it from the event and the environment variable goes. If the function also needs the pool outside of trigger invocations, write the pool ID to an SSM parameter from a second, smaller stack, or set the variable in a later stack update.
OpenSearch and Elasticsearch domains: an access policy with the domain's own ARN
A domain's AccessPolicies statement usually names the domain ARN as its Resource, and !GetAtt Domain.Arn inside the domain's own properties is a self-loop. Give the domain a name and write the ARN as a string instead:
SearchDomain:
Type: AWS::OpenSearchService::Domain
Properties:
DomainName: !Sub '${AWS::StackName}-search'
AccessPolicies:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal: {AWS: !GetAtt AppRole.Arn}
Action: es:ESHttp*
Resource: !Sub 'arn:${AWS::Partition}:es:${AWS::Region}:${AWS::AccountId}:domain/${AWS::StackName}-search/*'
The domain name has its own rules (lowercase, 3 to 28 characters, starts with a letter), so keep the stack name short if you derive from it.
EC2: an instance role that names the instance, or an instance that tags itself
Two classics from the same family. An instance that wants a tag containing its own instance ID (Value: !Ref myInstance in its own Tags) is a one-resource loop, and the message is Circular dependency between resources: [myInstance]. The three-resource version is subtler: a role whose policy allows ec2:CreateTags only on instance/${Server}, an instance profile that references the role, and an instance that references the profile. The instance needs the profile, the profile needs the role, the role needs the instance's ID. cfn-lint lists all three.
Instance IDs are the purest example of a value you cannot know in advance, so the fix is to stop naming it and scope the permission another way. CloudFormation tags every EC2 instance it creates with aws:cloudformation:stack-name, so a condition on that tag scopes the permission to this stack's instances without knowing their IDs:
Policies:
- PolicyName: tag-self
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: ec2:CreateTags
Resource: !Sub 'arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:instance/*'
Condition:
StringEquals:
aws:ResourceTag/aws:cloudformation:stack-name: !Ref AWS::StackName
For the self-tagging instance, do the tagging from inside the instance: a few lines of user data that read the instance ID from the instance metadata service and call aws ec2 create-tags, using the role above. The template never has to mention the ID.
Two DependsOn attributes that point at each other
The explicit version is rare in hand-written templates and common in generated or merged ones: a queue with DependsOn: Topic and a topic with DependsOn: Queue, left behind after someone removed the references that once justified them. cfn-lint reports both resources; delete the DependsOn that no longer has a reason. A good habit when you remove a !Ref between two resources is to look for a DependsOn going the other way, because the Ref was holding it in check.
DependsOn still has real jobs, and knowing them keeps you from deleting the wrong one. CloudFormation requires it where a dependency exists but no value flows: an EC2 instance with a public IP, a load balancer, an Elastic IP, an RDS instance or an internet route all depend on the VPC's gateway attachment when the VPC and gateway are in the same template, and nothing in their properties references the attachment, so you declare it. Wait conditions and anything that must be deleted in a fixed order are the other cases. A DependsOn that names a resource you also reference with Ref or GetAtt is redundant, and a DependsOn that points the other way is the loop.
SAM and the Serverless Framework: the same loop under a transform
Both tools generate CloudFormation, so the error is identical, but the loop is harder to see because resources you never wrote are in it. In SAM, an Events entry of type S3 on a function generates the bucket notification and the Lambda permission, and Policies: - S3ReadPolicy: {BucketName: !Ref Bucket} generates the role policy. SAM requires the bucket to be declared in the same template for an S3 event, and if the policy and the permission both reference the bucket resource, you have the ring from the S3 section with generated names. The fix is the same: set BucketName: !Sub 'blobs-${AWS::AccountId}-${AWS::Region}' on the bucket, and give S3ReadPolicy the same string rather than a Ref. Messages that list a single [LambdaPerm] are this case, the permission being the resource that closes the loop.
In the Serverless Framework, the loop usually appears when iamRoleStatements builds a bucket ARN with Ref to a bucket that an s3 event on a function also creates. Build the ARN from the bucket name string instead (arn:aws:s3:::my-bucket-${self:provider.stage}/*), or attach the event to an existing bucket with the framework's existing: true option, which uses a custom resource rather than the bucket's own notification property.
CDK: "would create a cyclic reference" between two stacks
The CDK catches loops before CloudFormation does, at cdk synth, and the wording is different: "would create a cyclic reference." Within one stack the CDK rarely produces a loop, because its constructs already apply the fixes above (the S3 notification, for instance, is a custom resource in the CDK, not the bucket's property). The cycle appears when you split resources across stacks. The two-stack test behind this page: a StorageStack with a bucket, a ComputeStack with a resize function, and in the storage stack bucket.addEventNotification(..., new LambdaDestination(fn)) plus bucket.grantRead(fn). Synthesis failed with:
Error: 'StorageStack' depends on 'ComputeStack' (StorageStack -> ComputeStack/Resize/Resource.Arn).
Adding this dependency (ComputeStack -> StorageStack/Uploads/Resource.Arn) would create a cyclic reference.
The message gives you the complete diagnosis. The notification in StorageStack needs the function's ARN from ComputeStack; the grant in ComputeStack needs the bucket's ARN from StorageStack. Across stacks, each of those becomes an export and an import, and two stacks cannot import from each other.
The fix that synthesized cleanly: in the compute stack, refer to the bucket by name instead of by object, and attach both the grant and the notification to that reference.
// StorageStack
const bucket = new s3.Bucket(storage, "Uploads");
// ComputeStack
const uploads = s3.Bucket.fromBucketName(compute, "UploadsRef", bucket.bucketName);
uploads.grantRead(fn);
uploads.addEventNotification(s3.EventType.OBJECT_CREATED, new n.LambdaDestination(fn));
After the change, the storage stack exports only the bucket name, and the compute stack holds the function, its role and policy, the Lambda permission and the Custom::S3BucketNotifications resource that writes the notification onto the bucket. All the arrows run one way, storage to compute. The general rule for CDK cycles: decide which stack is upstream, and in the downstream stack import upstream resources by name or ARN (fromBucketName, fromFunctionArn, fromSecurityGroupId, fromTableName) rather than passing the construct object, whenever the downstream stack would otherwise write something back onto the upstream resource.
Other CDK shapes with the same message and the same remedy: a Fargate task definition in one stack whose container logging references a log group in another; an ECS service in one stack registered with a target group from an ALB stack, which then needs the service's security group; a secret with its own KMS key in one stack granted to a role in another. In each case the error names the two stacks and the two references, and one of the two sides can usually be rewritten as an import by name. When the resource truly needs values from both directions, move it into one of the two stacks. If you are seeing the CDK error after a bootstrap or SSM problem instead, that is a different failure; our CDK bootstrap guide covers it.
Jake: "Why does the CDK get this and plain CloudFormation doesn't?"
Ethan: "Plain CloudFormation gets it too, it just waits until you hand in the template. The CDK reads your plan before you leave the house. Same loop, earlier warning."
Nested stacks and the CloudFormation side of cross-stack loops
Nested stacks can put you in the CDK situation without the CDK: a parent passes a value into a nested stack as a parameter, the nested stack returns an output, and if the parent then feeds that output into the resource it passed in, the parent's nested-stack resource depends on itself. A long list of names with SSM and IdentityPool entries in it, from a Cognito template, is a typical sign. Break it the same way: pass strings the nested stack can use without the resource existing (names you compute, ARNs you assemble), or move the resource that needs both sides into the nested stack.
The ten-minute fix order
- Run
cfn-lint template.yamland read the E3004 lines as a chain. For the CDK, read the two references in the synth error. - Find the one reference in the chain that only needs a name (bucket name, function name, domain name, stack name). That is the arrow to cut.
- Set that name yourself from pseudo parameters:
${AWS::StackName},${AWS::AccountId},${AWS::Region}. - Rewrite every reference that pointed at that resource as a string built from the name. Check for a DependsOn that now has no reason, and remove it; check for a permission the resource needs at creation time (S3 notifications), and keep that DependsOn.
- Run cfn-lint again. Zero E3004 lines means CloudFormation will accept the ordering.
- Deploy. Because the original attempt created nothing, there is no failed stack to delete first.
Fixes by symptom
| What you see | What it is | Fix |
|---|---|---|
| One name in the brackets | A resource references itself (security group rule, instance tag, API policy, domain policy) | Move the rule out, or replace the self-reference with a string or wildcard |
| Bucket, permission, function, role | S3 notification ring | Compute the bucket name; strings for SourceArn and policy; DependsOn on the bucket |
Only [LambdaPerm] or one permission name | SAM S3 event with a Ref'd bucket | BucketName with pseudo parameters; S3ReadPolicy with the same string |
| API, function, deployment, stage names together | Function environment variable holds the API ID | Read apiId from the event; or a custom domain |
| User pool and a function | Trigger function has the pool ID in its environment | Read userPoolId from the event |
| Function and log group | LoggingConfig and LogGroupName reference each other | Set FunctionName; derive the log group name |
| Eight or more names, autoscaling template | One loop pulling in everything attached to it | cfn-lint to find the actual pair; usually a security group or a DependsOn |
| "would create a cyclic reference" | CDK cross-stack loop | Import by name in the downstream stack; attach there |
| Loop appears only after adding DependsOn | DependsOn points against an existing Ref | Remove the DependsOn; the Ref already orders them |
Frequently asked questions about CloudFormation circular dependencies
What does "circular dependency between resources" mean in CloudFormation?
The resources listed reference each other in a ring through Ref, GetAtt, Sub or DependsOn, so CloudFormation cannot pick one to create first. It rejects the template before creating anything; nothing is left behind in your account.
How do I find which resources cause the circular dependency?
Run cfn-lint on the template. Rule E3004 prints one line per resource in the loop with the resource it depends on, which reads as a chain. For CDK apps, the synth error names the two stacks and the two references.
How do I fix a circular dependency between an S3 bucket and a Lambda function?
Set BucketName with pseudo parameters, write the Lambda permission's SourceArn and the role policy as strings built from that name instead of GetAtt, and keep DependsOn on the bucket pointing at the permission, because S3 checks the permission when the bucket is created.
Why does the S3 bucket depend on the Lambda permission?
When CloudFormation creates a bucket with a notification configuration, it verifies that S3 is allowed to invoke the target function. If the AWS::Lambda::Permission does not exist yet, bucket creation fails with "Unable to validate the following destination configurations."
Does adding DependsOn fix a circular dependency?
No. DependsOn adds an ordering arrow; a loop is already too many arrows. The fix removes a reference by replacing it with a value you can write down, such as a computed name. The one exception is the S3 bucket, which needs DependsOn on the permission after the references are gone.
How do I make a security group rule that allows traffic from the same group?
Declare the group without inline rules, then add an AWS::EC2::SecurityGroupIngress resource with GroupId and SourceSecurityGroupId both set to the group. The rule depends on the group and nothing depends on the rule.
How do I avoid hardcoding a bucket name when fixing the loop?
Compute it from pseudo parameters: !Sub 'uploads-${AWS::AccountId}-${AWS::Region}' is unique across accounts and Regions, and adding ${AWS::StackName} makes it unique per stack. Bucket names must be lowercase and 3 to 63 characters.
What does "would create a cyclic reference" mean in the CDK?
Two stacks would each export a value the other imports, which CloudFormation cannot order. The error names both stacks and both references. Import the upstream resource by name or ARN in the downstream stack and attach grants or notifications there.
How do I fix a CDK cyclic reference for an S3 notification across stacks?
In the stack with the function, call s3.Bucket.fromBucketName with the bucket's name and use that reference for grantRead and addEventNotification. The notification custom resource and the permission then live in the function's stack, and only the bucket name crosses between stacks.
How do I reference an API Gateway's own ARN in its resource policy?
Leave the API ID out: set the policy's Resource to execute-api:/* (Fn::Join of "execute-api:/" and "*"). API Gateway completes the ARN because the policy can only apply to the API it is attached to.
How can a Lambda function know its API Gateway ID without a circular dependency?
Read it from the request event: requestContext.apiId, requestContext.domainName and requestContext.stage are present on every invocation. A custom domain name set in advance also works. Avoid an environment variable that references the API.
How do I pass the Cognito user pool ID to a trigger Lambda?
Trigger events include userPoolId at the top level, so read it from the event. A Ref to the pool in the function's environment creates a loop because the pool references the function as a trigger.
Why does my Lambda log group cause a circular dependency?
LoggingConfig on the function references the log group, and LogGroupName /aws/lambda/${Fn} references the function. Set FunctionName from the stack name and build the log group name from the same string.
How do I tag an EC2 instance with its own instance ID in CloudFormation?
You cannot reference the instance inside its own properties. Tag it from user data: read the ID from instance metadata and call aws ec2 create-tags, with a role allowing CreateTags on instances tagged aws:cloudformation:stack-name equal to your stack.
Does the SAM circular dependency error have a different fix?
No. SAM generates the same bucket notification, permission and policy. Set BucketName on the bucket with pseudo parameters and pass the same string to S3ReadPolicy instead of a Ref. The error usually lists only the generated permission, such as [LambdaPerm].
Can I fix the loop by creating the stack in two steps?
Yes. Deploy without the NotificationConfiguration and without DependsOn so the bucket name is generated, then add the notification and update the stack. It works but turns every fresh deploy into two steps, so most pipelines prefer the computed-name fix.
Does aws cloudformation validate-template catch circular dependencies?
Rely on cfn-lint for that check; it runs offline, needs no credentials, and reports the loop with rule E3004 before any create or change-set call reaches AWS.
Is anything created or billed when the circular dependency error appears?
No. The template is rejected before any resource is created, so there is no stack to delete and no rollback. Fix the template and deploy again.
For readers preparing for an AWS certification
We have been covering AWS certifications alongside our fixes, so here is a short extra for readers studying for one. If you only came for the fix, you already have it; feel free to skip this part.
Exams that test this topic: Developer – Associate (DVA-C03 from December 1, 2026) • DevOps Engineer – Professional (DOP-C02) • CloudOps Engineer – Associate (SOA-C03).
Here are the exam-style questions this topic tends to raise, with the reasoning you need to answer them:
1. How do you catch template errors before deploying?
Run cfn-lint or validate-template, then review a change set.
2. How do you preview what an update will change in a production stack?
Create a change set and review it before you run it.
3. How do two stacks share a value such as a VPC ID?
An output with an Export in one stack and Fn::ImportValue in the other, or an SSM parameter.
4. A database must survive if its stack is deleted. What do you set?
DeletionPolicy: Retain or Snapshot on the resource.
5. Certain resources must never be replaced by a stack update. What protects them?
A stack policy that denies updates to those resources.
6. The same stack must be deployed to many accounts and Regions. What do you use?
CloudFormation StackSets.
Exam codes and dates change often. Our AWS certification changes page keeps track of what is current.
Ethan's fix was three lines: a bucket name built from the account and Region, two ARNs written as strings, and the DependsOn he had been about to delete left exactly where it was. The stack came up in under a minute, and the first broken-screen photo Jake uploaded came back resized before he had put his phone down. "So the answer to 'who goes first,'" Jake said, "was to tell them the name of the door." Ethan thought that was close enough.
📌 If you keep one line from this page
A circular dependency is a ring of references, and you break it by replacing one reference with a value you can write down before anything exists: a name built from the stack, account or Region, never another DependsOn.
cfn-lint E3004 finds the ring · S3 buckets: computed name + string ARNs + DependsOn on the permission · security groups: separate ingress resources · CDK: import by name downstream.
Revision note. Written October 16, 2026, with every template checked by cfn-lint and the CDK case synthesized in a two-stack app. "A chain is only as strong as its weakest link," the old saying goes; here the weakest link is the one you want, and you cut it on purpose.