我正在从我的 GCP 项目中调用云功能。
当功能配置为Allow internal traffic only时,我收到 403(Permission Denied) ,请参阅 https://cloud.google.com/functions/docs/networking/network-settings#ingress_settings
删除入口控制没有问题时,该函数以状态 200 响应。该函数不允许未经身份验证的访问,已配置IAM 策略。
按照https://cloud.google.com/functions/docs/securing/authenticating#function-to-function的示例:
# main.py
import requests
# TODO<developer>: set these values
# REGION = None
# PROJECT_ID = None
RECEIVING_FUNCTION = 'hello-get'
# Constants for setting up metadata server request
# See https://cloud.google.com/compute/docs/instances/verifying-instance-identity#request_signature
function_url = f'https://{REGION}-{PROJECT_ID}.cloudfunctions.net/{RECEIVING_FUNCTION}'
metadata_server_url = \
'http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience='
token_full_url = metadata_server_url + function_url
token_headers = {'Metadata-Flavor': 'Google'}
def hello_trigger(request):
token_response = requests.get(token_full_url, headers=token_headers)
jwt = token_response.text
function_headers = {'Authorization': f'bearer {jwt}'}
function_response = requests.get(function_url, headers=function_headers)
function_response.raise_for_status()
return function_response.text
def hello_get(req):
return 'Hello there...'
使用所需的入口设置部署函数和触发函数:
gcloud functions deploy hello-get --trigger-http --entry-point hello_get --runtime python37 --ingress-settings internal-only
gcloud functions deploy hello-trigger --trigger-http --entry-point hello_trigger --runtime python37 --ingress-settings all --allow-unauthenticated
调用hello-trigger
返回 403。
改变 ingress ofhello-get
解决了这个问题:
gcloud functions deploy hello-get --trigger-http --entry-point hello_get --runtime python37 --ingress-settings all
现在调用hello-trigger
返回 200。
用于 Cloud Functions 的服务帐户被赋予了此设置的 Functions Invoker 角色。