Evan Gertis
Evan Gertis

Reputation: 2052

How to use a condition count statement in Terraform

Given a module like so

module us-west-2 {
    count          = "${local.environments[terraform.workspace] ==  "logging" ? true : false}"
    source = "./modules/flow_log"
    providers = {
        aws = aws.us-west-2
    }
    log_destination = module.nf_cis_benchmark.aws_s3_bucket_vpc_flow_log
    log_destination_type = "s3"
    traffic_type = "REJECT"
    depends_on = [ module.nf_cis_benchmark.raws_s3_bucket_vpc_flow_log_arn ]
    aws_vpc_ids = data.aws_vpcs.us-west-2.ids
}

How can we conditionally create this module based on the return value from local.environments[terraform.workspace]?

Expected: When the user runs terraform apply the resources are conditionally created based on the selected workspace.

Actual:

330:     count          = length("${local.environments[terraform.workspace] ==  "logging" ? true : false}")
│     ├────────────────
│     │ local.environments is object with 9 attributes
│     │ terraform.workspace is "nf-logging"
│ 
│ Call to function "length" failed: argument must be a string, a collection type, or a structural type.

Upvotes: 0

Views: 11472

Answers (2)

Mark B
Mark B

Reputation: 200486

Your error message has a length() call, but your posted code does not. Please post the actual code that is generating the error when you post a question like this.


I have no idea why you are trying to wrap the count expression in double quotes, or why you are trying to return true or false, and then take the string length of those strings to create a count value. Are you using a really old version of Terraform? I think what you are attempting to do would actually look like this, if you are using Terraform 0.12 or later:

count = local.environments[terraform.workspace] == "logging" ? 1 : 0

Upvotes: 5

Matthew Schuchard
Matthew Schuchard

Reputation: 28739

There are several issues with the count meta-argument in the question, including the use of it originally, but to answer the question's intent, you could could conditionally manage a module like:

module "us-west-2" {
  for_each = local.environments[terraform.workspace] == "logging" ? toset(["this"]) : []
  ...
}

which will manage one declaration of the module (consequentially from the size one list iterated) when the local equals the string logging, and zero declarations (from the size zero list iterated) otherwise.

Upvotes: 2

Related Questions