brikis98 / terraform-up-and-running-code

Code samples for the book "Terraform: Up & Running" by Yevgeniy Brikman
http://www.terraformupandrunning.com/
MIT License
2.87k stars 1.92k forks source link

Terraform can't change AWS region #20

Closed devforfu closed 4 years ago

devforfu commented 6 years ago

Not sure if that's an expected behavior or kind of bug, but when I change an AWS region after the first instance was already deployed, the old instance is not deleted.

Here is an example. Consider the script from the 2nd chapter:

provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "example" {
  ami           = "ami-40d28157"
  instance_type = "t2.micro"
  vpc_security_group_ids = ["${aws_security_group.instance.id}"]

  user_data = <<-EOF
              #!/bin/bash
              echo "Hello World!" > index.html
              nohup busybox httpd -f -p 8080 &
              EOF

  tags {
    Name = "terraform-example"
  }
}

resource "aws_security_group" "instance" {
  name = "terraform-example-instance"

  ingress = {
    from_port   = 8080
    to_port     = 8080
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

If you run terraform apply everything is fine. If you change anything, then these changes will be detected. However, try to replace region with something else like:

provider "aws" {
  region = "eu-west-1"
}

In this case, terraform plan doesn't say that one instance is destroyed and a new one created. It tries to create the second instance instead, and fails with error due to same ID or something.

Probably this moment should be mentioned somewhere in the book if this issue still exists in new versions of the Terraform, or probably the "provider" section is not covered with guarantee of being idempotent?

brikis98 commented 6 years ago

This is actually a Terraform limitation. It doesn't really track provider changes, so when you change regions, you get some very odd behavior.

It tries to create the second instance instead, and fails with error due to same ID or something.

The failure is either Terraform trying to delete the instance IDs from the old region in the new one, which will fail since those IDs don't exist in the new region, or from trying to deploy the AMI ID in the new region, as AMI IDs are also region specific.

devforfu commented 6 years ago

@brikis98 Ok, understood, thank you for the explanation.

v71017 commented 5 years ago

Terrform maintain the state in s3 bucket as backend. Please check if there is already some existing state in the bucket. if it is failing rename the key and try again.

brikis98 commented 4 years ago

I believe the question here was answered, so closing.