GCP部署CI/CD的密钥处理咨询:Streamlit应用凭据安全问题
以下是几个安全且实用的解决方案,既不会把凭据文件推到GitHub,又能保证GCP部署时正常使用:
1. 用GCP默认凭据(最推荐)
在GCP的托管环境(比如Cloud Run、GKE、Cloud Functions)部署时,完全不需要手动指定凭据文件路径。GCP会自动为运行中的服务关联一个服务帐号,SDK会自动获取这个帐号的凭据。
操作步骤:
- 删掉代码里这两行:
import os os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = './google-creds.json' - 部署应用时,给服务分配一个拥有Vertex AI预测权限的服务帐号(比如
roles/aiplatform.predictor角色)。
这样应用在GCP环境运行时,会自动通过默认凭据链获取权限,无需任何本地凭据文件。
2. 配合GitHub Secrets做CI/CD
如果你的CI/CD流程(比如GitHub Actions)需要在构建阶段用到凭据(比如构建镜像时测试Vertex AI连接),可以把google-creds.json的内容存在GitHub Secrets里,在CI脚本中动态生成文件,用完就清理。
示例GitHub Actions步骤:
- name: 生成临时凭据文件 run: echo "${{ secrets.GOOGLE_APPLICATION_CREDENTIALS_CONTENT }}" > ./google-creds.json
注意:构建完成后要确保这个临时文件不会被打包进镜像,或者在镜像构建的最后一步删除它。
3. 用GCP Secret Manager存储凭据
把凭据文件存在GCP的Secret Manager里,应用启动时从Secret Manager拉取凭据内容,写入临时文件或者直接加载到内存中使用。
修改代码示例:
import os import json from google.cloud import secretmanager from google.oauth2 import service_account from google.cloud import aiplatform def get_gcp_secret(project_id, secret_id): client = secretmanager.SecretManagerServiceClient() secret_name = f"projects/{project_id}/secrets/{secret_id}/versions/latest" response = client.access_secret_version(name=secret_name) return response.payload.data.decode("UTF-8") # 从Secret Manager拉取凭据 creds_json_str = get_gcp_secret("你的GCP项目ID", "存储凭据的Secret名称") creds_info = json.loads(creds_json_str) # 直接用凭据信息初始化客户端,无需本地文件 credentials = service_account.Credentials.from_service_account_info(creds_info) aiplatform.init(credentials=credentials, project="你的GCP项目ID")
前提:给运行应用的服务帐号分配roles/secretmanager.secretAccessor角色,允许它访问Secret Manager里的凭据。
4. 用环境变量直接传递凭据内容
跳过本地文件,把凭据的JSON内容直接设置为环境变量,代码里直接读取这个环境变量的内容来初始化客户端。
修改代码示例:
import os import json from google.oauth2 import service_account from google.cloud import aiplatform # 从环境变量读取凭据JSON creds_json_str = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS_JSON") if not creds_json_str: raise ValueError("环境变量GOOGLE_APPLICATION_CREDENTIALS_JSON未设置") creds_info = json.loads(creds_json_str) credentials = service_account.Credentials.from_service_account_info(creds_info) aiplatform.init(credentials=credentials, project="你的GCP项目ID")
部署时操作:在GCP的部署配置里(比如Cloud Run的环境变量设置),添加GOOGLE_APPLICATION_CREDENTIALS_JSON变量,值为凭据文件的完整JSON内容。
内容的提问来源于stack exchange,提问作者afrologicinsect

