Home > Enterprise >  Use terraform to push docker image to azure container registry
Use terraform to push docker image to azure container registry

Time:10-10

I am using terraform to provision the infrastructure for my project in Azure.

Part of the infrastructure is a container registry to store the docker images that will be used by kubernates. Since at the moment everything is provisioned using terraform I am trying to build and push the images too. I found the kreuzwerker/docker provider that maybe can do the job.

For the moment I have this code:

provider "docker" {
  registry_auth {
    address  = azurerm_container_registry.example.login_server
    username = azurerm_container_registry.example.admin_username
    password = azurerm_container_registry.example.admin_password
  }
}

resource "docker_registry_image" "example" {
  name          = "example"
  keep_remotely = false

  build {
    context    = path.cwd
    dockerfile = "Dockerfile"
  }
}

It seems like the image has been build but when it comes to push it to the registry I get this error:

╷
│ Error: resourceDockerRegistryImageCreate: Unable to get authConfig for registry: no auth config found for registry registry-1.docker.io in auth configs: map[string]types.AuthConfig{"***.azurecr.io":types.AuthConfig{Username:"***", Password:"***", Auth:"", Email:"", ServerAddress:"https://***.azurecr.io", IdentityToken:"", RegistryToken:""}}
│ 
│   with docker_registry_image.backend,
│   on docker.tf line 1, in resource "docker_registry_image" "backend":
│    1: resource "docker_registry_image" "backend" {
│ 
╵

I think it's trying to push to registry-1.docker.io but that's not the correct registry. So I tried

provider "docker" {
  host = azurerm_container_registry.example.login_server

  registry_auth {
    address  = azurerm_container_registry.example.login_server
    username = azurerm_container_registry.example.admin_username
    password = azurerm_container_registry.example.admin_password
  }
}

But then I get this error:

╷
│ Error: Error initializing Docker client: unable to parse docker host `***.azurecr.io`
│ 
│   with provider["registry.terraform.io/kreuzwerker/docker"],
│   on provider.tf line 8, in provider "docker":
│    8: provider "docker" {
│ 
╵

How can I use this provider to push the image to the correct ACR?

CodePudding user response:

For docker images, the name if the image actually defines which registry will be used to push the image to (or fetch it from). So when you define the image name to be example, it will by default go to DockerHub.

In order to send the image to your own registry, wherever that may be, the registry domain must be prepended to the image name, as desrcibed here.

In an example taken from the link above, mcr.microsoft.com/oss/nginx/nginx:1.15.5-alpine would be pushed to the registry mcr.microsoft.com instead of DockerHub.

  • Related