Introduction to Infrastructure as Code and Terraform

Infrastructure as Code (IaC) has become a cornerstone of modern cloud management. It allows development teams to define and provision infrastructure using configuration files, a stark contrast to manual, error-prone processes via cloud provider consoles. This approach ensures consistency, repeatability, and version control for your cloud resources.

Terraform, developed by HashiCorp, is a leading open-source IaC tool. It supports a wide array of cloud providers, including AWS, Azure, and Google Cloud. Terraform uses a declarative configuration language called HashiCorp Configuration Language (HCL), which makes it relatively easy to read and write infrastructure definitions. The core principle is defining the desired end-state of your infrastructure, and Terraform figures out how to get there.

In this guide, we will walk through deploying two Amazon DynamoDB tables, Orders and Products, on AWS using Terraform. By the end, you will have these tables deployed and managed entirely through your Terraform code, enabling seamless updates, rollbacks, and integration into CI/CD pipelines.

Setting Up Your Environment

Before you can deploy DynamoDB tables with Terraform, you need to ensure your local environment is properly configured. This involves installing both Terraform and the AWS CLI, and configuring AWS credentials.

Install Terraform

Terraform can be downloaded from the official Terraform website. Follow the installation instructions for your operating system. Once installed, you can verify the installation by running terraform --version in your terminal.

Install AWS CLI

The AWS Command Line Interface (CLI) provides a convenient way to interact with AWS services from your terminal. Download and install the AWS CLI from the official AWS documentation. After installation, configure your AWS credentials by running aws configure and providing your AWS Access Key ID, Secret Access Key, default region, and output format.

Configure AWS Provider

Your Terraform configuration will need to specify the AWS provider and its region. This is typically done in a versions.tf or main.tf file.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 3.0"
    }
  }
}

provider "aws" {
  region = "us-east-1" # Replace with your desired AWS region
}

This block tells Terraform that you will be using the AWS provider and sets the default region for all resources defined in this configuration.

Defining DynamoDB Tables with Terraform

Now, let's define the DynamoDB tables using Terraform's HCL syntax. We will create two tables: Orders and Products. Each table will have a primary key.

The Orders Table

The Orders table will use OrderId as its partition key. We will define this using the aws_dynamodb_table resource.

resource "aws_dynamodb_table" "orders" {
  name           = "Orders"
  billing_mode   = "PROVISIONED" # Or "PAY_PER_REQUEST"
  read_capacity  = 5
  write_capacity = 5

  attribute {
    name = "OrderId"
    type = "S" # 'S' for String, 'N' for Number, 'B' for Binary
  }

  hash_key = "OrderId"
}

In this configuration:

  • name: The name of the DynamoDB table.
  • billing_mode: Can be PROVISIONED (specify read/write capacity units) or PAY_PER_REQUEST (on-demand). We've chosen PROVISIONED here for demonstration.
  • read_capacity and write_capacity: These are relevant if billing_mode is PROVISIONED.
  • attribute block: Defines the attributes used in the table's keys. Here, OrderId is defined as a String.
  • hash_key: Specifies the attribute that serves as the partition key.

The Products Table

Similarly, the Products table will use ProductId as its partition key. The structure is almost identical to the Orders table definition.

resource "aws_dynamodb_table" "products" {
  name           = "Products"
  billing_mode   = "PAY_PER_REQUEST"
  # read_capacity and write_capacity are not needed for PAY_PER_REQUEST

  attribute {
    name = "ProductId"
    type = "S"
  }

  hash_key = "ProductId"
}

For the Products table, we've opted for the PAY_PER_REQUEST billing mode, which automatically scales throughput based on demand. This mode does not require manual configuration of read and write capacities.

Applying the Terraform Configuration

With your Terraform configuration files in place (e.g., main.tf, versions.tf), you can now apply them to your AWS account. This process involves three main steps:

1. Initialize Terraform

Navigate to your project directory in the terminal and run the following command. This downloads the necessary AWS provider plugin.

terraform init

2. Plan the Deployment

Before making any changes to your infrastructure, it's crucial to see what Terraform plans to do. The plan command generates an execution plan, showing which resources will be created, modified, or destroyed.

terraform plan

Review the output carefully. It should indicate that two aws_dynamodb_table resources will be created.

3. Apply the Changes

If the plan looks correct, you can apply it to provision the DynamoDB tables in your AWS account. Terraform will prompt you for confirmation.

terraform apply

Type yes when prompted to confirm. Terraform will then create the Orders and Products DynamoDB tables.

Managing DynamoDB Tables with Terraform

Once your tables are managed by Terraform, you can easily update their configurations. For example, to change the billing mode of the Orders table to PAY_PER_REQUEST, you would modify the aws_dynamodb_table resource block in your main.tf file:

resource "aws_dynamodb_table" "orders" {
  name           = "Orders"
  billing_mode   = "PAY_PER_REQUEST" # Changed from PROVISIONED
  # read_capacity and write_capacity are removed for PAY_PER_REQUEST

  attribute {
    name = "OrderId"
    type = "S"
  }

  hash_key = "OrderId"
}

After saving the change, run terraform plan again to see the proposed modification, and then terraform apply to enact the change. Terraform handles the complexities of updating the existing resource.

Destroying the Infrastructure

When you no longer need the DynamoDB tables, you can remove them cleanly using Terraform. This prevents incurring unnecessary AWS costs.

terraform destroy

Terraform will show you which resources will be destroyed and prompt for confirmation. Type yes to proceed. This will delete the Orders and Products DynamoDB tables from your AWS account.

Conclusion

Using Terraform to manage DynamoDB tables on AWS provides a robust and efficient way to handle your database infrastructure. It ensures consistency, automates deployments, and simplifies updates and tear-downs. This approach is essential for any team serious about scalable and maintainable cloud operations.