部署功能标志
本快速入门介绍了如何使用 App Lifecycle Manager 创建、发布和使用功能标志。
在本快速入门中,您将学习如何安装和配置标志提供方,以及如何使用 App Lifecycle Manager 功能标志执行基本的功能标志操作。
准备工作
-
登录您的 Google 账号。
如果您还没有 Google 账号,请 注册新账号。
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the App Lifecycle Manager, Artifact Registry, Infrastructure Manager, Developer Connect, Cloud Build, Cloud Storage, Cloud Run and SaaS Config APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.-
Create a service account:
-
Ensure that you have the Create Service Accounts IAM role
(
roles/iam.serviceAccountCreator) and the Project IAM Admin role (roles/resourcemanager.projectIamAdmin). Learn how to grant roles. -
In the Google Cloud console, go to the Create service account page.
Go to Create service account - Select your project.
-
In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.
In the Service account description field, enter a description. For example,
Service account for quickstart. - Click Create and continue.
-
Grant the Project > Owner role to the service account.
To grant the role, find the Select a role list, then select Project > Owner.
- Click Continue.
-
Click Done to finish creating the service account.
-
Ensure that you have the Create Service Accounts IAM role
(
-
安装 Google Cloud CLI。
-
如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI。
-
如需初始化 gcloud CLI,请运行以下命令:
gcloud init -
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the App Lifecycle Manager, Artifact Registry, Infrastructure Manager, Developer Connect, Cloud Build, Cloud Storage, Cloud Run and SaaS Config APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.-
Create a service account:
-
Ensure that you have the Create Service Accounts IAM role
(
roles/iam.serviceAccountCreator) and the Project IAM Admin role (roles/resourcemanager.projectIamAdmin). Learn how to grant roles. -
In the Google Cloud console, go to the Create service account page.
Go to Create service account - Select your project.
-
In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.
In the Service account description field, enter a description. For example,
Service account for quickstart. - Click Create and continue.
-
Grant the Project > Owner role to the service account.
To grant the role, find the Select a role list, then select Project > Owner.
- Click Continue.
-
Click Done to finish creating the service account.
-
Ensure that you have the Create Service Accounts IAM role
(
-
安装 Google Cloud CLI。
-
如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI。
-
如需初始化 gcloud CLI,请运行以下命令:
gcloud init - 创建 SaaS 产品。您需要 SaaS 产品才能完成本快速入门。 如需详细了解如何创建 SaaS 产品,请参阅 创建 SaaS 产品。
向 App Lifecycle Manager 服务帐号授予权限
启用 App Lifecycle Manager API 后,App Lifecycle Manager 会创建一个服务账号。此服务帐号名为
service-PROJECT-NUMBER@gcp-sa-saasservicemgmt.iam.gserviceaccount.com,其中 PROJECT-NUMBER 是您的项目编号。
运行以下命令,向此服务帐号授予所需的权限:
gcloud projects add-iam-policy-binding `PROJECT_ID` \
--member="serviceAccount:service-<var>`PROJECT_NUMBER`</var>@gcp-sa-saasservicemgmt.iam.gserviceaccount.com" \
--role="roles/saasservicemgmt.serviceAgent"
将
- PROJECT_ID:表示项目 ID 的字符串标识符。
- PROJECT_NUMBER:您的项目编号。
查找参考文档
此服务帐号代表您执行各种任务,例如预配单元。
在 Artifact Registry 中创建代码库
如需使用 App Lifecycle Manager,您需要在 Artifact Registry 中拥有一个代码库。如需创建此代码库,请在终端中运行以下命令:
gcloud artifacts repositories create flags-quickstart \
--repository-format=docker \
--location=us-central1
此代码库将包含一个蓝图(打包的 Terraform 文件),用于描述如何预配单元。
创建功能标志应用蓝图
创建一个 Python 脚本,用于读取功能标志并使用该标志构建和推送 Docker 映像:
为 Docker 构建上下文创建一个名为
alm_docker的目录。在
alm_docker目录中,使用以下代码段创建文件flags.py:import google.auth.transport.grpc import google.auth.transport.requests import grpc import logging import time import os import sys from flask import Flask, jsonify from openfeature import api from openfeature.provider import ProviderEvent, ProviderStatus from openfeature.contrib.provider.flagd import FlagdProvider from openfeature.contrib.provider.flagd.config import ResolverType # --- Flask App Setup --- app = Flask(__name__) # --- Logging Setup --- logging.basicConfig(stream=sys.stdout) # Log to stdout for Cloud Run log = logging.getLogger(__name__) log.setLevel(logging.INFO) # Use INFO or DEBUG as needed # --- OpenFeature/Flagd Setup --- FLAG_KEY = "quickstart-flag" DEFAULT_FLAG_VALUE = False # Check for necessary environment variable provider_id = os.environ.get("FLAGD_SOURCE_PROVIDER_ID") if not provider_id: log.critical("FATAL: FLAGD_SOURCE_PROVIDER_ID environment variable not set.") sys.exit("FLAGD_SOURCE_PROVIDER_ID not set") # Exit if critical config is missing log.info(f"Initializing OpenFeature provider for ID: {provider_id}") def add_x_goog_request_params_header(config_name): return lambda context, callback: callback([("x-goog-request-params", f'name={config_name}')], None) try: # Configure gRPC credentials for Google Cloud service configservice_credentials = grpc.composite_channel_credentials( grpc.ssl_channel_credentials(), grpc.metadata_call_credentials( google.auth.transport.grpc.AuthMetadataPlugin( google.auth.default()[0], # Get just the credentials from the tuple google.auth.transport.requests.Request() ) ), grpc.metadata_call_credentials( add_x_goog_request_params_header(provider_id) ) ) # Set up the Flagd provider to connect to SaaS Config service # Using IN_PROCESS resolver type as recommended for direct gRPC connection provider = FlagdProvider( resolver_type=ResolverType.IN_PROCESS, host="saasconfig.googleapis.com", port=443, sync_metadata_disabled=True, # Important when using IN_PROCESS with direct service provider_id=provider_id, channel_credentials=configservice_credentials ) api.set_provider(provider) client = api.get_client() initial_flag_value = client.get_boolean_value(FLAG_KEY, DEFAULT_FLAG_VALUE) log.info(f"***** STARTUP FLAG CHECK ***** Flag '{FLAG_KEY}' evaluated to: {initial_flag_value}") except Exception as e: log.critical(f"FATAL: Failed to initialize OpenFeature provider: {e}", exc_info=True) # Depending on the desired behavior, you might exit or let Flask start # but log the critical failure. Exiting might be safer in production. sys.exit(f"Provider initialization failed: {e}") # --- Flask Routes --- @app.route('/') def home(): """Endpoint to check the feature flag's value.""" log.info(f"Request received for flag: {FLAG_KEY}") try: # Get the flag value. Use the client initialized earlier. # The default value (DEFAULT_FLAG_VALUE) is returned if the flag isn't found # or if the provider isn't ready/errors occur during evaluation. flag_value = client.get_boolean_value(FLAG_KEY, DEFAULT_FLAG_VALUE) log.info(f"Evaluated flag '{FLAG_KEY}': {flag_value}") return jsonify({ "flag_key": FLAG_KEY, "value": flag_value, }) except Exception as e: log.error(f"Error evaluating flag '{FLAG_KEY}': {e}", exc_info=True) # Return an error response but keep the server running return jsonify({ "error": f"Failed to evaluate flag {FLAG_KEY}", "details": str(e), }), 500 if __name__ == '__main__': port = int(os.environ.get('PORT', 8080)) log.info(f"Starting Flask server on port {port}") app.run(host='0.0.0.0', port=port)此 Python 脚本演示了如何在 App Lifecycle Manager 单元上以 Docker 映像形式运行的应用中访问功能标志。它使用标准的 OpenFeature 原则与 App Lifecycle Manager 功能标志配置服务 (
saasconfig.googleapis.com) 集成。在
alm_docker目录中创建一个名为requirements.txt的文本文件,其中包含以下代码段:google-auth grpcio>=1.49.1,<2.0.0dev openfeature-sdk==0.8.0 openfeature-provider-flagd==0.2.2 requests typing_extensions Flask>=2.0将以下内容附加到
alm_docker目录中的Dockerfile:FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY flags.py . CMD ["python", "flags.py"]在本地环境中运行以下命令,以构建和推送 Docker 映像:
export DOCKER_REGISTRY="us-central1-docker.pkg.dev/PROJECT_ID/flags-quickstart" export FULL_IMAGE_PATH="${DOCKER_REGISTRY}/flags-quickstart:latest" docker build -t "${FULL_IMAGE_PATH}" . docker push "${FULL_IMAGE_PATH}"将
- PROJECT_ID:表示项目 ID 的字符串标识符。
在 Docker 环境中,创建一个
alm_terraform目录。在
alm_terraform中,创建以下文件:main.tflocals { config_path = "projects/${var.system_unit_project}/locations/${var.system_unit_location}/featureFlagsConfigs/${var.system_unit_name}" docker_image_path = "${var.system_unit_location}-docker.pkg.dev/${var.system_unit_project}/${var.docker_repo_name}/${var.docker_tag}" } provider "google" { project = var.system_unit_project region = var.system_unit_location } resource "google_cloud_run_service" "flags_quickstart_service" { name = var.cloud_run_service_name location = var.system_unit_location project = var.system_unit_project template { spec { containers { image = local.docker_image_path env { name = "FLAGD_SOURCE_PROVIDER_ID" value = local.config_path } } service_account_name = var.actuation_sa } } }variables.tfvariable "actuation_sa" { description = "Actuation SA" type = string } variable "system_unit_project" { description = "Project id - variable set by App Lifecycle Manager" type = string } variable "system_unit_location" { description = "Location - variable set by App Lifecycle Manager" type = string } variable "system_unit_name" { description = "Unit name- variable set by App Lifecycle Manager" type = string } variable "docker_repo_name" { description = "The name of the Artifact Registry repository where the Docker image is stored." type = string default = "flags-quickstart" } variable "docker_tag" { description = "The tag of the Docker image to deploy." type = string default = "flags-quickstart:latest" } variable "cloud_run_service_name" { description = "Name for the Cloud Run service to be created." type = string default = "saas-flags-quickstart-svc" }在
alm_terraform目录中,运行以下命令来打包 Terraform 蓝图文件:zip terraform-files.zip main.tf variables.tf
使用应用蓝图创建单元
创建利用功能标志的应用蓝图后,您需要创建一个 App Lifecycle Manager 单元种类 (flags-unit-kind),然后创建此种类的单元 (flags-quickstart-unit)。
如需详细了解单元和单元种类,请参阅对部署的单元进行建模和打包。
如需使用应用蓝图创建单元,请按照以下 gcloud CLI 步骤操作:
如需将 Terraform 配置打包为 OCI 映像(蓝图),请在 Terraform 目录中创建一个名为
Dockerfile的文件:# syntax=docker/dockerfile:1-labs FROM scratch COPY --exclude=Dockerfile --exclude=.git --exclude=.gitignore . /构建
Dockerfile并将其推送到 Artifact Registry 代码库:IMAGE_NAME="us-central1-docker.pkg.dev/PROJECT_ID/flags-quickstart/flags-quickstart-blueprint:latest" ENGINE_TYPE=inframanager ENGINE_VERSION=1.5.7 docker buildx build -t $IMAGE_NAME \ --push \ --annotation "com.easysaas.engine.type=$ENGINE_TYPE" \ --annotation "com.easysaas.engine.version=$ENGINE_VERSION" \ --provenance=false .将
- PROJECT_ID:表示项目 ID 的字符串标识符。
创建
flags-unit-kind和flags-release资源:# Create unit kind gcloud beta app-lifecycle-manager unit-kinds create flags-unit-kind \ --project=PROJECT_ID \ --location=global \ --saas=flags-quickstart-saas-offering # Create release referencing the Blueprint image gcloud beta app-lifecycle-manager releases create flags-release \ --project=PROJECT_ID \ --location=global \ --unit-kind=flags-unit-kind \ --blueprint-package=$IMAGE_NAME将
- PROJECT_ID:表示项目 ID 的字符串标识符。
创建
flags-quickstart-unit单元:gcloud beta app-lifecycle-manager units create flags-quickstart-unit \ --project=PROJECT_ID \ --location=us-central1 \ --unit-kind=flags-unit-kind \ --management-mode=user将
- PROJECT_ID:表示项目 ID 的字符串标识符。
创建和预配功能标志
在 App Lifecycle Manager 功能标志可供预配的单元使用之前,您必须创建功能标志资源并启动发布,以将配置传播到该单元。
运行以下命令来创建和预配 quickstart-flag 功能标志:
在您的环境中,定义以下变量:
export FLAG_ID="quickstart-flag" export FLAG_KEY="quickstart-flag" export SAAS_OFFERING_ID="flags-quickstart-saas-offering" export UNIT_KIND_ID="flags-unit-kind" export UNIT_ID="flags-quickstart-unit" export ROLLOUT_KIND_ID="flags-quickstart-rollout-kind" export ROLLOUT_ID="flags-quickstart-rollout"创建功能标志资源:
gcloud beta app-lifecycle-manager flags create ${FLAG_ID} \ --project=${PROJECT_ID} \ --key=${FLAG_KEY} \ --flag-value-type=BOOL \ --location=global \ --unit-kind=${UNIT_KIND_ID}创建修订版本:
export FLAG_REVISION_ID="${FLAG_ID}-rev1" gcloud beta app-lifecycle-manager flags revisions create ${FLAG_REVISION_ID} \ --project=${PROJECT_ID} \ --flag=${FLAG_ID} \ --location=global创建版本:
export FLAG_RELEASE_ID="${FLAG_ID}-rel1" gcloud beta app-lifecycle-manager flags releases create ${FLAG_RELEASE_ID} \ --project=${PROJECT_ID} \ --flag-revisions=${FLAG_REVISION_ID} \ --unit-kind=${UNIT_KIND_ID} \ --location=global创建发布种类:
gcloud beta app-lifecycle-manager rollout-kinds create ${ROLLOUT_KIND_ID} \ --project=${PROJECT_ID} \ --unit-kind=${UNIT_KIND_ID} \ --rollout-orchestration-strategy=Google.Cloud.Simple.AllAtOnce \ --location=global创建发布:
gcloud beta app-lifecycle-manager rollouts create ${ROLLOUT_ID} \ --project=${PROJECT_ID} \ --flag-release=${FLAG_RELEASE_ID} \ --rollout-kind=${ROLLOUT_KIND_ID} \ --location=global
您可以使用以下命令监控发布状态:
gcloud beta app-lifecycle-manager rollouts describe ${ROLLOUT_ID} --project=${PROJECT_ID} --location=global
查看正在运行的服务中的标志值
App Lifecycle Manager 单元成功预配 Cloud Run 服务后,您可以验证应用是否正在运行并正确评估功能标志:
在 Google Cloud 控制台中,前往 Cloud Run:
在
us-central1区域中找到名为saas-flags-quickstart-svc的服务。saas-flags-quickstart-svc旁边的对勾标记表示该服务已成功运行。点击
saas-flags-quickstart-svc以查看其详细信息。选择日志 标签页。
在日志条目中,查找类似于以下内容的消息:
INFO:__main__:***** STARTUP FLAG CHECK ***** Flag 'quickstart-flag' evaluated to: false这证实应用已启动、已连接到 SaaS 配置服务,并且已评估
quickstart-flag。
如需访问公共端点,请点击网络 标签页。
- 在端点 部分下找到列出的公共 网址 。
- 点击该网址以在浏览器中打开它,或使用
curl等工具从终端访问它(curl YOUR_SERVICE_URL,例如)。 每次访问该网址时,服务都会评估功能标志并以 JSON 格式返回其当前值。例如:
{ "flag_key": "quickstart-flag", "value": false }
您已成功部署一个 Google Cloud 读取一个 App Lifecycle Manager 管理的功能标志的服务。您可以尝试更改标志的值并创建新的发布,以查看应用是否会获取更改。
清理
为避免因本页中使用的资源导致您的 Google Cloud 账号产生费用,请按照以下步骤操作。
可选:删除项目
如果您在新 Google Cloud 项目中部署了解决方案,并且不再需要该 项目,请按照以下步骤将其删除:
- 在 Google Cloud 控制台中,前往管理资源页面。
- 在项目列表中,选择要删除的项目,然后点击删除。
- 在提示符处,输入项目 ID,然后点击关停 。
后续步骤
- 试用部署功能标志独立快速入门,以独立于 App Lifecycle Manager 管理的部署使用标志。
- 探索特定于语言的集成指南(Python、Java、Go)。
- 查看 App Lifecycle Manager 概览,详细了解 App Lifecycle Manager。