Using the VPC

Our EC2 module doesn't have the ability to be told what subnets (and therefore which VPC) to be created within. That means they'll be assigned to a subnet in the default VPC in our us-east-2 region.

We'll fix that by updating the ec2 module so it can be told which subnets to join.

File variables.tf

Add the following to file modules/ec2/variables.tf:

1variable subnets {
2 type = list(string)
3 description = "valid subnets to assign to server"
4}
5 
6variable security_groups {
7 type = list(string)
8 description = "security groups to assign to server"
9 default = []
10}

File main.tf

We'll update file modules/ec2/main.tf to make use of the new variables.

We make use of the random_shuffle provider to get us a random subnet from given list of subnets we provide.

1+resource "random_shuffle" "subnets" {
2+ input = var.subnets
3+ result_count = 1
4+}
5  
6 resource "aws_instance" "cloudcasts_web" {
7 ami = var.instance_ami
8 instance_type = var.instance_size
9  
10 root_block_device {
11 volume_size = var.instance_root_device_size
12 volume_type = "gp3"
13 }
14  
15+ subnet_id = random_shuffle.subnets.result[0]
16+ vpc_security_group_ids = var.security_groups
17  
18 lifecycle {
19 create_before_destroy = true
20 }
21  
22 tags = {
23 Name = "cloudcasts-${var.infra_env}-${var.infra_role}"
24 Role = var.infra_role
25 Project = "cloudcasts.io"
26 Environment = var.infra_env
27 ManagedBy = "terraform"
28 }
29 }

File cloudcasts.tf

Finally, we can update the cloudcasts.tf file to say which subnets to create the ec2 instances into.

1 module "ec2_app" {
2 source = "./modules/ec2"
3  
4 infra_env = var.infra_env
5 infra_role = "app"
6 instance_size = "t3.small"
7 instance_ami = data.aws_ami.app.id
8+ subnets = keys(module.vpc.vpc_public_subnets) # Note: Public subnets
9+ # security_groups = [] # TODO: Create security groups
10+ # instance_root_device_size = 12
11 }
12  
13 module "ec2_worker" {
14 source = "./modules/ec2"
15  
16 infra_env = var.infra_env
17 infra_role = "app"
18 instance_size = "t3.small"
19 instance_ami = data.aws_ami.app.id
20+ subnets = keys(module.vpc.vpc_private_subnets) # Note: Private subnets
21+ # security_groups = [] # TODO: Create security groups
22+ # instance_root_device_size = 20 //
23 }

We have a new provider plugin used (via the random_shuffle resource), so we need to init before planning/applying:

1terraform init
2terraform plan -var-file=variables.tfvars
3terraform apply -var-file=variables.tfvars

Don't miss out

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