Terraform conditional block inside a map



  • I have an https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/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.



  • 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
    }
    

    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2