首页 > 解决方案 > 是否可以在不实际部署映像的情况下在 GCE 上配置容器优化的 OS VM?

问题描述

我想构建一个 CI 管道,在将 Dockerized 应用程序上传到 Artifact Registry 并首次部署之前,基础设施阶段使用 Terraform 在 Google Compute Engine 上提供容器优化的操作系统实例。

我的 Terraform 配置:

data "google_compute_image" "cos" {
  family  = "cos-stable"
  project = "cos-cloud"
}

resource "google_compute_instance" "container_optimized_os_vm" {
  name                      = "container-optimized-os-vm"
  machine_type              = "f1-micro"
  allow_stopping_for_update = true

  network_interface {
    network = "default"
  }

  boot_disk {
    initialize_params {
      image = data.google_compute_image.cos.self_link
    }
  }

  metadata = {
    google-logging-enabled = "true"
    gce-container-declaration =<<EOT
spec:
  containers:
    - image: image-repository/image-name:latest
      name: containervm
      securityContext:
        privileged: false
      stdin: false
      tty: false
      volumeMounts: []
      restartPolicy: Always
      volumes: []
EOT
  }
}

我从 Artifact Registry 部署最新版本图像的命令:

gcloud compute instances update-container container-optimized-os-vm \
            --zone europe-west2-b \
            --container-image "europe-west2-docker.pkg.dev/my-project-id/my-image-repository-name/my-image-name:latest"

当我省略gce-container-declaration元数据时,我收到以下错误:

ERROR: (gcloud.compute.instances.update-container) Instance doesn't have gce-container-declaration metadata key - it is not a container.

我希望能够在不指定图像的情况下配置实例gce-container-declaration——这可能吗?我担心的是,当检测到基础架构更改时,gce-container-declaration将部署其中的图像而不是我的应用程序的图像。

标签: dockergoogle-cloud-platformterraformgoogle-compute-enginegoogle-artifact-registry

解决方案


需要明确的是,容器优化操作系统用于运行 Docker 容器,这意味着您的 VM 实例被创建为 Docker 容器,并且您的容器化应用程序将在其之上运行,如以下文档 [1] 中所述。

现在,gce-container-declaration参数是容器的清单,您可以在其中指定容器化应用程序(包括图像)所需的所有参数。

gcloud compute instances update-container使用您的应用程序映像路径作为 --container-image 标志运行命令只会将部署的原始容器映像从 更改image-repository/image-name:latesteurope-west2-docker.pkg.dev/my-project-id/my-image-repository-name/my-image-name:latest,与您最初可以指定的相同:

 metadata = {
    google-logging-enabled = "true"
    gce-container-declaration =<<EOT
spec:
  containers:
    - image: europe-west2-docker.pkg.dev/my-project-id/my-image-repository-name/my-image-name:latest
      name: containervm
      securityContext:
        privileged: false
      stdin: false
      tty: false
      volumeMounts: []
      restartPolicy: Always
      volumes: []
EOT
  }

您得到的错误是因为一旦您取出gce-container-declaration标志,VM 实例就不再创建为容器,而只是一个普通的 VM;因此错误。

当两者都可以并行完成时,我不明白为什么要创建 VM 实例以稍后部署您的应用程序,实际上提供的 terraform 代码就是这样工作的。

[1] https://cloud.google.com/container-optimized-os/docs/concepts/features-and-benefits


推荐阅读