Amazon Elastic Container Registry is a fully managed Docker container offering provided by Amazon Web Services. ECR is used to store, manage, and deploy container images. In a cloud computing and microservice world, infrastructure resources must be provisioned with consistency and reproducibility. 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 called HashiCorp Configuration Language or HCL which implies the desired state of infrastructure resources. These resources can include virtual machines, networks, databases, and container registries provided by big top cloud providers such as Amazon Web Services, Microsoft Azure, Google Cloud Platform, and others.
Using Terraform to create an Amazon Elastic Container Registry repository offers several advantages. Infrastructure as Code provides consistency, reproducibility, and version control mechanisms in which infrastructure setup will be provided. Automated Provisioning allows content population and management of ECR repositories with a reduction in human interventions and human error reluctance. Declarative Configuration is used for specifying resources by the means of its configuration file.
What AWS ECR Provides
ECR supports Cross-Region and Cross-Account Replication to replicate images where needed easily. ECR offers a pay-as-you-go pricing model, meaning you only pay for the amount of storage used and the data transferred without upfront costs.
Repositories of ECR may be differentiating for the libraries, each of which contains multiple Docker Images, designated by different tags which represent versions and configurations.
Terraform Workflow for ECR Creation
The steps to creating an ECR repository with Terraform are as follows:
- Install Terraform
- Configure Terraform AWS provider
- Create an ECR repository
- Run terraform init
- Run terraform plan
- Apply your configuration
- Verify the deployment in the AWS console
- Run terraform destroy
This workflow applies to a basic example but the Terraform code can be customized according to specific needs. For instance, you can set repository policies and lifecycle policies or even configure other advanced options.
Install Terraform and Configure the AWS Provider
Make sure you have Terraform installed on your machine. You can download by referring to Terraform Install.
Once you have Terraform installed, it’s time to add some configuration files. Create a new Terraform configuration file, e.g., main.tf.
In this file, you need to define the AWS provider and specify your AWS credentials. An example provider block is:
hcl
provider "aws" {
region = "us-east-1"
access_key = "YOUR_AWS_ACCESS_KEY"
secret_key = "YOUR_AWS_SECRET_KEY"
}
Replace YOURAWSACCESSKEY and YOURAWSSECRETKEY with your actual AWS access key and secret key. Alternatively, you can use environment variables or an AWS credentials file.
Define the ECR Repository Resource
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.
In the same main.tf file, add a resource block to create an ECR repository:
hcl
resource "aws_ecr_repository" "my_ecr_repo" {
name = "my-ecr-repo"
image_tag_mutability = "MUTABLE"
image_scanning_configuration {
scan_on_push = true
}
}
This configuration creates an ECR repository named "my-ecr-repo" with image scanning enabled on push. You can customize the repository name and other settings as needed.
A safer defaults example uses:
hcl
resource "aws_ecr_repository" "my_ecr_repo" {
name = "my-ecr-repo"
image_tag_mutability = "IMMUTABLE"
image_scanning_configuration {
scan_on_push = true
}
}
Setting imagetagmutability = "IMMUTABLE" and scanonpush = true gives you safer defaults out of the box.
From here on, you will be able to push Docker images to this repository or performing other operations as required.
Initialize, Plan and Apply
Open your terminal or command prompt, navigate to the directory containing your main.tf file, and run the following command to initialize Terraform:
bash
terraform init
Step 4: Initialize Terraform
Before applying the configuration, you can review the execution plan by running:
bash
terraform plan
This is the Review the Execution Plan step.
Step 6: Apply the Configuration
If the execution plan looks good, apply the configuration by running:
bash
terraform apply
This command will prompt you to confirm the changes. Type yes to proceed. Terraform will create the ECR repository according to your configuration.
Verification and Cleanup
Step 7: Verify the deployment via the AWS console.
Step 8: Delete the deployment.
You can delete the AWS ECR once it's not required via the following command in the cli:
bash
terraform destroy
That's it! Your Terraform script will now be used to create an ECR Repository. From here on, you will be able to push Docker images to this repository or performing other operations as required.
Lifecycle Policies and Cost Control
Lifecycle policies are important to include when setting up your ECR, so they should be covered in the configuration.
Attach an awsecrlifecycle_policy with a JSON policy to expire old or untagged images and keep storage costs in check.
The policy uses camelCase keys in JSON. A lifecycle policy resource is attached to the repository to manage image retention.
Common lifecycle actions include expiration of untagged images and limiting the number of images retained per tag.
The table below summarizes typical attributes used when defining an ECR repository with Terraform:
| Attribute | Example Value | Purpose |
|---|---|---|
| name | my-ecr-repo | Repository identifier |
| imagetagmutability | IMMUTABLE or MUTABLE | Controls tag mutability |
| imagescanningconfiguration.scanonpush | true | Enables vulnerability scanning on push |
Importing Existing Repositories
In the final example, the AWS ECR Terraform module and its usage will be discussed.
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.
Importing allows existing ECR repositories to be brought into Terraform state without recreation. The import block syntax in Terraform 1.5+ enables this operation.
Practical Considerations
Repositories of ECR may be differentiating for the libraries, each of which contains multiple Docker Images, designated by different tags.
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.
With Terraform, an open source IaC tool that is widely used for provisioning and managing cloud resources across many cloud service providers such as AWS, becoming the de-facto standard, it is not surprising that people have started noticing its advantages over other available options.
Conclusion
Creating an Amazon Elastic Container Registry repository with Terraform aligns container storage with infrastructure as code principles. The awsecrrepository resource provides a declarative way to define repository name, image tag mutability, and scanning configuration. Pairing it with awsecrlifecycle_policy enables cost control through automated expiration of old or untagged images.
The workflow from provider configuration through terraform init, terraform plan, terraform apply, and verification in the AWS console remains consistent across resources. Importing existing repositories with a top-level import block extends Terraform management to previously created infrastructure without disruption.
As container adoption increases, the combination of ECR’s pay-as-you-go pricing, cross-region and cross-account replication, and Terraform’s declarative provisioning delivers reproducible registries that can evolve with application needs while keeping storage costs predictable.