LLM_Enthusiast
LLM_Enthusiast

Reputation: 87

Docker image build and push fails when executed via Terraform on AWS ECR

I'm encountering an issue where I am unable to successfully build and push a Docker image to AWS ECR using Terraform. The process seems to execute without errors, but the ECR repository remains empty. I need help understanding what might be going wrong.

Directory Structure:

Terraform code:

resource "aws_ecr_repository" "pvf_stress_test" {
  name = "${random_pet.user.id}-ecr-pvf-stress-test"
  image_scanning_configuration {
    scan_on_push = true
  }
}

resource "null_resource" "docker_packaging" {
  depends_on = [aws_ecr_repository.pvf_stress_test]

  provisioner "local-exec" {
    command = <<EOF
      aws ecr get-login-password --region ${var.region} --profile ${var.account_prefix} | docker login --username AWS --password-stdin ${data.aws_caller_identity.current.account_id}.dkr.ecr.${var.region}.amazonaws.com
      docker build -t "${aws_ecr_repository.pvf_stress_test.name}:latest" -f pvf-stress-tests/Dockerfile pvf-stress-tests
      docker push "${aws_ecr_repository.pvf_stress_test.name}:latest"
    EOF
  }
}

When I run terraform apply, the logs show that all commands are executed without any errors, and it even shows "Login Succeeded" for the Docker login command. However, when I check the AWS ECR repository, it is empty. The logs from Terraform do not show any errors during the Docker build or push commands.

When executing the Docker commands manually from the command line in the same directory where main.tf is located, everything works as expected: the Docker image is built and pushed successfully to ECR.

Attempts to Resolve:

Could someone help me understand why these Docker commands are not working when executed through Terraform? What might I be missing or need to adjust in my Terraform configuration?

Thank you in advance for any insights or assistance!

Upvotes: 0

Views: 320

Answers (1)

LLM_Enthusiast
LLM_Enthusiast

Reputation: 87

I solved the problem by splitting each command line into a local-exec provisioner.

resource "null_resource" "docker_packaging" {

  depends_on = [
    aws_ecr_repository.pvf_stress_test,
  ]
  provisioner "local-exec" {
    command = "aws ecr get-login-password --region ${var.region} --profile ${var.account_prefix} | docker login --username AWS --password-stdin ${data.aws_caller_identity.current.account_id}.dkr.ecr.${var.region}.amazonaws.com"
  }

  provisioner "local-exec" {
    command = "docker build -t "${aws_ecr_repository.pvf_stress_test.name}:latest" -f pvf-stress-tests/Dockerfile pvf-stress-tests"
  }

  provisioner "local-exec" {
    command = "docker push ${data.aws_caller_identity.current.account_id}.dkr.ecr.${var.region}.amazonaws.com/${aws_ecr_repository.pvf_stress_test.name}:latest"
  }

  triggers = {
    "run_at" = timestamp()
  }
  
}

Upvotes: 0

Related Questions