user6826691
user6826691

Reputation: 2011

How to slice 1st element in nested list in terraform

I want to pass var.domain_names as list(list(string)), example:

domain_names = [
  ["foo.com",".*foo-1.com",".*foo-2.com"],
  ["bar.com",".*bar-1.com"],
  ...
]

So it should create certificate for foo.com, bar.com ... but add others like .*foo-1.com ... to the subject_alternative_names.

Please help me solve this, Using terraform 0.12.18

resource "aws_acm_certificate" "certificate" {
  domain_name               = var.domain_names[count.index]
  subject_alternative_names = slice(var.domain_names, 1, length(var.domain_names))
  validation_method         = var.validation_method

  tags = {
    Name      = var.domain_names[count.index]
    owner     = "xx"
    terraform = "true"
  }

  lifecycle {
    create_before_destroy = true
  }
}

Upvotes: 3

Views: 1406

Answers (1)

Ben Whaley
Ben Whaley

Reputation: 34416

You can accomplish this with a map and a for_each loop. For example:

variable "domain_names" {
  type = map(list(string))
  default = {
    "foo.com" = ["foo.com", ".*foo-1.com", ".*foo-2.com"]
    "bar.com" = [".*bar-1.com"]
  }
}

resource "aws_acm_certificate" "certificate" {
  for_each                  = var.domain_names
  domain_name               = each.key
  subject_alternative_names = each.value
  validation_method         = var.validation_method

  tags = {
    Name      = each.key
    owner     = "xx"
    terraform = "true"
  }

  lifecycle {
    create_before_destroy = true
  }
}

Refer to this blog post for more info on loops and conditionals.

Upvotes: 2

Related Questions