Community EC2 Module

The community EC2 module creates one or more EC2 instances for us, but what do we do with our EIP resources?

We can use modules within our own modules! Let's see how to do that.

File main.tf

First we'll update modules/ec2/main.tf to use the community module in place of our aws_instance resource block.

1resource "random_shuffle" "subnets" {
2 input = var.subnets
3 result_count = 1
4}
5 
6# https://registry.terraform.io/modules/terraform-aws-modules/ec2-instance/aws/latest
7module "ec2-instance" {
8 source = "terraform-aws-modules/ec2-instance/aws"
9 version = "2.17.0"
10 
11 name = "cloudcasts-${var.infra_env}"
12 
13 ami = var.instance_ami
14 instance_type = var.instance_size
15 vpc_security_group_ids = var.security_groups
16 subnet_id = random_shuffle.subnets.result[0]
17 
18 root_block_device = [{
19 volume_size = var.instance_root_device_size
20 volume_type = "gp3"
21 }]
22 
23 tags = merge(
24 {
25 Name = "cloudcasts-${var.infra_env}"
26 Role = var.infra_role
27 Project = "cloudcasts.io"
28 Environment = var.infra_env
29 ManagedBy = "terraform"
30 },
31 var.tags
32 )
33}
34 
35resource "aws_eip" "cloudcasts_addr" {
36 count = (var.create_eip) ? 1 : 0
37 # We're not doing this directly
38 # instance = aws_instance.cloudcasts_web.id
39 vpc = true
40 
41 lifecycle {
42 # Temporarily disable this so we can remove the
43 # EIP from our worker EC2 server
44 # prevent_destroy = true
45 }
46 
47 tags = {
48 Name = "cloudcasts-${var.infra_env}-web-address"
49 Role = var.infra_role
50 Project = "cloudcasts.io"
51 Environment = var.infra_env
52 ManagedBy = "terraform"
53 }
54}
55 
56resource "aws_eip_association" "eip_assoc" {
57 count = (var.create_eip) ? 1 : 0
58 
59 # Use the "module.module-name.output" syntax
60 # to get the modules output variables
61 instance_id = module.ec2-instance.id[0]
62 allocation_id = aws_eip.cloudcasts_addr[0].id
63}

We can see some differences in how we create an instance using the module, but largely it's the same!

File outputs.tf

We need to update our module/ec2/outputs.tf file to return the first server the module it creates, since it uses count to create one or more servers.

1output "app_instance" {
2 # Use the "module.module-name.output" syntax
3 # to get the modules output variables
4 value = module.ec2-instance.id[0]
5}

To use the new module, we need to init first:

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.