Changing Existing Infrastructure

Let's make some changes and see how Terraform handles it.

We'll assign an IP address to the server, and add some tags.

Some related resources:

Let's see what that looks like:

1 # File cloudcasts.tf
2  
3 resource "aws_instance" "cloudcasts_web" {
4 ami = data.aws_ami.app.id
5 instance_type = "t3.small"
6  
7 root_block_device {
8 volume_size = 8 # GB
9 volume_type = "gp3"
10 }
11  
12+ tags = {
13+ Name = "cloudcasts-staging-web"
14+ Project = "cloudcasts.io"
15+ Environment = "staging"
16+ ManagedBy = "terraform"
17+ }
18 }
19  
20 # We add in all the following as well
21  
22 resource "aws_eip" "cloudcasts_addr" {
23 ## We're don't define an instance directly here,
24 ## The reason is covered in the video
25 # instance = aws_instance.cloudcasts_web.id
26  
27 vpc = true
28  
29 lifecycle {
30 prevent_destroy = true
31 }
32  
33 tags = {
34 Name = "cloudcasts-staging-web-address"
35 Project = "cloudcasts.io"
36 Environment = "staging"
37 ManagedBy = "terraform"
38 }
39 }
40  
41 resource "aws_eip_association" "eip_assoc" {
42 instance_id = aws_instance.cloudcasts_web.id
43 allocation_id = aws_eip.cloudcasts_addr.id
44 }

Note the use of the prevent_destroy lifecycle rule as well. This helps us not lose an EIP accidentally, which might be important to save us from downtime if our IP address changes and we had a DNS entry pointing to that that IP.

Terraform often lets you do some shortcuts, such as create an EIP and immediately associate it with a server within the aws_eip resource.

However, if you have the option, you should always use additional resources for associations. In this case, we'll use resource "aws_eip_association" to associate an EIP to an instance. This prevents issues in the future such as deleting an EIP due to dependency handling in Terraform, or circular dependencies when TF is planning on what it needs to do.

We apply the changes:

1terraform plan
2terraform apply

Don't miss out

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