Replacing Existing Infrastructure

Now we'll see that some times we change re-creates resources instead of updates in place. In this case, we'll change the AMI used.

1 # File cloudcasts.tf
2  
3 resource "aws_instance" "cloudcasts_web" {
4- ami = data.aws_ami.app.id
5+ ami = "ami-0a91cd140a1fc148a"
6 instance_type = "t3.small"
7  
8 root_block_device {
9 volume_size = 8 # GB
10 volume_type = "gp3"
11 }
12  
13+ lifecycle {
14+ create_before_destroy = true
15+ }
16  
17 tags = {
18 Name = "cloudcasts-staging-web"
19 Project = "cloudcasts.io"
20 Environment = "Staging"
21 ManagedBy = "Terraform"
22 }
23 }
24  
25 resource "aws_eip" "cloudcasts_addr" {
26 # We're not doing this directly
27 # instance = aws_instance.cloudcasts_web.id
28 vpc = true
29  
30 tags = {
31 Name = "cloudcasts-staging-web-address"
32 Project = "cloudcasts.io"
33 Environment = "staging"
34 ManagedBy = "terraform"
35 }
36 }
37  
38 resource "aws_eip_association" "eip_assoc" {
39 instance_id = aws_instance.cloudcasts_web.id
40 allocation_id = aws_eip.cloudcasts_addr.id
41 }

Note that the EIP remained associated with the new instance. Terraform handled it seamlessly!

We also added a new lifecycle hook:

1lifecycle {
2 create_before_destroy = true
3}

This tells Terraform to create some infrastructure BEFORE destroying the infrastructure it's replacing.

1terraform plan
2terraform apply

Don't miss out

Sign up to learn when new content is released! Courses are in production now.