Terraform Resource Creation Order guide with Nested Modules and Data Sources
I'm trying to debug I've encountered a strange issue with I'm working with a question with resource creation order when using nested modules in Terraform. I have a root module that calls a networking module to create VPC and subnets, and then a separate module for EC2 instances that relies on the subnets created in the networking module. The scenario arises because I'm trying to reference an output from the networking module (the subnet IDs), but Terraform applies the EC2 module before the networking module has completed its execution. Hereโs a simplified version of my Terraform configuration: In the root module `main.tf`: ```hcl module "networking" { source = "./modules/networking" } module "ec2" { source = "./modules/ec2" subnet_ids = module.networking.subnet_ids } ``` In the networking module `modules/networking/main.tf`: ```hcl resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" } resource "aws_subnet" "subnet" { count = 3 vpc_id = aws_vpc.main.id cidr_block = "10.0.${count.index}.0/24" } output "subnet_ids" { value = aws_subnet.subnet[*].id } ``` And in the EC2 module `modules/ec2/main.tf`: ```hcl resource "aws_instance" "web" { count = length(var.subnet_ids) ami = "ami-12345678" instance_type = "t2.micro" subnet_id = var.subnet_ids[count.index] } ``` When I run `terraform apply`, I get the behavior message: ``` behavior: Dependency cycle: aws_instance.web The dependency graph has cycles, with the following paths: aws_instance.web -> module.networking.aws_subnet.subnet module.networking.aws_subnet.subnet -> aws_instance.web ``` I've tried using `depends_on` in the EC2 module, but that doesnโt seem to resolve the dependency order scenario. Iโve also explored breaking out the EC2 instances into a separate `terraform apply` step, but that complicates my deployment process. How can I ensure that the networking module finishes creating the VPC and subnets before the EC2 instances are created without running into dependency cycles? Any suggestions or best practices would be highly appreciated! I've been using Hcl for about a year now. Any advice would be much appreciated. For context: I'm using Hcl on Ubuntu 22.04.