Skip to content

Create AWS ECR Repository with Terraform

Terraform Project Structure

.
├── dev-ecr
│   ├── backend.tf
│   ├── ecr.tf
│   ├── variables.auto.tfvars
│   └── variables.tf
└── modules
    └── ecr
        ├── data.tf
        ├── main.tf
        └── variables.tf

4 directories, 7 files

modules

data.tf

data "aws_caller_identity" "current" {}

main.tf

resource "aws_ecr_repository" "ecr" {
  for_each             = toset(var.ecr_name)
  name                 = each.key
  image_tag_mutability = var.image_mutability
  encryption_configuration {
    encryption_type = var.encrypt_type
  }
  image_scanning_configuration {
    scan_on_push = true
  }
  tags = var.tags
}

variables.tf

variable "ecr_name" {
  description = "The name of the ECR registry"
  type        = any
  default     = null
}

variable "image_mutability" {
  description = "Provide image mutability"
  type        = string
  default     = "IMMUTABLE"
}


variable "encrypt_type" {
  description = "Provide type of encryption here"
  type        = string
  default     = "KMS"
}

variable "tags" {
  description = "The key-value maps for tagging"
  type        = map(string)
  default     = {}
}

dev-ecr

backend.tf

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.0"
    }
  }
}

provider "aws" {
  region  = "enter-your-aws-region"
  profile = "enter-your-aws-profile"
}

ecr.tf

module "ecr-repo" {
  source           = "./../modules/ecr"
  ecr_name         = var.ecr_name
  tags             = var.tags
  image_mutability = var.image_mutability

}

variables.tf

variable "ecr_name" {
  description = "The list of ecr names to create"
  type        = list(string)
  default     = null
}
variable "tags" {
  description = "The key-value maps for tagging"
  type        = map(string)
  default     = {}
}
variable "image_mutability" {
  description = "Provide image mutability"
  type        = string
  default     = "MUTABLE"
}

variable "encrypt_type" {
  description = "Provide type of encryption here"
  type        = string
  default     = "KMS"
}

variables.auto.tfvars

tags = {
  "Environment" = "Dev"
}

ecr_name = [
  "demoapp/frontendservice"
]

image_mutability = "IMMUTABLE"

Terraform run

terraform init
terraform plan
terraform apply

Reference

  • https://dev.to/aws-builders/provision-aws-elastic-container-registry-repository-using-terraform-373g
  • https://medium.com/@praveenvallepu/amazon-ecr-repository-with-terraform-3e430369900d
  • https://awstip.com/elastic-container-registry-ecr-terraform-d752753b6ac1
  • https://www.pulumi.com/ai/answers/pCbrsk46e8XF98WnQbyK5H/building-aws-ecr-repositories-with-terraform
Leave a message