Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform 0.11: conditional vpc_config in aws_lambda_function

I am trying to deploy a Lambda function with a conditional on the vpc_config block. I have tried using count inside vpc_config but it is not possible to use a count statement there. Per the documentation for the resource, if you pass in empty lists as follows, the vpc_config portion is ignored:

  vpc_config {
    subnet_ids = []
    security_group_ids = []
  }

I can confirm that this does work as expected (no VPC configuration is attempted).

I have therefore tried using conditionals for subnet_ids and security_group_ids - something along the lines of var.vpc_function ? var.subnet_ids : [] - but you cannot pass in a list in a conditional statement. The closest I have got to a solution is the below hacky number, which joins then splits the lists:

  resource "aws_lambda_function" "lambda_function" {
  ...
  vpc_config {
    subnet_ids = ["${split(",", var.vpc_function ? join(",", var.subnet_ids) : join(",", var.empty_array))}"]
    security_group_ids = ["${split(",", var.vpc_function ? join(",", aws_security_group.lambda_security_group.*.id) : join(",", var.empty_array))}"]
  }

variable "vpc_function" {
  default = "false"
}
variable "subnet_ids" {
  type = "list"
  default = ["subnet-a", "subnet-b"]
}
variable "empty_array" {
  type = "list"
  default = []
}

This applies fine the first time both where vpc_function is true or false, which is great, but where vpc_function is false, terraform always sees the above as a change on each reapply:

  vpc_config.#:                      "0" => "1"
  vpc_config.0.security_group_ids.#: "0" => "1"
  vpc_config.0.security_group_ids.0: "" => ""
  vpc_config.0.subnet_ids.#:         "0" => "1"
  vpc_config.0.subnet_ids.0:         "" => ""

I guess the problem is that my joined-then-split list is not seen as [], but rather as a list with some (blank) content.

Does anyone else have a solution for this? I have tried to use Terraform 0.12 as well but couldn't figure it out. Maybe someone has done something similar in Terraform 0.12 and could lend some pointers?

like image 734
SuaSwe Avatar asked Oct 15 '22 10:10

SuaSwe


1 Answers

I ended up finding the solution in terraform 12 in the end:

resource "aws_lambda_function" "lambda_function" {
...
  vpc_config {
    subnet_ids = var.vpc_function ? var.subnet_ids : []
    security_group_ids = var.vpc_function ? aws_security_group.lambda_security_group.*.id : []
  }
...
}

Variable subnet_ids is passed in as follows:

subnet_ids = ["subnet-123", "subnet-345", "subnet-456"]

And aws_security_group.lambda_security_group.*.id is created as a normal resource.

like image 69
SuaSwe Avatar answered Oct 21 '22 04:10

SuaSwe