Anthony Kong
Anthony Kong

Reputation: 40844

'At least one field is expected inside environment' error in terraform

When I tried to apply a terraform in order to create a lambda function, I got this error:

 Error: At least one field is expected inside environment

Here is my terraform module:

resource "aws_lambda_function" "lambda" {
  function_name = var.lambda_filename
  description = var.description
  runtime = "python3.6"
  environment {
    variables = var.variables
  }
}

This error is thrown when var.variables is set to null.

How can I fix it?

I am using terraform 0.12.6 and aws provider 2.25.0

Upvotes: 6

Views: 4001

Answers (2)

smyndlo
smyndlo

Reputation: 1

Adding to the solution above, also remember to set the default value for your variable to null. Eg.

variable variables {
  type    = map
  default = null
  description = "My map" 
}

Upvotes: 0

Anthony Kong
Anthony Kong

Reputation: 40844

I find a solution: Use dynamic in the latest version of terrafrom

resource "aws_lambda_function" "lambda" {
  function_name = var.lambda_filename
  description = var.description
  runtime = "python3.6"

  dynamic "environment" {
    for_each = local.environment_map
    content {
      variables = environment.value
    }
  }
}

The environment_map is created this way:

locals {
  environment_map = var.variables == null ? [] : [var.variables]
}

Upvotes: 12

Related Questions