Terraform - pre and post conditions

The latest version of Terraform 1.2 introduces a nice feature around check conditions. Previously we’re having the option to validate variables, but it was static validation. Preconditions and Postconditions introduce a dynamic validation option because at the static level you cannot figure out if the selected resource argument is valid you should check it (pre) before applying or checking the return attribute is expected (post). Let’s jump to the example:

variable "aws_subnet_id" {
  type    = string
  default = "subnet-0ccd2f1ba5c6fcac5"
}

data "aws_subnet" "default" {
  id = var.aws_subnet_id
}

resource "aws_network_interface" "default" {
  subnet_id = var.aws_subnet_id
  lifecycle {
    precondition {
      condition     = data.aws_subnet.default.map_public_ip_on_launch
      error_message = "Selected subnet ${var.aws_subnet_id} is not public"
    }
  }
}

resource "aws_instance" "default" {
  ami           = "ami-02ddaf75821f25213"
  instance_type = "t4g.micro"

  network_interface {
    network_interface_id = aws_network_interface.default.id
    device_index         = 0
  }
}

data "aws_ebs_volume" "default" {
  filter {
    name   = "volume-id"
    values = [aws_instance.default.root_block_device[0].volume_id]
  }

  lifecycle {
    postcondition {
      condition     = self.size > 10
      error_message = "Instance EBS root volume size ${self.size}GB < 10GB"
    }
  }
}

right before (pre) creating aws_network_interface we can check whether the selected subnet is “public”, we have precondition option at resource aws_network_interface if not terraform apply will stop. The postconditions check is being fired right after creating EC2 instance because after that we will know the size of the root volume (depends of AMI), and once again terraform will fail if the condition is not met. I notice one disadvantage of this approach when you’re trying to destroy the infrastructure with the unmet conditions it will fail due to … unmet conditions. It could be painful when you create a dynamic infrastructure from users' parameters and when those parameters are wrong you should manually fix them to clean things up. Nevertheless, nice approach which can be additionally connected with tflint checks.

comments powered by Disqus

powered by Hugo and Noteworthy theme