Content of first.tf
### The module takes three variables as inputs:
variable "service_name" {
description = "The name of the microservice"
}
variable "ami" {
description = "The ID of an AMI for the microservice"
}
variable "instance_type" {
description = "The type of EC2 Instance for the microservice"
}
### To keep the example simple, all the module will do is create a single EC2 Instance and an Elastic IP Address for it:
resource "aws_instance" "example" {
ami = "${var.ami}"
instance_type = "${var.instance_type}"
tags {
Name = "${var.service_name}"
}
}
resource "aws_eip" "example" {
instance = "${aws_instance.example.id}"
}
# Here is an example of how you could use this module to deploy two microservices, a frontend and a backend:
module "frontend" {
source = "/modules/microservice"
service_name = "frontend"
ami = "ami-abcd1234"
instance_type = "t2.medium"
}
module "backend" {
source = "/modules/microservice"
service_name = "backend"
ami = "ami-efgh5678"
instance_type = "m4.large"
}
## This works fairly well, except for one problem: while the frontend service is user-facing and needs a public IP address, the backend is not user-facing, and it’s a waste, and perhaps even a security risk, to create a public IP for it. How can you conditionally create the aws_eip resource for some users of the microservice module and not create it for others?
If var.create_ip is true, the module will create one EIP and if var.create_ip is false, the module will create zero EIPs?which is exactly what we want!
# First, you’d add a variable that can be used to specify whether an Elastic IP Address should be created:
variable "create_eip" {
description = "If set to true, create an EIP for the microservice"
}
# Putting these two ideas together, you can update the microservice module as follows:
resource "aws_eip" "example" {
count = "${var.create_eip}"
instance = "${aws_instance.example.id}"
}
# If var.create_ip is true, the module will create one EIP and if var.create_ip is false, the module will create zero EIPs — which is exactly what we want! You can now update your two microservices so that the frontend gets an EIP and the backend does not:
module "frontend" {
source = "/modules/microservice"
service_name = "frontend"
ami = "ami-abcd1234"
instance_type = "t2.medium"
create_eip = true
}
module "backend" {
source = "/modules/microservice"
service_name = "backend"
ami = "ami-efgh5678"
instance_type = "m4.large"
create_eip = false
}