Introduction
When adopting Infrastructure as Code (IaC) with Terraform, a key architectural decision is how to organize source code repositories. Teams must decide whether to store Terraform configuration files with the application source code (monorepo) or maintain them in separate repositories (polyrepo). The ideal structure depends on team responsibilities, deployment workflows, and how application and infrastructure changes are managed.
Scenario
The guiding principle is to align repository boundaries with the rate of change and ownership of the components. Two common patterns highlight this choice:
- Serverless or Microservices Architecture: In an architecture like AWS Lambda, the function code and its infrastructure resources—such as permissions, triggers, and event sources—are tightly coupled. They typically need to be versioned and deployed together.
- Traditional Server-Based Architecture: In setups where centralized infrastructure, like a cluster of EC2 instances or shared networking, is managed independently of application deployments, the infrastructure changes less frequently than the application code.
Recommendation
Choose a repository structure that reflects the rate of change and ownership of each component.
Approach 1: Monorepo for Tightly Coupled Components
Use a monorepo structure when application code and its infrastructure are tightly coupled and evolve together, such as in serverless or microservices architectures. Storing Terraform configuration with application code simplifies versioning, enables atomic changes, and treats the application and its infrastructure as a single deployable unit.
Approach 2: Polyrepo for Loosely Coupled Components
Use a polyrepo structure when core infrastructure is managed independently from application deployments, such as with traditional server-based architectures. Separating repositories clarifies team responsibilities, reduces unnecessary dependencies, and accommodates different release cadences for infrastructure and applications.
Ultimately, the decision is influenced more by team workflows and collaboration needs than by technical limitations.
The Role of Terraform Modules
Regardless of your repository strategy, using Terraform Modules is an essential best practice for encapsulating and reusing infrastructure logic.
- Encapsulation and Reuse: Modules package complex infrastructure configurations, enabling reuse across multiple projects and environments.
- Decoupling: Applications can reference centrally maintained modules, even from a third repository, to ensure consistent standards and reduce duplication.
Additional Information
For more details on creating and using modules, refer to the official Terraform Modules documentation.