Amazon Elastic Container Registry is a fully managed container registry service. Terraform is an open-source resource infrastructure tool manufactured by HashiCorp that provides the independence of its declaration and configuration to 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.
In a cloud computing and microservice world, we must concentrate on the involvement of the infrastructure resources properly. With Terraform, an open source IaC infrastructure as code tool that is widely used for provisioning and managing cloud resources across many cloud service providers such as AWS Amazon Web Services, becoming the de-facto standard, it is not surprising that people have started noticing its advantages over other available options. Among the workable services of AWS is Amazon Elastic Container Registry which is a well-managed Docker container registry that gives the chance to images to store, manage, and deploy.
Terraform replies to the difficulty of creating and handling ECR repositories by providing a hot approach to IT architecture preservation. In Terraform, you may define your desired state of an ECR repository and other associated resources in a software configuration file. Terraform will consequently handle the creation, updating, and maintenance procedures for your infrastructure.
What Terraform and Amazon ECR Are
Amazon Elastic Container Registry 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.
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.
Repositories of ECR may be differentiating for the libraries, each of which contains multiple Docker Images, designated by different tags versions and configurations.
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.
Terraform Infrastructure as Code tool used to automate and manage all cloud resources.
- Defines, provisions, and destroys infrastructure consistently across environments
- Enables full automation of the VPC, ECS, ALB, CloudFront, S3, CloudWatch, and SNS setup
- Makes your deployments repeatable, version-controlled, and easy to maintain
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.
Prerequisites and Project Structure
This guide shows how to set up ECR using Terraform.
Prerequisites
- AWS CLI configured
- Terraform installed
- Docker installed locally
- Container images to store
Project Structure
aws-ecr-terraform/
├── main.tf
├── variables.tf
├── outputs.tf
└── terraform.tfvars
The structure separates provider configuration, resource definitions, variable declarations, and values for a clean, repeatable workflow.
Basic ECR Configuration with Terraform
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.
provider "aws" {
region = var.aws_region
}
ECR Repository Resource
resource "aws_ecr_repository" "main" {
name = var.repository_name
image_tag_mutability = "IMMUTABLE"
image_scanning_configuration {
scan_on_push = true
}
encryption_configuration {
encryption_type = "KMS"
kms_key = aws_kms_key.ecr.arn
}
tags = {
Environment = var.environment
}
}
The resource sets imagetagmutability to IMMUTABLE, enables scanonpush, and configures encryptionconfiguration with encryptiontype KMS referencing awskmskey.ecr.arn.
KMS Key for Encryption
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 KMS key supports encryption for the repository and has key rotation enabled.
The following table summarizes key attributes from the reference configuration.
| Attribute | Value | Purpose |
|---|---|---|
| imagetagmutability | IMMUTABLE | Prevents tag overwrites |
| scanonpush | true | Vulnerability scanning on push |
| encryption_type | KMS | Server-side encryption |
| deletionwindowin_days | 7 | KMS key deletion window |
| enablekeyrotation | true | Automatic key rotation |
Repository Policy and Lifecycle Policy
Repository Policy
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"
]
}
]
})
}
The policy restricts pull access to specified AWS account ARNs.
Lifecycle Policy
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 defines rules for retention, in the example keeping last 30 production images with tagPrefixList prod.
Terraform Workflow for ECR
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.
Step 3: Initialize Terraform
Set up Terraform in your working directory.
terraform init
Step 4: Format the Terraform Code
Clean up the Terraform files optional but recommended:
terraform fmt
Step 5: Prepare the Docker Image and Push to ECR
If you haven’t pushed your app image to ECR yet, Check for ecr_push.sh in scripts folder and run the commands
This script will:
- Build the Docker image
- Tag it with your ECR repo URL
- Push the image to ECR
Already have an image in ECR? You can skip this step.
Final Checks Before You Deploy
The workflow ensures the repository is created, policy applied, and images pushed in a repeatable manner.
Terraform will show the resource being adopted into state with no changes if your configuration matches the live resource, or a diff if it doesn’t.
Run terraform apply to perform the import. Once the apply succeeds, you can remove the import block from your configuration — it’s only needed for the initial import.
Modules for Reusable ECR Configuration
If you plan to create multiple ECR repositories with similar configurations, you should consider using Terraform modules for reusability best practice.
Modules allow you to define the ECR repository configuration once and reuse it for multiple repositories with minor adjustments. Centralizing configuration in a module makes it easier to manage and update the code for all ECR repositories. Modules also promote code organization and separation between core infrastructure and specific resource configurations.
You can use a public or private module for this. Public modules offer a quick starting point, while private modules provide greater control and customization.
If you prefer to develop a private module:
- Create a separate directory for your module code e.g., modules/ecr
- Inside the directory, create a file named main.tf containing the awsecrrepository resource definition with desired configuration options
- Optionally, create a variables.tf file to define variables that can be customized when using the module
Automate Terraform Deployments with Spacelift
Automate your infrastructure provisioning, build more complex workflows based on Terraform using policy as code, programmatic configuration, context sharing, drift detection, resource visualization, and many more.
Operational Notes and Integration
Amazon Elastic Container Registry is a managed container image registry service provided by AWS, used to store, manage, and deploy Docker container images.
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.
ECR integrates with services like ECS, EKS, and CodeBuild, allowing secure, scalable image storage without managing your own registry.
The Terraform configuration can be extended to define repository policies, lifecycle policies, KMS encryption, and tagging consistently across environments. This supports repeatable, version-controlled deployments and reduces manual error.
Conclusion
Managing Amazon ECR with Terraform provides a declarative, auditable approach to container image storage. Defining the AWS provider, awsecrrepository, awskmskey, awsecrrepositorypolicy, and awsecrlifecyclepolicy in HCL allows infrastructure to be versioned alongside application code. Prerequisites such as AWS CLI configured, Terraform installed, Docker installed locally, and container images to store remain essential for a working setup. Project structure with main.tf, variables.tf, outputs.tf, and terraform.tfvars keeps configuration organized. Modules enable reuse across multiple repositories, while import workflows and drift detection support adoption of existing resources. With ECR backed by S3 for durability and integration with ECS, EKS, and CodeBuild for deployment, Terraform codifies the desired state and enforces consistent security, encryption, and lifecycle management without manual console operations.