Skip to content

LocalStack Terraform Backend Configuration

This configuration demonstrates how to use Terraform with [[LocalStack]] to simulate AWS infrastructure locally^[README.md]. It utilizes a Docker-based workflow to store the tfstate file in a local S3 bucket and manage state locks using a local DynamoDB instance^[README.md].

Prerequisites

To implement this setup, ensure the following software is installed on your machine^[README.md]:

Docker Network Setup

To enable communication between the AWS CLI container and the LocalStack instance, you must create a shared Docker network^[README.md].

  1. Create the network named localstack^[README.md]:
    docker network create localstack
    
  2. Configure your docker-compose.yml to use this external network^[README.md]:
    networks:
      default:
        external:
          name: "localstack"
    

Initializing LocalStack

Once the environment is configured, start the LocalStack container and verify the services^[README.md].

  • Start Services: Use make up to launch the container^[README.md].
  • Health Check: Run make health to ensure the dependent services (S3 and DynamoDB) are running^[README.md].

AWS CLI Configuration

Since this is a local simulation, the AWS CLI requires a specific configuration pointing to the LocalStack endpoint^[README.md].

Containerized AWS CLI

It is recommended to run the AWS CLI v2 via Docker to avoid dependency issues^[README.md].

  • Alias Command: Set up an alias to simplify commands targeting the LocalStack endpoint^[README.md]:
    alias laws='docker run --network localstack -it -v ~/.aws:/root/.aws -e LOCALSTACK_HOSTNAME=localstack amazon/aws-cli --endpoint-url=http://localstack:4566'
    

Credentials

Create a local AWS configuration with dummy credentials. The region is the most critical setting, as credential validation is typically bypassed in this environment^[README.md].

  • ~/.aws/config:
    [default]
    cli_pager=
    output=json
    region=ap-southeast-2
    
  • ~/.aws/credentials:
    [default]
    aws_access_key_id=test
    aws_secret_access_key=test
    

Provisioning Backend Resources

The final step involves using Terraform to create the S3 bucket for state storage and the DynamoDB table for locking^[README.md].

  1. Plan and Apply: Run the standard Terraform workflow commands^[README.md]:
    make plan
    make apply
    
  2. Verification: Use the AWS CLI to confirm the resources were created within LocalStack^[README.md]:
    # Verify S3 bucket
    laws s3 ls
    # Expected Output: 2021-09-05 10:23:23 terraform-state
    
    # Verify DynamoDB table
    laws dynamodb list-tables
    # Expected Output: { "TableNames": ["terraformlock"] }
    

Sources

  • README.md