HiveBrain v1.2.0
Get Started
← Back to all entries
patternterraformMinor

Terraform conditional block inside a map

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
mapblockconditionalterraforminside

Problem

I have an aws_lambda_function resource like below:

resource "aws_lambda_function" "mylambda" {

    #...
    
    environment {
        variables = {
            FOO = 1
        }
    }

}


I'm tring to add some environment variables dynamically based on my var.enable_vars

variable "enable_vars" {
  type        = bool
  default     = false
}

resource "aws_lambda_function" "mylambda" {

    #...
    
    environment {
        variables = {
            FOO = 1
    #### if var.enable_vars == true
    #       BAR = 2
    #       BAZ = 3
        }
    }

}


How to achieve that? Is not clear to me if a dynamic block can be used there.

Solution

This could be done with a dynamic block but its pretty complicated. This is how I would do it but there are other ways.

variable "enable_vars" {
  type        = bool
  default     = false
}

locals {
  default_lambda_vars = {
    FOO = 1
  }
  extra_vars = {
    BAR = 2
    BAZ = 3
  }

  final_lambda_vars = var.enable_vars ? merge(local.default_lambda_vars, local.extra_vars) : local.default_lambda_vars
}

resource "aws_lambda_function" "mylambda" {

    #...

    environment {
        variables = local.final_lambda_vars
    }

}

Code Snippets

variable "enable_vars" {
  type        = bool
  default     = false
}

locals {
  default_lambda_vars = {
    FOO = 1
  }
  extra_vars = {
    BAR = 2
    BAZ = 3
  }

  final_lambda_vars = var.enable_vars ? merge(local.default_lambda_vars, local.extra_vars) : local.default_lambda_vars
}


resource "aws_lambda_function" "mylambda" {

    #...

    environment {
        variables = local.final_lambda_vars
    }

}

Context

StackExchange DevOps Q#16751, answer score: 3

Revisions (0)

No revisions yet.