Menu
blog.headdesk.me
blog.headdesk.me

Terraform and time_sleep

Posted on 2024/11/132024/11/13

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!

Loading

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Full text search

Recent Posts

  • Generate secure password
  • AWS Compute Savings Plans
  • AWS Zonal Shift
  • Coffee break…
  • Prevent private key from being committed to git
  • aws (14)
  • coffee (2)
  • headfi (1)
  • linux (9)
  • others (61)
  • security (2)
  • tech (41)
  • terraform (3)
  • wordpress (2)

Loading

apache aws awscli azure backup boot cloud coffee docker ec2 EL8 ElasticBeanstalk espresso featured git kernel lelit linux lvm meltdown MFA nat gateway php power proliant python rdp Redhat RHEL rpm Ryzen scp security smartarray smart switch snapshot spectre tech terraform ubuntu ubuntu upgrade vpn windows wordpress workspace

©2026 blog.headdesk.me | Powered by SuperbThemes