Home > Software design >  Setting a resource block parameter based on a boolean
Setting a resource block parameter based on a boolean

Time:07-28

I am trying to create a Terraform project for Aurora PostgreSQL and would like to have a variable defined whether it's serverless or not, if possible at all. For example:

  1. variables.tf:

    variable "serverless" {type = bool}

  2. terraform.tfvars:

    serveless = "true"

  3. main.tf (pseudo code):

    resource "aws_rds_cluster" "db_cluster" {
    ...
    
    if var.serveless == true ? 
        serverlessv2_scaling_configuration {
          max_capacity = 16
          min_capacity = 0.5
        }
    : []
    
    

If the variable is true - set the serverless code, otherwise - don't include it at all.

CodePudding user response:

It is probably a good candidate to use for_each [1] and dynamic [2] block combined. In that case, you would have something like:

resource "aws_rds_cluster" "example" {
  # ... other configuration ...

  dynamic "serverlessv2_scaling_configuration" {
    for_each = var.serveless ? [1] : []
    content {
      max_capacity = var.max_capacity
      min_capacity = var.min_capacity
    }
  }
}

Take care also about the note for Aurora Severless:

serverlessv2_scaling_configuration configuration is only valid when engine_mode is set to provisioned

So you might also want to use the ternary expression in that case.


[1] https://www.terraform.io/language/meta-arguments/for_each

[2] https://www.terraform.io/language/expressions/dynamic-blocks

  • Related