'Using a public ECR image in local Kubernetes cluster in Terraform

I've setup a very simple local kubernetes cluster for development purposes, and for that I aim to pull a docker image for my pods from ECR.

Here's the code

   terraform {
      required_providers {
        kubernetes = {
          source  = "hashicorp/kubernetes"
          version = ">= 2.0.0"
        }
      }
    }

    provider "kubernetes" {
        config_path = "~/.kube/config"
    } 

    resource "kubernetes_deployment" "test" {
      metadata {
        name      = "test-deployment"
        namespace = kubernetes_namespace.test.metadata.0.name
      }

      spec {
        replicas = 2
        selector {
          match_labels = {
            app = "MyTestApp"
          }
        }

        template {
          metadata {
            labels = {
              app = "MyTestApp"
            }
          }

          spec {
            container {
              image = "public ECR URL"  <--- this times out
              name  = "myTestPod"
    
              port {
                container_port = 4000
              }
            }
          }
        }
      }
    }

I've set that ECR repo to public and made sure that it's accessible. My challenge is that in a normal scenario you have to login to ECR in order to retrieve the image, and I do not know how to achieve that in Terraform. So on 'terraform apply', it times out and fails.

I read the documentation on aws_ecr_repository, aws_ecr_authorization_token,Terraform EKS module and local-exec, but none of them seem to have a solution for this.

Achieving this in a Gitlab pipeline is fairly easy, but how can one achieve this in Terraform? how can I pull an image from a public ECR repo for my local Kubernetes cluster?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source