Sometimes it takes a while to provision resource A, and resource B can only be deployed after. Here I’ll demonstrate how to use time_sleep to set up the wait and dependency.
In this example, I am working on a VPC module. The module can optionally create additional CIDR association, which takes time for AWS to provision. A wait need to be introduced before creating subnets.
Normally this can be done with a simple depends_on. But in this case, the additional CIDR resource is optional. Also, even when aws_vpc_ipv4_cidr_block_association is “completed”, it actually takes a little more time before the additional CIDR can be used. We need to introduce a wait.
The following creates a 10 second sleep if additional CIDR association is requested:
# Additional CIDR association resource
resource "aws_vpc_ipv4_cidr_block_association" "additional_cidr" {
for_each = toset(var.secondary_cidr_blocks)
vpc_id = aws_vpc.vpc.id
cidr_block = each.value
}
# Optionally wait for additional cidr association
resource "time_sleep" "wait-10s" {
depends_on = [aws_vpc_ipv4_cidr_block_association.additional_cidr]
count = length(var.secondary_cidr_blocks)
create_duration = "10s"
triggers = {
slept = length(aws_vpc_ipv4_cidr_block_association.additional_cidr)
}
}
Then my subnets will need to wait if additional CIDR is requested. This is done by setting a dummy tag with value coming from the time_sleep’s triggers.
resource "aws_subnet" "private-subnets" {
count = length(var.private-subnet-cidrs)
vpc_id = aws_vpc.vpc.id
availability_zone = element(data.aws_availability_zones.available-az.names, count.index % 2)
cidr_block = var.private-subnet-cidrs[count.index]
tags = {
Name = "${var.resource-prefix}-private-${split("-", element(data.aws_availability_zones.available-az.names, count.index))[2]}-${count.index + 1}"
TfInternal = try(time_sleep.wait-10s[0].triggers.slept, "na")
}
}
Yes, my subnets will then have an unnecessary TfInternal tag. If you know a better way, please share!
![]()