2
votes

Earlier today I was looking at https://github.com/terraform-aws-modules/terraform-aws-vpc/blob/v2.77.0/main.tf to look deeper into how the VPC module for AWS works behind the scenes.

One thing that I am struggling with is the count conditional such as the one in the aws_internet_gateway resource.

Can someone explain and translate what the count defined in this resource is actually doing? It's very confusing to me at the moment.

resource "aws_internet_gateway" "this" {
  count = var.create_vpc && var.create_igw && length(var.public_subnets) > 0 ? 1 : 0

  vpc_id = local.vpc_id

  tags = merge(
    {
      "Name" = format("%s", var.name)
    },
    var.tags,
    var.igw_tags,
  )
}
1
How did it go with the conditions? Is it more clear now?Marcin

1 Answers

3
votes

It uses ternary operation in the general form of:

CONDITION ? TRUEVAL : FALSEVAL

In the module, the

CONDITION is var.create_vpc && var.create_igw && length(var.public_subnets) > 0

TRUEVAL is 1

FALSEVAL is 0

This translates to the following: If both create_vpc and create_igw are true as well as public_subnets has been defined, then count will be 1 (TRUEVAL) and exactly one aws_internet_gateway.this will be created.

In contrast if the CONDITION is not satisfied, count will be 0 (FALSEVAL) and no aws_internet_gateway.this will be created.

In general, it is a common pattern to conditionally create resources in terraform:

resource "type" "name" {

  count = CONDITION : 1 ? 0

}