3

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.

3
  • You could set the environment variables in the code itself from a file conditionally based on one variable set during the build time
    – jabbson
    Commented Oct 19, 2022 at 16:26
  • @jabbson can you add more details?
    – sgargel
    Commented Oct 19, 2022 at 18:57
  • you could have your environment variables stored in the .env files, uploaded along with the code and then loaded during execution. Also you could use ternary operator, if setting BAR = 0 or -1 could mean the same as not being set within your app logic.
    – jabbson
    Commented Oct 19, 2022 at 21:11

1 Answer 1

3

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
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.