我正在尝试从另一个(CF1)调用云功能(CF2)。但是,我不断收到403。
我的问题是弄清楚哪个服务帐户是CF2的“云功能调用者”。
我以为CF1的云功能服务代理是必需的,但这没有用。
答案 0 :(得分:1)
来自 Documentation:
首先,您需要配置接收功能以接受来自调用功能的请求:
将Cloud Functions Invoker(roles / cloudfunctions.invoker)角色授予接收函数上的调用函数身份。默认情况下,此身份为PROJECT_ID@appspot.gserviceaccount.com
使用gcloud函数add-iam-policy-binding命令:
gcloud functions add-iam-policy-binding RECEIVING_FUNCTION \
--member='serviceAccount:CALLING_FUNCTION_IDENTITY' \
--role='roles/cloudfunctions.invoker'
其中RECEIVING_FUNCTION是接收函数,而CALLING_FUNCTION_IDENTITY是调用函数标识。
在调用函数中,您需要:
- 创建一个由Google签名的OAuth ID令牌,并将访问者(aud)设置为接收函数的URL。
- 在对函数的请求中的“授权:承载ID_TOKEN”标头中包含ID令牌。
# Requests is already installed, no need to add it to requirements.txt
import requests
def calling_function(request):
# Make sure to replace variables with appropriate values
receiving_function_url = 'https://REGION-PROJECT.cloudfunctions.net/RECEIVING_FUNCTION'
# Set up metadata server request
# See https://cloud.google.com/compute/docs/instances/verifying-instance-identity#request_signature
metadata_server_token_url = 'http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience='
token_request_url = metadata_server_token_url + receiving_function_url
token_request_headers = {'Metadata-Flavor': 'Google'}
# Fetch the token
token_response = requests.get(token_request_url, headers=token_request_headers)
jwt = token_response.content.decode("utf-8")
# Provide the token in the request to the receiving function
receiving_function_headers = {'Authorization': f'bearer {jwt}'}
function_response = requests.get(receiving_function_url, headers=receiving_function_headers)
return function_response.content
可以找到更多信息 here
答案 1 :(得分:0)
这是我遵循的步骤:
我创建了两个服务帐户:
gcloud iam service-accounts create function-one --desplay-name function-one
gcloud iam service-accounts create function-two --display-name function-two
我为我的服务帐户分配了必要的角色:
gcloud projects add-iam-policy-binding my_project --member serviceAccount:function-one@my_project.iam.gserviceaccount.com --role roles/cloudfunctions.serviceAgent
gcloud projects add-iam-policy-binding my_project --member serviceAccount:function-two@my_project.iam.gserviceaccount.com --role roles/cloudfunctions.serviceAgent
我在Google Cloud控制台link上创建了两个云功能。当我创建云功能时,在“环境变量,网络,超时等”下的“服务助手”下,我为每个云功能分配了一个在步骤1中创建的服务帐户。
def hello_gcs_generic_one(request):
import requests
print ('Hello from cloud function one')
response = requests.post("https://us-central1-my_project.cloudfunctions.net/function-two")
if response.status_code != 200:
exit("Could not call function! :(")
def hello_gcs_generic_two(request):
print ('Hello from cloud function two')
我测试过调用函数一“测试/测试功能”:
功能一登录:
Function execution started
Hello from cloud function one
Function execution took 2219 ms, finished with status code: 200
功能两个Logg:
Function execution started
Hello from cloud function two
Function execution took 18 ms, finished with status code: 200