Search code examples
kubernetesterraformibm-cloudterraform-provider-ibm

IBM Cloud: Access container registry from Terraform


I am using IBM Cloud and its Terraform provider. Now, I would like to deploy a container image off the IBM Cloud Container Registry and need to provide pull secrets. How can I do that using Terraform?


Solution

  • Creating pull secrets via Terraform and then using them to pull a container image off the IBM Cloud Container Registry is possible with some configuration.

    First, I have a template file for the Docker configuration named docker_config.json:

    {"auths":{"${docker-server}":{"username":"${docker-username}","password":"${docker-password}","email":"${docker-email}","auth":"${auth}"}}}
    

    That file is referenced from the Terraform code:

    # template for container registry secrets
    data "template_file" "docker_config_script" {
      template = file("${path.module}/docker_config.json")
      vars = {
        docker-username = "iamapikey"
        docker-password = var.ibmcloud_api_key
        docker-server   = var.docker-server
        docker-email    = var.docker-email
        auth            = base64encode("iamapikey:${var.ibmcloud_api_key}")
      }
    }
    
    # Create secrets to access IBM Container Registry to pull container image
    resource "kubernetes_secret" "registry_secrets" {
      metadata {
        name      = "my-docker-registry"
        namespace = var.iks_namespace
      }
    
      data = {
        ".dockerconfigjson" = data.template_file.docker_config_script.rendered
      }
    
      type = "kubernetes.io/dockerconfigjson"
    }
    

    The above code first reads the template and fills it with values from environment variables or current state. Thereafter, it creates a Kubernetes secret my-docker-registry of type Docker configuration. Later on, that secret can be referenced as image_pull_secret in the deployment configuration.

    The above is a generic approach. Depending on your account setup, individual user and service ID privileges in that account and how the Kubernetes cluster was created, you may be able to use a pre-created pull secret. See this part in the IBM Cloud Kubernetes Service docs on how to authorize pulling images from private registries.