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_ami14 instance_type = var.instance_size15 vpc_security_group_ids = var.security_groups16 subnet_id = random_shuffle.subnets.result[0]17 18 root_block_device = [{19 volume_size = var.instance_root_device_size20 volume_type = "gp3"21 }]22 23 tags = merge(24 {25 Name = "cloudcasts-${var.infra_env}"26 Role = var.infra_role27 Project = "cloudcasts.io"28 Environment = var.infra_env29 ManagedBy = "terraform"30 },31 var.tags32 )33}34 35resource "aws_eip" "cloudcasts_addr" {36 count = (var.create_eip) ? 1 : 037 # We're not doing this directly38 # instance = aws_instance.cloudcasts_web.id39 vpc = true40 41 lifecycle {42 # Temporarily disable this so we can remove the43 # EIP from our worker EC2 server44 # prevent_destroy = true45 }46 47 tags = {48 Name = "cloudcasts-${var.infra_env}-web-address"49 Role = var.infra_role50 Project = "cloudcasts.io"51 Environment = var.infra_env52 ManagedBy = "terraform"53 }54}55 56resource "aws_eip_association" "eip_assoc" {57 count = (var.create_eip) ? 1 : 058 59 # Use the "module.module-name.output" syntax60 # to get the modules output variables61 instance_id = module.ec2-instance.id[0]62 allocation_id = aws_eip.cloudcasts_addr[0].id63}
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" syntax3 # to get the modules output variables4 value = module.ec2-instance.id[0]5}
To use the new module, we need to init first:
1terraform init2terraform plan -var-file=variables.tfvars3terraform apply -var-file=variables.tfvars