AWS ECR Terraform Infrastructure Patterns

Amazon Elastic Container Registry is a fully managed container registry service. In a cloud computing and microservice world, infrastructure resources must be involved properly. Terraform, an open source IaC tool that is widely used for provisioning and managing cloud resources across many cloud service providers such as AWS, has become the de-facto standard for defining the desired state of infrastructure in software configuration files. With Terraform, you may define your desired state of an ECR repository and other associated resources. Terraform will consequently handle the creation, updating, and maintenance procedures for your infrastructure.

Amazon Elastic Container Registry is a fully managed Docker container registry that gives the chance to images to store, manage, and deploy. The Amazon ECR is a fully managed Docker container offering provided by Amazon Web Services as it is prevalently called, abbreviated as AWS, which is a cloud computing subsidiary of Amazon. AWS ECR is a service offered by AWS that allows developers to store, manage, and deploy Docker container images and Open Container Initiative images. It integrates seamlessly with Amazon ECS, EKS, and other AWS services, enabling streamlined containerized application development and deployment. ECR also provides features like image versioning, access control, and automated scanning for vulnerabilities. Each ECR account has its own private registry, where you can create one or more repositories to store Docker images, OCI images, and compatible artifacts. Clients must authenticate to an Amazon ECR private registry as an AWS user before pushing or pulling images.

Prerequisites and Project Layout

A guide to setting up ECR using Terraform lists prerequisites that are commonly required.

  • AWS CLI configured
  • Terraform installed
  • Docker installed locally
  • Container images to store

The project structure referenced for an ECR Terraform example is:

aws-ecr-terraform/
├── main.tf
├── variables.tf
├── outputs.tf
└── terraform.tfvars

This layout separates provider configuration, resource definitions, variable declarations, and variable values.

Core AWS ECR Concepts

What is an ECR repository?

The Amazon ECR is a fully managed Docker container offering provided by Amazon Web Services. Repositories of ECR may be differentiating for the libraries, each of which contains multiple Docker Images, designated by different tags (versions and configurations).

ECR uses S3 as the underlying storage layer, which provides durability, availability, and lifecycle management for the images. ECR is used to store, manage, and deploy Docker container images in AWS. It integrates with services like ECS, EKS, and CodeBuild, allowing secure, scalable image storage without managing your own registry.

Amazon Elastic Container Registry is a managed container image registry service provided by AWS, used to store, manage, and deploy Docker container images. It is not the same as Docker.

Terraform Fundamentals for ECR

Terraform is an open-source resource infrastructure tool manufactured by HashiCorp. It provides the independence of its declaration and configuration to the developers and operations teams to define, provision, and manage cloud infrastructure resources across multiple cloud providers and off-premises environments in a consistent manner.

The basic structure of terraform is based on a human-friendly language that is called HashiCorp Configuration Language or HCL which implies the desired state of infrastructure resources. These resources can include things like virtual machines, networks, databases, and container registries provided by big top cloud providers such as Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the rest.

OpenTofu is an open-source version of Terraform that expands on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6.

Create ECR repository in AWS using Terraform: Practical Step-by-Step Guide

Step 1: Install Terraform

If you haven't already, install Terraform on your machine. You can download by referring to Terraform Install

Step 2: Configure AWS Provider

Create a new Terraform configuration file, let's call it main.tf. In this file, you need to define the AWS provider and specify your AWS credentials

Basic ECR Configuration with Terraform

A basic ECR configuration with Terraform typically defines the AWS provider, the repository, encryption, and tagging.

```hcl
provider "aws" {
region = var.aws_region
}

resource "awsecrrepository" "main" {
name = var.repositoryname
image
tagmutability = "IMMUTABLE"
image
scanningconfiguration {
scan
onpush = true
}
encryption
configuration {
encryptiontype = "KMS"
kms
key = awskmskey.ecr.arn
}
tags = {
Environment = var.environment
}
}
```

The KMS key for encryption is defined alongside the repository.

hcl resource "aws_kms_key" "ecr" { description = "KMS key for ECR encryption" deletion_window_in_days = 7 enable_key_rotation = true tags = { Environment = var.environment } }

The terraform-aws-ecr module provides a flexible interface for managing ECR resources in AWS. The module is highly customizable through many input variables.

Configuration flow from Terraform variables to AWS ECR resources is illustrated in module documentation.

Repository Policy and Access Control

Repository policy controls who can pull or push images.

hcl resource "aws_ecr_repository_policy" "main" { repository = aws_ecr_repository.main.name policy = jsonencode({ Version = "2012-10-17" Statement = [ { Sid = "AllowPull" Effect = "Allow" Principal = { AWS = var.allowed_account_arns } Action = [ "ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage", "ecr:BatchCheckLayerAvailability" ] } ] }) }

Clients must authenticate to an Amazon ECR private registry as an AWS user before pushing or pulling images.

Lifecycle Policy and Cost Management

Attach an awsecrlifecycle_policy with a JSON policy (camelCase keys) to expire old or untagged images and keep storage costs in check.

hcl resource "aws_ecr_lifecycle_policy" "main" { repository = aws_ecr_repository.main.name policy = jsonencode({ rules = [ { rulePriority = 1 description = "Keep last 30 production images" selection = { tagStatus = "tagged" tagPrefixList = ["prod"] countType = } } ] }) }

The lifecycle policy can be used to retain a defined number of images and remove untagged images.

Resource Purpose Key Attributes
awsecrrepository Create registry repository name, imagetagmutability, imagescanningconfiguration
awskmskey Encryption for images description, deletionwindowindays, enablekey_rotation
awsecrrepository_policy Access control repository, policy json
awsecrlifecycle_policy Cost and retention repository, policy json with camelCase keys

Using the terraform-aws-ecr Module

This guide provides essential instructions for setting up and using the terraform-aws-ecr module to manage Amazon Elastic Container Registry resources. For more advanced features like pull-through cache configuration or replication settings, see Advanced Features.

Before using the terraform-aws-ecr module, ensure you have prerequisites in place.

To use the module in your Terraform configuration, add the following block:

The module provides a flexible interface for managing ECR resources in AWS.

This example shows how to create a private ECR repository with a lifecycle policy and access control.

For a public repository, use the following configuration.

The module is highly customizable through many input variables.

Importing Existing Repositories and Multi-Repository Patterns

Bring an existing repository under Terraform management with a top-level import block. Requires Terraform 1.5 or later, and the id is the repository name.

For multiple repositories that share configuration, use a public module like terraform-aws-modules/ecr/aws or cloudposse/ecr/aws, or wrap the resource in your own module.

Integration and Storage Characteristics

ECR integrates seamlessly with Amazon ECS, EKS, and other AWS services, enabling streamlined containerized application development and deployment.

Each ECR account has its own private registry, where you can create one or more repositories to store Docker images, OCI images, and compatible artifacts.

Is ECR backed by S3?

ECR uses S3 as the underlying storage layer, which provides durability, availability, and lifecycle management for the images.

Frequently Asked Questions

  • Is ECR the same as Docker?
    Amazon Elastic Container Registry is a managed container image registry service provided by AWS, used to store, manage, and deploy Docker container images.

  • What is an ECR used for?
    ECR is used to store, manage, and deploy Docker container images in AWS. It integrates with services like ECS, EKS, and CodeBuild, allowing secure, scalable image storage without managing your own registry.

  • Is ECR backed by S3?
    ECR uses S3 as the underlying storage layer, which provides durability, availability, and lifecycle management for the images.

Conclusion

Managing AWS ECR with Terraform provides a hot approach to IT architecture preservation for container image storage. Defining repositories, encryption with KMS, scanning on push, repository policies, and lifecycle policies in HCL ensures consistent, auditable, and repeatable infrastructure. Module-based workflows such as terraform-aws-ecr, import workflows for existing repositories, and shared module patterns for multiple repositories support scale and governance. With ECR’s integration with ECS, EKS, and CodeBuild, and its S3-backed durability, Terraform-driven ECR configurations remain a core part of modern container delivery pipelines.

Sources

  1. Source Name
  2. Source Name
  3. Source Name
  4. Source Name

Related Posts