Module Inputs
Categories:
2 minute read
To make a reusable module effective you need to be able to customize the parameters to which it builds resources when it is used by the root module. If values are hardcoded in the reusable module then every deployment will be the same and that is not useful and it’s likely you’d come to a crashing halt as most resources require unqiue names, etc.
To solve this we use input variables
that are defined in the reusable module and declared in the root module.
This is a stand-alone Terraform configuration to build an AWS EC2 instance. The ami
and instance_type
are hard coded.
resource "aws_instance" "example" {
ami = "ami-0fb653ca2d3203ac1"
instance_type = "t2.micro"
}
If this code was changed to a reusable module and called from the root moduled then you would only be able to deploy an Ubuntu instance at the t2.micro type. To allow you to change these values we need to use module inputs
defined as variables.
In the reusable module folder you have two files. The main.tf
file is where you define the resources as usual but instead of setting the value you use variables instead which are defined in the second filed called variables.tf
. No actual values are set in the reusable module code, they are declared in the root module by referring to the variable names and then entering the actual value.
In the reusable module
folder you have the main.tf
and variables.tf
files.
resource "aws_instance" "example" {
ami = var.ami
instance_type = var.instance_type
}
variable "ami" {
description = "The AMI to be used for the EC2"
type = string
}
variable "instance_type" {
description = "The type of the EC2 Instances to run (e.g. t2-micro)"
type = string
}
In the root module
folder you have the configuration file where you reference the variable names and declare the values which are used by the reusable module code when it executes.
main.tf
module "ec2_instance" {
source = "../../../../modules/ec2-instance"
ami = "ami-0fb653ca2d3203ac1"
instance_type = "m2.micro"
}
The folder structure would look like this.
+---modules
| \---ec2-instance
| | main.tf
| | variables.tf
|
+---projects
| \---project00
| \---prod
| \---services
| \---virtual-machines
| | main.tf