Terraform modules are a good way to abstract out repeated chunks of code, making it reusable across other Terraform projects and configurations. In this hands-on lab, we’ll be writing a basic Terraform module from scratch and then testing it out.
Learning Objectives
Successfully complete this lab by achieving the following learning objectives:
- Create the Directory Structure for the Terraform Project
- Check that Terraform is installed and functioning properly using the
terraform version
command. - Create a new directory to house your Terraform code called
terraform_project
. - In the main project directory, create a custom directory called
modules
and a directory inside it calledvpc
.
- Check that Terraform is installed and functioning properly using the
- Write Your Terraform VPC Module Code
- In the
vpc
directory, create a new file calledmain.tf
and add the provided code. - Create a new file called
variables.tf
and add the provided code. - Create a new file called
outputs.tf
and add the provided code.
- In the
- Write Your Main Terraform Project Code
- In the
terraform_project
directory, create a new file calledmain.tf
and add the provided code, which invokes the VPC module created earlier. - Create a new file called
outputs.tf
and add the provided code.
- In the
- Deploy Your Code and Test Out Your Module
- Format the code in all of your files using the
terraform fmt -recursive
command. - Initialize the Terraform configuration to fetch any required providers and get the code being referenced in the module block with the
terraform init
command. - Validate the code using the
terraform validate
command. - Review the actions that will be performed when you deploy the code using the
terraform plan
command. - Deploy the code with the
terraform apply --auto-approve
command. - View the resources that were created using the
terraform state
command. - Tear down the infrastructure using the
terraform destroy
command.
- Format the code in all of your files using the