是否可以从 Cloud Build 步骤启动 PubSub 模拟器

Is it possible to start PubSub Emulator from Cloud Build step

如标题所述,我想知道是否可以从 Cloud Build 步骤开始并使用 pubsub 模拟器?

options:
  env:
    - GO111MODULE=on
    - GOPROXY=https://proxy.golang.org
    - PUBSUB_EMULATOR_HOST=localhost:8085
  volumes:
    - name: "go-modules"
      path: "/go"

steps:
  - name: "golang:1.14"
    args: ["go", "build", "."]

  # Starts the cloud pubsub emulator
  - name: 'gcr.io/cloud-builders/gcloud'
    entrypoint: 'bash'
    args: [
      '-c',
      'gcloud beta emulators pubsub start --host-port 0.0.0.0:8085 &'
    ]

  - name: "golang:1.14"
    args: ["go", "test", "./..."]

为了测试我需要它,它在本地工作,而不是使用来自云构建的专用 pubsub,我想使用模拟器。

谢谢

这是可能的,因为 Cloud Build 上的每个步骤都是在 docker 容器中执行的,但是映像 gcr.io/cloud-builders/gcloud 只有 gcloud 组件的最小安装,在启动模拟器之前,您需要通过 gcloud 命令安装 pubsub 模拟器

gcloud components install pubsub-emulator

还需要安装 Open JDK7,因为大多数 Gcloud 模拟器需要 java 才能运行。

因为我找到了解决方法和 interesting git repository,所以我想与您分享解决方案。

根据需要,您需要一个 cloud-build.yaml 并且您想要添加一个启动模拟器的步骤:

options:
  env:
    - GO111MODULE=on
    - GOPROXY=https://proxy.golang.org
    - PUBSUB_EMULATOR_HOST=localhost:8085
  volumes:
    - name: "go-modules"
      path: "/go"

steps:
  - name: "golang:1.14"
    args: ["go", "build", "."]

  - name: 'docker/compose'
    args: [
        '-f',
        'docker-compose.cloud-build.yml',
        'up',
        '--build',
        '-d'
    ]
    id: 'pubsub-emulator-docker-compose'

  - name: "golang:1.14"
    args: ["go", "test", "./..."]

如您所见,我 运行 一个 docker-compose 命令将实际启动模拟器。

version: "3.7"

services:
  pubsub:
    # Required for cloudbuild network access (when external access is required)
    container_name: pubsub
    image: google/cloud-sdk
    ports:
      - '8085:8085'
    command: ["gcloud", "beta", "emulators", "pubsub", "start", "--host-port", "0.0.0.0:8085"]
    network_mode: cloudbuild

networks:
  default:
    external:
      name: cloudbuild

设置容器名称和网络很重要,否则您将无法从另一个云构建步骤访问 pubsub 模拟器。