基于GCP服务账号模拟的AWS Lambda调用GCP Cloud Function认证实现
AWS Lambda通过GCP Workload Identity Pool认证调用Cloud Function方案
核心问题说明
你当前代码用google.auth.default()是在尝试加载GCP本地凭证(比如服务账号密钥、元数据服务器凭证),但Lambda环境里没有这些,所以必须基于Workload Identity Pool的流程,用AWS Lambda的执行角色身份去换取GCP的短期访问凭证。
正确实现步骤
1. 先确认Workload Identity Pool配置无误
- 已在GCP创建Workload Identity Pool,并添加了AWS作为身份提供商
- 已将Lambda的执行角色ARN映射到Pool中的身份
- 该GCP身份已绑定
roles/cloudfunctions.invoker角色(确保能调用目标Cloud Function)
2. Lambda中的认证代码实现
需要使用google.auth.aws模块来完成身份交换,以下是可运行的代码示例:
import google.auth from google.auth.aws import AwsCredentials from google.auth.transport.requests import Request import requests def get_gcp_access_token(): # 用Lambda的默认AWS凭证初始化GCP的AWS身份凭证 aws_creds = AwsCredentials() # 指定要模拟的GCP服务账号(格式:projects/[GCP_PROJECT_ID]/serviceAccounts/[SA_EMAIL]) target_service_account = "projects/your-gcp-project-id/serviceAccounts/your-sa@your-gcp-project-id.iam.gserviceaccount.com" # 定义所需的权限范围 scopes = ["https://www.googleapis.com/auth/cloud-platform"] # 刷新凭证,完成身份交换 request = Request() aws_creds.refresh(request) # 获取针对目标服务账号的模拟凭证 impersonated_creds = google.auth.impersonated_credentials.Credentials( source_credentials=aws_creds, target_principal=target_service_account, target_scopes=scopes, lifetime=3600 ) # 获取访问令牌 impersonated_creds.refresh(request) return impersonated_creds.token def invoke_gcp_cloud_function(gcf_url, access_token): headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } # 这里可以根据需要传递请求体 response = requests.post(gcf_url, headers=headers) response.raise_for_status() return response.json() def lambda_handler(event, context): gcf_url = "https://your-region-your-gcp-project-id.cloudfunctions.net/your-function-name" access_token = get_gcp_access_token() result = invoke_gcp_cloud_function(gcf_url, access_token) return {"statusCode": 200, "body": result}
3. 关键注意事项
- Lambda执行角色需要有
sts:GetCallerIdentity权限(默认的Lambda基本执行角色已包含此权限,若自定义角色需手动添加) - 部署Lambda时需安装依赖:
google-auth、google-auth-aws、requests,可以用层或者打包部署 - 若Lambda在VPC内,需确保VPC的安全组和NACL允许出站访问GCP的HTTPS端口(443),同时如果没有互联网访问,需要配置VPC端点或者NAT网关
原代码问题分析
你之前的代码调用google.auth.default()会尝试从Lambda环境中查找GCP本地凭证,而Lambda没有GCP的元数据服务器或本地密钥文件,所以无法获取有效凭证,必须使用Workload Identity Pool对应的AWS身份交换流程。
内容的提问来源于stack exchange,提问作者Bigbentem
相关产品推荐
相关产品推荐

