šŸ¶
Terraform

Deploy Docker Image to ECR with Terraform

By Ondřej DolanskĆ½ on 01/01/2025

Learn how to seamlessly push your Docker images to Amazon Elastic Container Registry (ECR) using the power and automation of Terraform.

Deploy Docker Image to ECR with Terraform

Table of Contents

Introduction

This guide provides a step-by-step approach to building and deploying Docker images to Amazon Elastic Container Registry (ECR) using Terraform. We will cover creating an ECR repository, configuring AWS credentials, building and tagging Docker images, pushing images to ECR, and referencing them in your Terraform code.

Step-by-Step Guide

  1. Define ECR repository:

    resource "aws_ecr_repository" "example" {
      name = "my-repo"
    }
  2. Configure AWS credentials: Ensure your Terraform environment has access to your AWS account.

  3. Build the Docker image: Use the Docker CLI or a tool like Docker Compose.

    docker build -t my-image:latest .
  4. Authenticate to ECR: Retrieve an authentication token and log in to your ECR registry using the AWS CLI.

    aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin <account_id>.dkr.ecr.us-east-1.amazonaws.com
  5. Tag the image: Tag your Docker image with the ECR repository URI.

    docker tag my-image:latest <account_id>.dkr.ecr.us-east-1.amazonaws.com/my-repo:latest
  6. Push the image: Push the tagged image to your ECR repository.

    docker push <account_id>.dkr.ecr.us-east-1.amazonaws.com/my-repo:latest
  7. Reference the image in your Terraform code: Use the image argument in your ECS task definition or other relevant resources.

    resource "aws_ecs_task_definition" "example" {
      # ...
      container_definitions = <<EOF
      [
        {
          "name": "my-container",
          "image": "${aws_ecr_repository.example.repository_url}:latest"
        }
      ]
      EOF
    }

Code Example

This code provides a complete example of deploying a Docker image to Amazon ECR and using it in an ECS task definition. It includes Terraform code to define an ECR repository and an ECS task definition that references the Docker image. A Dockerfile builds a simple web server using Nginx, and a bash script builds, tags, and pushes the Docker image to the ECR repository. The example demonstrates a basic setup that can be expanded with features like automated deployments, environment variables, service discovery, and load balancing.

This example demonstrates the entire process, from defining an ECR repository to referencing the pushed image in an ECS task definition.

1. Terraform Code (main.tf):

# Configure the AWS Provider
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
}

provider "aws" {
  region = "us-east-1" # Replace with your desired region
}

# Define ECR Repository
resource "aws_ecr_repository" "example" {
  name = "my-repo"
}

# Define ECS Task Definition
resource "aws_ecs_task_definition" "example" {
  family = "my-app"
  container_definitions = <<EOF
[
  {
    "name": "my-container",
    "image": "${aws_ecr_repository.example.repository_url}:latest",
    "portMappings": [
      {
        "containerPort": 80,
        "hostPort": 80
      }
    ],
    "essential": true,
    "memory": 512
  }
]
EOF

  requires_compatibilities = ["FARGATE"]
  cpu                      = "256"
  memory                   = "512"
  network_mode             = "awsvpc"
}

2. Dockerfile (Dockerfile):

FROM nginx:latest

# Add your application code here
COPY . /usr/share/nginx/html

3. Build and Push Script (build-and-push.sh):

#!/bin/bash

# Replace with your AWS account ID and region
AWS_ACCOUNT_ID=<your_account_id>
AWS_REGION=us-east-1

# Build the Docker image
docker build -t my-image:latest .

# Authenticate to ECR
aws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com

# Tag the image
docker tag my-image:latest $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/my-repo:latest

# Push the image
docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/my-repo:latest

echo "Image pushed successfully!"

Steps:

  1. Configure AWS Credentials: Ensure your Terraform environment and local machine have access to your AWS account.
  2. Create the necessary files: Create main.tf, Dockerfile, and build-and-push.sh files.
  3. Update placeholders: Replace <your_account_id> and us-east-1 with your actual AWS account ID and desired region.
  4. Build and push the image: Run chmod +x build-and-push.sh and then ./build-and-push.sh.
  5. Deploy with Terraform: Run terraform init, terraform plan, and terraform apply to deploy your infrastructure.

This example showcases a basic setup. You can expand it further by adding features like:

  • Automated deployments: Integrate with CI/CD pipelines for automatic image building and deployment.
  • Environment variables: Pass environment variables to your Docker container through the task definition.
  • Service discovery: Configure service discovery for your application to communicate with other services.
  • Load balancing: Set up load balancing for high availability and scalability.

Additional Notes

1. ECR Repository:

  • Think of an ECR repository like a "Docker Hub" within your own AWS account, offering a private and secure place to store your Docker images.
  • The aws_ecr_repository resource in Terraform simplifies the creation process.
  • Beyond the basic name attribute, you can customize repositories with policies for access control, lifecycle rules for image management, and image scanning settings for security.

2. AWS Credentials:

  • Terraform needs access to your AWS account to interact with services like ECR.
  • The recommended way is to use AWS access keys (access key ID and secret access key) associated with an IAM user having appropriate permissions.
  • Security Best Practice: Avoid hardcoding credentials directly in your Terraform code. Instead, leverage environment variables, the AWS shared credentials file, or IAM roles for more secure management.

3. Building the Docker Image:

  • The docker build command uses your Dockerfile as a blueprint to create the image.
  • The -t flag assigns a tag (name:version) to your image for easy identification.
  • Ensure your Dockerfile includes all necessary dependencies, configurations, and application code for your containerized application.

4. Authenticating to ECR:

  • ECR requires authentication to push and pull images.
  • The provided AWS CLI command fetches a temporary login token and uses it to authenticate your Docker client to your ECR registry.
  • This authentication usually lasts for 12 hours, after which you'll need to re-authenticate.

5. Tagging the Image:

  • Tagging creates an alias for your Docker image, making it easier to reference and manage within ECR.
  • The tag structure typically includes the ECR repository URI and a version identifier (e.g., latest, v1.0, etc.).

6. Pushing the Image:

  • The docker push command uploads your tagged image to the specified ECR repository.
  • Ensure you have a stable internet connection, as image sizes can vary.

7. Referencing the Image in Terraform:

  • Once pushed, you can reference your ECR image in various Terraform resources, such as ECS task definitions, AWS Lambda functions, or AWS Batch jobs.
  • Terraform interpolates the repository_url attribute from the aws_ecr_repository resource to construct the complete image URI.

Additional Tips:

  • Automation: Integrate these steps into your CI/CD pipeline for automated image building, tagging, pushing, and deployment.
  • Image Scanning: Enable ECR image scanning to detect vulnerabilities in your Docker images early in the development lifecycle.
  • Lifecycle Policies: Implement lifecycle policies to automatically manage image versions and optimize storage costs in your ECR repositories.

Summary

This guide outlines the process of pushing a Docker image to an Amazon Elastic Container Registry (ECR) repository using Terraform and the Docker CLI.

Steps:

  1. Create ECR Repository: Define an ECR repository using Terraform (aws_ecr_repository resource).
  2. Configure AWS Credentials: Ensure your Terraform environment can access your AWS account.
  3. Build Docker Image: Build your Docker image locally using docker build.
  4. Authenticate to ECR: Use aws ecr get-login-password and docker login to authenticate with your ECR registry.
  5. Tag Docker Image: Tag your image with the ECR repository URI using docker tag.
  6. Push Docker Image: Push the tagged image to your ECR repository using docker push.
  7. Reference Image in Terraform: Use the repository_url attribute from the aws_ecr_repository resource to reference the image within your Terraform code (e.g., in an ECS task definition).

Key Points:

  • This process utilizes both Terraform and the Docker CLI.
  • Authentication with ECR is crucial before pushing the image.
  • The repository_url attribute dynamically references the ECR repository within your Terraform code.

This approach streamlines the deployment of Docker images to ECR, enabling efficient containerized application deployments.

Conclusion

By following these steps, you can efficiently build, deploy, and manage Dockerized applications on AWS, leveraging the power of infrastructure as code with Terraform and the convenience of ECR as a private container registry. This approach enhances development workflows, promotes automation, and ensures secure and scalable container deployments within your AWS environment.

References

Were You Able to Follow the Instructions?

šŸ˜Love it!
šŸ˜ŠYes
šŸ˜Meh-gical
šŸ˜žNo
šŸ¤®Clickbait