For_each loop, when used, terminates aws ec2 instances even though variable unrelated(?)

Currently using a variable map to create instances using the for_each loop. Even though I only change the private_ip variable, on the defined instance block, it is tearing down the entire stack that is defined. Is this something you simply cannot do and I’ll have to create a block for each instance?


Hi @matthew.paskus, it’s hard to say what is going on without seeing the configuration. A complete example would be helpful in diagnosing your issue.

I found that if I just change the ip within hostnames (variable map) it destroys both instances.

resource "aws_instance" "stack" {
  for_each      = var.hostnames
  ami           = each.value.version
  instance_type = each.value.instance_type
  iam_instance_profile  = "OnSipSSMRole"
  private_ip = each.value.private_ip
  security_groups = ["${}","${}"]
  subnet_id  =
  user_data = templatefile("${path.module}/templates/user_data.tpl", {
    instance_hostname = each.value.instance_name
  tags = {
    Name = "${each.key}"


variable "hostnames" {
  default = {
     "bounce" = {
      "instance_name"   = "bounce",
      "instance_type"   = "t2.micro"
      "private_ip"     = "",
      "version"         = "ami-0ac9a26f4cd07afd6",
      "security_groups" = ["allow_ssh"]
    "aws-test" = {
      "instance_name"   = "aws-test",
      "instance_type"   = "t2.small"
      "private_ip"      = "",
      "version"         = "ami-079d1857385c60832",
      "security_groups" = ","

Changeing the private_ip of a an aws_instance will force that instance to be replaced. This is a property of the aws_instance resource, and not decided by Terraform itself. When you have change like tis, you can also look for the # forces replacement note in the plan output, which indicates the attribute causing the planned action.

Thank you so even if the variable was in the first block(ip change for first instance) it also accounts for that second instance being torn down?

Hi @matthew.paskus,

As @jbardin noted, Terraform should explain in the plan output which of the changes caused the provider to plan to replace each object, so I’d expect to see a # forces replacement annotation on each of the instances proposed for replacement.

If the plan isn’t being clear about which change prompted it, perhaps you could share the planned changes here in a new message and then we can hopefully interpret what the provider proposed and explain why it did so.