Skip to content

Terraform changes a lot of resources when removing an element from the middle of a list #14275

@joshuaspence

Description

@joshuaspence

We have a lot of AWS Route53 zones which are setup in exactly the same way. As such, we are using count and a list variable to manage these. The code basically looks like this:

variable "zone_names" {
  type    = "list"
  default = []
}

resource "aws_route53_zone" "ctld" {
  name  = "${var.zone_names[count.index]}"
  count = "${length(var.zone_names)}"
}

resource "aws_route53_record" "www" {
  zone_id = "${var.zone_names[count.index]}"
  name    = "www"
  type    = "A"

  alias {
    # ...
  }

  count = "${length(var.zone_names)}"
}

However, the problem with this is that Terraform references resources using a numeric identifier. As such, if we remove an element from the middle of the list then Terraform will want to recreate all resources with a larger numeric index. This can be minimally reproduce with the following code snippet:

variable "names" {
  type    = "list"
  default = ["foo", "bar", "baz"]
}

resource "null_resource" "test" {
  triggers {
    name = "${var.names[count.index]}"
  }

  count = "${length(var.names)}"
}

Run terraform apply and then remove "bar" from var.names. The subsequent plan is as follows:

-/+ null_resource.test.1
    triggers.%:    "1" => "1"
    triggers.name: "bar" => "baz" (forces new resource)

- null_resource.test.2

I thought that one possible way to fix this would be if Terraform could index a list of resources by its identifier rather than its sequence in a list.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions