Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional map variables in terraform module

Not sure if this is possible but I have a module for a DynamoDb table, I want to make the global_secondary_index attribute optional but I can't figure out how to do it.

I have the following module

resource "aws_dynamodb_table" "basic_dynamodb_table" {
  name                = "${var.table_name}"
  read_capacity       = "${var.read_capacity}"
  write_capacity      = "${var.write_capacity}"
  hash_key            = "${var.primary_key}"

  attribute {
    name            = "${var.primary_key}"
    type            = "${var.primary_key_type}"
  }

  global_secondary_index = ["${var.global_secondary_index}"]
}

variable "table_name" {}

variable "read_capacity" {
  default     = "1"
}

variable "write_capacity" {
  default     = "1"
}

variable "primary_key" {}

variable "primary_key_type" {}

variable "global_secondary_index" {
  default = {}
  type = "map"
  description = "This should be optional"
}

And it would be used

module "test-table" {
  source              = "./modules/DynamoDb"

  table_name          = "test-table"
  primary_key         = "Id"
  primary_key_type    = "S"

  global_secondary_index = {
    name = "by-secondary-id"
    hash_key = "secondaryId"
    range_key = "type"
    projection_type = "INCLUDE"
    non_key_attributes = [
        "id"
    ]
    write_capacity = 1
    read_capacity = 1
  }
}

I've tried:

  • without using [] around the interpolation and get global_secondary_index: should be a list error
  • just using the var global_secondary_index = ["${var.global_secondary_index}"] get global_secondary_index.0: expected object, got string error
  • Conditional but apparently doesn't support list or map
  • merge map global_secondary_index = ["${merge(var.global_secondary_index,map())}"] also get global_secondary_index.0: expected object, got string error

out of ideas on how to make this work now

like image 588
JonSquared Avatar asked Feb 28 '17 00:02

JonSquared


1 Answers

Seems to be a feature that's missing:

https://github.com/hashicorp/terraform/issues/3388

Variations on that theme (passing lists of maps in to resources):

https://github.com/hashicorp/terraform/issues/12294 https://github.com/hashicorp/terraform/issues/7705

One last thing to note though, on the conditionals you can get sneaky with those.

resource "some_tf_resource" "meh" {
  count = "${length(keys(var.my_map)) > 0 ? 1 : 0}"
  # other resource settings here
}

Using count and setting it to 0 was the hack way of getting around terraforms lack of conditionals in earlier versions. It still works =)

That gets ugly quickly though if there are other resources that depend on the meh resource, so I wouldn't use it too often if you can avoid it.

like image 128
Paul Avatar answered Sep 23 '22 15:09

Paul