Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Terraform count using bool?

count is a great meta-argument for being able to provision resources conditionally in Terraform. From my previous experience, we do something like my_var = "1" and use this to programmatically control resource creation with count.

Since count in that case takes in a string "1", but can also interpret a number type (e.g. 1), I’m wondering:

a) What is Terraform’s count doing under the hood; is it parsing the string as a number first?
b) Can it also accept other data types e.g. bool?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m hoping to have a .tfvars which has a my_var = true in it, which is then passed into the count meta-argument on affected resources e.g count = var.my_var. Is this possible?


I also kindly request some information which goes into generally how data types are interpreted in Terraform for "truthiness". If you have docs or a blog post to share it’d be much appreciated!

>Solution :

a). In Terraform string representation of numeric values are automatically converted to numbers. From the docs:

Terraform automatically converts number and bool values to strings when needed. It also converts strings to numbers or bools, as long as the string contains a valid representation of a number or bool value.

  • true converts to "true", and vice-versa
  • false converts to "false", and vice-versa
  • 15 converts to "15", and vice-versa

This is valid:

resource "aws_s3_bucket" "s3" {
  bucket = "bucket-name"
  count = "1"
}

This is also valid:

resource "aws_s3_bucket" "s3" {
  bucket = "bucket-name"
  count = 1
}

b). In Terraform booleans are not considered to be numeric values. Numbers are not automatically converted to booleans, which means this is NOT valid:

resource "aws_s3_bucket" "s3" {
  bucket = "asd"
  count = false
}

It will throw the following error:

╷
│ Error: Incorrect value type
│
│   on main.tf line 9, in resource "aws_s3_bucket" "s3":
│    9:   count = false
│
│ Invalid expression value: number required.
╵
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading