Terraform docker cannot authenticate with container registry for remote host

1.4k Views Asked by At

I am on a Windows machine using Terraform 0.13.4 and trying to spin up some containers on a remote host using Terraform and the Docker provider:

provider "docker" {
  host = "tcp://myvm:2376/"

  registry_auth {
    address = "myregistry:443"
    username = "myusername"
    password = "mypassword"
  }

  ca_material = file(pathexpand(".docker/ca.pem"))
  cert_material = file(pathexpand(".docker/cert.pem"))
  key_material = file(pathexpand(".docker/key.pem"))
}

data "docker_registry_image" "mycontainer" {
  name = "myregistry:443/lvl1/lvl2/myimage:latest"
}

I am having a hard time with this as it cannot authenticate with my private registry. Always getting 401 Unauthorized.

If I don't do this to grab the sha256_digest and just use the docker_container resource, everything works but it forces replacements of the running containers.

2

There are 2 best solutions below

3
On

Hello Angelos if you dont want to force replace the running container you should try this :

provider "docker" {
  host = "tcp://myvm:2376/"

  registry_auth {
    address = "myregistry:443"
    username = "myusername"
    password = "mypassword"
  }

  ca_material = file(pathexpand(".docker/ca.pem"))
  cert_material = file(pathexpand(".docker/cert.pem"))
  key_material = file(pathexpand(".docker/key.pem"))
}
data "docker_registry_image" "mycontainer" {
  name = "myregistry:443/lvl1/lvl2/myimage:latest"
}

resource "docker_image" "example" {
  name = data.docker_registry_image.mycontainer.name
  pull_triggers = [data.docker_registry_image.mycontainer.sha256_digest]
  keep_locally = true
}

then in the container use :

resource "docker_container" "example" {
  image = docker_image.example.latest
  name = "container_name"
   
}

you shoukd use

docker_image.example.latest

Using the resource docker_image itself if it already exist he wont pull the image and doesn't restart the container but if you pass the name as a string he will replace the container everytime.

https://www.terraform.io/docs/providers/docker/r/container.html

0
On

Turns out that the code is correct and that the container service I am using (older version of ProGet) is not replying correctly for the auth calls. I tested the code using another registry and it all works as expected.