Bootstrap FreeKB - Terraform - Using count to do something based on whether a condition evaluates to true or false
Terraform - Using count to do something based on whether a condition evaluates to true or false

Updated:   |  Terraform articles

count can be used to:

Let's say you have the following files on your Terraform server.

├── locals.tf
├── modules.tf
├── outputs.tf
├── provider.tf
├── terraform.tfstate
├── variables.tf
├── child (directory, child module)
│   ├── data.tf
│   ├── outputs.tf
│   ├── resources.tf

 

 


Evaluating a boolean

Let's say variable my-boolean in variables.tf contains a default value of true.

variable "my-boolean" {
  type = bool
  default = true
}

 

And let's say resources.tf uses the aws_vpc resource. In this scenario, the count expression will be true (1) and the Amazon Web Services (AWS) Virtual Private Cloud (VPC) will be created.

resource "aws_vpc" "my-vpc" {
  count = var.my-boolean ? 1 : 0
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "my-vpc"
  }
}

 

On the other hand, in this example, the count expression will be false (0) and the Amazon Web Services (AWS) Virtual Private Cloud (VPC) will NOT be created.

resource "aws_vpc" "my-vpc" {
  count = var.my-boolean ? 1 : 0
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "my-vpc"
  }
}

 


Evaluating a string

In this example, variable my-string contains a default value of "Hello".

variable "my-string" {
  type = string
  default = "Hello"
}

 

In this scenario, the count expression will be true (1) and the Amazon Web Services (AWS) Virtual Private Cloud (VPC) will be created.

resource "aws_vpc" "my-vpc" {
  count = var.my-string == "Hello" ? 1 : 0
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "my-vpc"
  }
}

 

On the other hand, in this example, the count expression will be false (0) and the Amazon Web Services (AWS) Virtual Private Cloud (VPC) will NOT be created.

resource "aws_vpc" "my-vpc" {
  count = var.my-string == "World" ? 1 : 0
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "my-vpc"
  }
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 139f91 in the box below so that we can be sure you are a human.