- A single EC2 instance, using a custom AMI, that hosts the application server.
- A DynamoDB NoSQL database to store employee and payroll data.
- An S3 bucket to store documents such as pay stubs and tax forms.

Module Directory and File Structure
The reusable module will be stored in themodules directory. In this example, we will use the path:
/root/terraform-projects/modules/payroll-app
This directory will contain resource definitions for the EC2 instance, S3 bucket, and DynamoDB table. To maintain consistency across environments, some configuration values such as the EC2 instance type, DynamoDB table name, and primary key are hard-coded, while others like the AMI are configurable by the user.
Creating the Module Directory
app_server.tfs3_bucket.tfdynamodb_table.tfvariables.tf
Module Resource Definitions
EC2 Instance Configuration (app_server.tf)
S3 Bucket Configuration (s3_bucket.tf)
DynamoDB Table Configuration (dynamodb_table.tf)
Module Variables (variables.tf)
Deploying the Terraform Module
Once the module is defined, we can deploy an instance of it. Below are examples of deploying the module in two regions: US East 1 and the UK (London region).US East 1 Deployment
Start by creating a directory for the US payroll application:main.tf file with the following content:
If you need to override the default bucket name, you can specify the
bucket variable in this module configuration.UK Deployment
To deploy the same stack in the UK region, create a directory for the UK payroll application:main.tf file with the following content:
app_region is set to eu-west-2 (London region) and the AMI ID is appropriate for that region. When you run terraform apply, Terraform will create the resources with names prefixed by eu-west-2 to reflect the region-specific deployment.
The module output ensures clear resource addressing. For instance, you can reference the DynamoDB table as:
Benefits of Using Terraform Modules
Using reusable modules in Terraform provides several advantages:
By adopting a module-based approach, you ensure that key configuration aspects such as the EC2 instance type and DynamoDB settings remain constant, while still being able to adjust region-specific variables like the AMI ID and bucket naming.
For further learning on Terraform modules, refer to the Terraform Documentation.
That’s it for this guide on creating and deploying a Terraform module for multiple environments. Happy deploying!