naeroy
naeroy

Reputation: 95

select specific patterns from string to create resources - terraform

I will like to create resources on AWS using patterns from a variable in terraform.

For example:

proyects = ["proyect1/X", "proyect1/Y", "proyect2/X", ...]

resource "aws_example" "proyect1" {
count = length(var.proyects) <-- only using the proyect1/... ones
name = var.proyects[count.index] <-- only using the proyect1/... ones

resource proyect1/X created

resource proyect1/Y created

resource "aws_example" "proyect2" {
count = length(var.proyects) <-- only using the proyect2/... ones
name = var.proyects[count.index] <-- only using the proyect2/... ones

resource proyect2/X created

resource proyect2/Y created


I don't know if this is possible...I'm trying using https://www.terraform.io/docs/language/functions/index.html

Upvotes: 1

Views: 179

Answers (1)

Marcin
Marcin

Reputation: 238877

You can filter by proyect1 and proyect2 and use for_each:

variable "proyects" {
  default = ["proyect1/X", "proyect1/Y", "proyect2/X", "proyect2/Y", "proyect2/Z"]
}


resource "aws_example" "proyect1" {
  for_each = [for v in var.proyects : v if length(regexall("proyect1.*", v)) > 0]
  name = each.key
}

resource "aws_example" "proyect2" {
  for_each = [for v in var.proyects : v if length(regexall("proyect2.*", v)) > 0]
  name = each.key
}

Upvotes: 1

Related Questions