IBM Cloud:从 Terraform 访问容器注册表

IBM Cloud: Access container registry from Terraform

我正在使用 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。我如何使用 Terraform 做到这一点?

通过 Terraform 创建 pull secret,然后使用它们从 IBM Cloud Container Registry 拉取容器镜像,这可以通过一些配置实现。

首先,我有一个用于 Docker 配置的模板文件,名为 docker_config.json:

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

Terraform 代码引用了该文件:

# 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"
}

上面的代码首先读取模板并用环境变量或当前状态的值填充它。此后,它创建一个 my-docker-registry 类型 Docker 配置的 Kubernetes 秘密 my-docker-registry。稍后,该秘密可以在部署配置中引用为 image_pull_secret

以上是通用的方法。根据您的帐户设置、该帐户中的个人用户和服务 ID 权限以及 Kubernetes 集群的创建方式,您可以使用 pre-created pull secret。 See this part in the IBM Cloud Kubernetes Service docs on how to authorize pulling images from private registries.

另请记住,您的集群可能已经具有合适的镜像拉取秘密。

默认情况下,新的 IBM Cloud Kubernetes Service 集群会获得一个包含凭据的机密 (all-icr-io),该凭据将授予对与集群相同的帐户所拥有的 IBM Cloud Container Registry 命名空间中所有图像的读取访问权限。 https://cloud.ibm.com/docs/containers?topic=containers-registry#cluster_registry_auth_default

或者,您也可以按照以下步骤导入 IKS 集群附带的现有 pull secret all-icr-io

main.tf

resource "kubernetes_secret" "all_icr_io" {
  # (resource arguments)
}

provider.tf

terraform {
  required_providers {
    kubernetes = {
      source = "hashicorp/kubernetes"
      version = "1.13.2"
    }
  }
}

provider "kubernetes" {
  # Configuration options
}

在终端上:

terraform import kubernetes_secret.all_icr_io default/all-icr-io

确认一下,

terraform show

结果:

# kubernetes_secret.all_icr_io:
resource "kubernetes_secret" "all_icr_io" {
    data = (sensitive value)
    id   = "default/all-icr-io"
    type = "kubernetes.io/dockerconfigjson"

    metadata {
        annotations      = {}
        generation       = 0
        labels           = {}
        name             = "all-icr-io"
        namespace        = "default"
        resource_version = "267"
        self_link        = "/api/v1/namespaces/default/secrets/all-icr-io"
        uid              = "0dea7ee0-ab03-4fc1-a4e4-b2xxxxxxx"
    }
}