Video Thumbnail for Lesson
7.3: Using Subdirectory Environments

Using Subdirectories to Manage Environments

In this lesson, we will demonstrate how to use subdirectories to manage multiple environments for our sample web application.

We will create two environments, production and staging, and deploy the web application to both environments using a directory layout approach.

Refactoring the Codebase

  1. Create a three new subdirectories: global, production, and staging.

  2. The global directory will contain resources shared across multiple environments, such as the Route 53 Zone. Add a main.tf file in the global directory with the Terraform block and the resource for the Route 53 Zone.

# Route53 zone is shared across staging and production
resource "aws_route53_zone" "primary" {
  name = "MY_DOMAIN.com"
}
  1. In both the production and staging directories, create a main.tf file defining the options for the module being deployed.

These files will be similar to the previous examples, but set the create_dns_zone variable to false since the DNS zone is managed in the global directory.

āÆ tree ./
.
ā”œā”€ā”€ global/
ā”‚   ā””ā”€ā”€ main.tf
ā”œā”€ā”€ production/
ā”‚   ā””ā”€ā”€ main.tf
ā””ā”€ā”€ staging/
    ā””ā”€ā”€ main.tf

3 directories, 4 files

Deploying the Environments

  1. Navigate to the global directory, initialize Terraform using terraform init, and apply the configuration using terraform apply. This step will create the shared Route 53 Zone.

  2. Navigate to the production directory, initialize Terraform using terraform init, and apply the configuration using terraform apply. This will deploy the production environment.

  3. Navigate to the staging directory, initialize Terraform using terraform init, and apply the configuration using terraform apply. This will deploy the staging environment.

Advantages and Disadvantages of the Subdirectories Approach

Advantages:

  • Clear organization of environments in the file structure.
  • Easier to reason about the actual infrastructure deployed.

Disadvantages:

  • More code repetition, as each environment has its own main.tf file.
  • Some limitations in templating the backend provider, leading to hardcoding values.

In this lesson, we demonstrated how to use subdirectories to manage multiple environments for our sample web application.

We created two environments, production and staging, and deployed the web application to both environments using a directory layout approach.

This method offers clear organization and is easy to understand, but has some downsides such as code repetition and limitations in templating the backend provider.