I’ve wanted to simplify the deployment of the infrastructure by eliminating the need to manually push the image to the created ECR repository as the code for the image was in the same repository as IaC.

variable "force_rebuild_push_docker_image" {
  description = "Whether to force rebuild and push the docker image to ECR on Terraform apply command with a local provisioner."
  type        = bool
  default     = false
}
 
locals {
  ecr_reg                         = "${data.aws_caller_identity.current.account_id}.dkr.ecr.${local.aws_region}.amazonaws.com"
  scanner_dkr_img_src_path        = "../../../src/services/antivirus/scanner"
  scanner_dkr_img_src_sha256      = sha256(join("", [for f in fileset(".", "${local.scanner_dkr_img_src_path}/**") : filesha256(f)]))
}
 
 
resource "aws_ecr_repository" "scanner" {
  name                 = "${local.name_prefix}-scanner"
  image_tag_mutability = "MUTABLE"
  force_delete         = true
}
 
resource "null_resource" "build_push_docker_image" {
  count = var.build_push_docker_image ? 1 : 0
 
  provisioner "local-exec" {
    command = <<-EOT
        cd ${local.scanner_dkr_img_src_path}
        docker build -t ${local.ecr_reg}/${aws_ecr_repository.scanner.name}:latest .
        aws ecr get-login-password --region ${local.aws_region} | docker login --username AWS --password-stdin ${local.ecr_reg}
        docker push ${local.ecr_reg}/${aws_ecr_repository.scanner.name}:latest
    EOT
  }
 
  triggers = {
    detect_docker_source_changes = local.scanner_dkr_img_src_sha256
  }
 
  depends_on = [
    aws_ecr_repository.scanner
  ]
}