简体   繁体   中英

Terraform Conditionals in AWS Module

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,
  )
}

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM