本指南介绍如何设置 Binary Authorization 以对 Cloud Run 服务强制执行基于政策的部署。
准备工作
执行以下操作,以设置 Cloud Run 并启用 API:
- 登录您的 Google Cloud 帐号。如果您是 Google Cloud 新手,请创建一个帐号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
-
在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目。
-
确保您的 Cloud 项目已启用结算功能。了解如何检查项目是否已启用结算功能。
-
启用 Cloud Run, Artifact Registry, Binary Authorization API。
- 安装 Google Cloud CLI。
-
如需初始化 gcloud CLI,请运行以下命令:
gcloud init
-
在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目。
-
确保您的 Cloud 项目已启用结算功能。了解如何检查项目是否已启用结算功能。
-
启用 Cloud Run, Artifact Registry, Binary Authorization API。
- 安装 Google Cloud CLI。
-
如需初始化 gcloud CLI,请运行以下命令:
gcloud init
在现有 Cloud Run 服务中启用 Binary Authorization
本部分介绍如何在现有服务上启用 Binary Authorization 强制执行。
如需在现有服务上启用 Binary Authorization 强制执行,请执行以下操作:
控制台
转到 Google Cloud 控制台中的“Cloud Run”页面。
点击相应服务的名称。
点击详情标签页。
如需对该服务启用 Binary Authorization 强制执行,请点击启用。
可选:如需配置 Binary Authorization 政策,请点击配置政策。
gcloud
运行以下命令:
gcloud run services update SERVICE_NAME --binary-authorization=default
将 SERVICE_NAME 替换为您的服务的名称。
YAML
您可以使用 gcloud run services describe --format export
命令下载并查看现有服务配置,该命令会生成清理后的 YAML 格式的结果。然后按照后续说明修改字段,最后使用 gcloud run services replace
命令上传修改后的 YAML。请务必严格按照说明修改字段。
如需查看和下载配置,请运行以下命令:
gcloud run services describe SERVICE --format export > service.yaml
按如下所示的方式更新
run.googleapis.com/ingress:
注释:apiVersion: serving.knative.dev/v1 kind: Service metadata: annotations: run.googleapis.com/binary-authorization: POLICY name: SERVICE spec: template:
请替换以下内容:
- SERVICE:Cloud Run 的名称
- POLICY:设置为
default
使用以下命令将服务替换为其新配置:
gcloud run services replace service.yaml
查看政策
如需查看政策,请点击查看政策。
详细了解如何配置 Binary Authorization 政策。
服务部署失败
如果您的服务因违反 Binary Authorization 政策而无法部署,您可能会看到如下错误:
Revision REVISION_NAME uses an unauthorized container image. Container image IMAGE_NAME is not authorized by policy.
此错误还包含有关映像为何违反政策的信息。在这种情况下,您可以使用 Breakglass 绕过政策强制执行并部署映像。
在新服务中启用 Binary Authorization
如需在新服务中启用 Binary Authorization,请执行以下操作:
控制台
转到 Cloud Run 页面:
点击创建服务。在随即显示的“创建服务”表单中执行以下操作:
- 选择 Cloud Run 作为开发平台。
- 选择您希望自己的服务所在的区域。
- 输入服务名称。
- 点击下一步以继续转到“配置服务的第一个修订版本”页面。
- 选择从现有容器映像部署一个修订版本。
- 输入或选择要部署的映像。
- 展开高级设置部分。
- 点击安全标签。
选中使用 Binary Authorization 验证容器部署复选框。
可选:点击配置政策以配置 Binary Authorization 政策。如需详细了解如何配置政策,请参阅配置政策
部署该服务。
gcloud
运行以下命令:
gcloud run deploy SERVICE_NAME --image=IMAGE_URL --binary-authorization=default --region=REGION
替换以下内容:
- SERVICE_NAME:服务的名称。
- IMAGE_URL:要部署的映像。
- REGION:要在其中部署服务的区域。
YAML
使用以下内容创建新的
service.yaml
文件:apiVersion: serving.knative.dev/v1 kind: Service metadata: name: SERVICE annotations: run.googleapis.com/binary-authorization: POLICY spec: template: spec: containers: - image: IMAGE
请替换以下内容:
- SERVICE:Cloud Run 的名称
- IMAGE:容器映像的网址。
- POLICY:设置为
default
使用以下命令部署新服务:
gcloud run services replace service.yaml
后续步骤
- 使用
built-by-cloud-build
证明者仅部署由 Cloud Build 构建的映像(预览版)。 - 使用 Google Cloud 控制台或命令行工具配置 Binary Authorization 政策。
- 通过使用证明来仅部署已签名的容器映像。
- 使用 Google Cloud 控制台或命令行工具配置 Binary Authorization 政策