Introduction Link to this heading

Amazon Elastic Container Registry (ECR) is a fully managed Docker container registry that makes it easy to store, manage, and deploy container images. Terraform, an Infrastructure as Code (IaC) tool, allows you to define and provision AWS infrastructure resources like ECR repositories. In this comprehensive guide, I will walk you through the process of using Terraform to set up and manage ECR repositories, covering essential features such as image scanning, image tag mutability, encryption, lifecycle policies, replication, registry scanning configuration and signing.

Prerequisites Link to this heading

  • Before we begin, ensure that you have the following prerequisites in place:
    • An AWS account with appropriate permissions.
    • Terraform installed on your local machine.
    • AWS CLI installed and configured with your AWS credentials.

Step 1: Initialize Your Terraform Project Link to this heading

  • Create a new directory for your project and initialize Terraform:
bash
1 mkdir learningecr
2 cd learningecr

Step 2: Define Your AWS Provider Configuration Link to this heading

  • Create a file called main.tf and specify your AWS provider configuration: hcl
    1provider "aws" {
    2region = "eu-west-1" # Change to your preferred region
    3}

Step 3: Create an ECR Repository with image tag mutability enabled Link to this heading

  • Create a file called ecr.tf file and define the terraform resources for ecr repository
  • below code creates an ECR repository named “firstecrrepo”
  • Image Tag Mutability Feature ECR allows control over image tag mutability to prevent accidental or unauthorized updates.
hcl
1resource "aws_ecr_repository" "learning_ecr_repo" {
2 name = "firstecrrepo"
3 image_tag_mutability = true
4}

Step 4: Enable Image Scanning Link to this heading

  • To enable image scanning on push, modify the ECR repository resource:
  • Image scanning helps identify vulnerabilities in your container images
  • Best Practice: Enable automated image scanning for your repositories. Set up Amazon CloudWatch Events to trigger alerts or actions upon the discovery of vulnerabilities.
hcl
1resource "aws_ecr_repository" "learning_ecr_repo" {
2 name = "firstecrrepo"
3 image_scanning_configuration {
4   scan_on_push = true
5 }
6}

Step 5: Configure Encryption Link to this heading

  • To configure encryption for your ECR repository, add encryption settings:
  • Below code enables encryption of the repository using a KMS key
  • Best Practice: Always enable encryption for your ECR repositories. Utilize AWS KMS to manage and control access to encryption keys.
hcl
 1resource "aws_ecr_repository" "learning_ecr_repo" {
 2  name = "firstecrrepo"
 3
 4  encryption_configuration {
 5    encryption_type = "KMS"
 6    kms_key        = aws_kms_key.ecr_kms_key.id
 7  }
 8}
 9
10resource "aws_kms_key" "ecr_kms_key" {
11  description = "ECR encryption key"
12  deletion_window_in_days = 30
13}

Step 6: Define Lifecycle Policies Link to this heading

  • To set up image lifecycle policies, you can add them to your ECR repository resource:
  • below policy retains the last 30 images in the repository.
  • helps to automatically clean up old and unused images
  • Best Practice: Implement lifecycle policies to expire and delete outdated images regularly. Consider retaining a certain number of most recent images for rollbacks and debugging.
hcl
 1
 2resource "aws_ecr_repository" "my_ecr_repo" {
 3  name = "firstecrrepo"
 4
 5  lifecycle_policy {
 6    policy_text = <<-POLICY
 7      {
 8        "rules": [
 9          {
10            "rulePriority": 1,
11            "description": "Keep last 30 images",
12            "selection": {
13              "tagStatus": "any",
14              "countType": "imageCountMoreThan",
15              "countNumber": 30
16            },
17            "action": {
18              "type": "expire"
19            }
20          }
21        ]
22      }
23    POLICY
24  }
25}

Step 7: Enable Replication Link to this heading

  • To enable replication of your ECR repository to other regions, add replication settings:
  • helps in improving the availability and resilience of container images
  • Below code configures replication to the “eu-west-2” region.
  • Best Practice: Create replicas of critical repositories in multiple regions to enhance availability and reduce latency for users in different geographic locations.
hcl
 1
 2resource "aws_ecr_replication_configuration" "learningecr_replication" {
 3  replication_configuration {
 4    rules {
 5      destination {
 6        region = "eu-west-2" # Change to your target region
 7      }
 8    }
 9  }
10}

Step 8: Signing Images Link to this heading

  • For image signing, create a signing profile and associate it with your repository:
  • Below code sets up image signing with a signing profile named “learningecr-signing-profile”.
  • Best Practice: Sign your container images using tools like AWS Signer or COSIGN and verify them before deployment to ensure authenticity and integrity.
hcl
 1
 2resource "aws_signer_signing_profile" "learning_signing_profile" {
 3  profile_name = "learningecr-signing-profile"
 4}
 5
 6resource "aws_ecr_repository" "learning_ecr_repo" {
 7  name = "firstecrrepo"
 8
 9  image_signing_configuration {
10    signing_profiles = [aws_signer_signing_profile.learning_signing_profile.profile_name]
11  }
12}

9. Registry Scanning Configuration Link to this heading

  • AWS ECR Registry Scanning continuously monitors your ECR registry for security vulnerabilities and integrates with AWS Security Hub.
  • Best Practice: Enable AWS ECR Registry Scanning for your ECR registries. Configure findings to be forwarded to AWS Security Hub for centralized monitoring and response.
hcl
 1
 2resource "aws_ecr_registry_scanning_configuration" "configuration" {
 3  scan_type = "ENHANCED"
 4
 5  rule {
 6    scan_frequency = "CONTINUOUS_SCAN"
 7    repository_filter {
 8      filter      = "example"
 9      filter_type = "WILDCARD"
10    }
11  }
12}

10. Cross-Account Access Link to this heading

  • When working in a multi-account environment, you might need to grant access to ECR repositories from different AWS accounts.
  • Best Practice: Is to pull images from a centralized ECR repository is a best practice that enhances security, reliability, and operational efficiency in containerized environments.
hcl
 1
 2resource "aws_ecr_repository_policy" "cross_account_policy" {
 3  repository = aws_ecr_repository.learning_ecr_repo.name
 4
 5  policy = jsonencode({
 6    Version = "2008-10-17",
 7    Statement = [
 8      {
 9        Action = ["ecr:GetDownloadUrlForLayer",
10          "ecr:BatchCheckLayerAvailability",
11          "ecr:GetRepositoryPolicy",
12          "ecr:ListImages",
13          "ecr:GetLifecyclePolicy",
14          "ecr:GetLifecyclePolicyPreview",
15          "ecr:PutImage",
16          "ecr:PutImageScanningConfiguration",
17          "ecr:StartImageScan",
18          "ecr:BatchGetImage"
19        ]
20        Effect = "Allow",
21        Principal = {
22          AWS = "arn:aws:iam::123456789012:root"  # Replace with the target AWS account ID
23        }
24      }
25    ]
26  })
27}

Step 11: Initialize and Apply Terraform Configuration Link to this heading

  • After defining all the necessary configurations, initialize and apply the Terraform configuration:
bash
1   terraform init
2   terraform apply

Conclusion Link to this heading

In this step-by-step guide, you have learned how to use Terraform to manage Amazon ECR repositories, including enabling features like image scanning, encryption, lifecycle policies, replication, and image signing. Terraform automates the provisioning and management of container image repositories, making containerized applications more secure and efficient.

Happy Container Image Management🐳🛠️🚀!