0
0
TerraformHow-ToBeginner · 3 min read

How to Use Bool Variable in Terraform: Simple Guide

In Terraform, you declare a boolean variable using variable block with type = bool. You can then use this variable in your configuration to control resource behavior with true or false values.
📐

Syntax

To declare a boolean variable in Terraform, use the variable block with type = bool. You can also set a default value as true or false. This tells Terraform to expect a true or false value for this variable.

terraform
variable "example_flag" {
  type    = bool
  default = false
}
💻

Example

This example shows how to declare a boolean variable and use it to conditionally create a resource. If the variable is true, the resource is created; if false, it is skipped.

terraform
variable "create_bucket" {
  type    = bool
  default = true
}

resource "aws_s3_bucket" "example" {
  count  = var.create_bucket ? 1 : 0
  bucket = "my-example-bucket"
  acl    = "private"
}
Output
Terraform will create the S3 bucket if create_bucket is true; otherwise, it creates no bucket.
⚠️

Common Pitfalls

Common mistakes include not specifying type = bool which makes Terraform treat the variable as string, causing errors. Another is using strings like "true" or "false" instead of boolean values true or false. Also, forgetting to handle the variable in resource conditions can lead to unexpected resource creation.

terraform
variable "wrong_flag" {
  default = "true"  # Incorrect: string instead of bool
}

variable "correct_flag" {
  type    = bool
  default = true
}
📊

Quick Reference

ConceptExampleNotes
Declare bool variablevariable "flag" { type = bool }Defines a boolean variable
Set defaultdefault = trueOptional default value
Use in conditioncount = var.flag ? 1 : 0Create resource if true
Avoid string valuesdefault = "true" (wrong)Use true without quotes

Key Takeaways

Always declare boolean variables with type = bool for correct behavior.
Use boolean variables to control resource creation with conditional expressions.
Avoid using strings like "true" or "false"; use true or false without quotes.
Set default values to simplify usage and avoid errors.
Test your boolean logic to ensure resources behave as expected.