我正在嘗試從 Cloud Function 向部署在默認 GAE 服務上的多個 App Engine 端點發送請求。我的代碼很簡單:
云功能
主檔案
import logging
import requests
def main(event, context):
bucketname = event['bucket']
filename = event['name']
endpoint = # Some logic extracting the endpoint to be used
url = 'https://myproject.ew.r.appspot.com/{}'.format(endpoint)
data = {
'bucketname': bucketname,
'filename': filename
}
r = requests.post(url, json=data)
logging.info(r)
return str(r)
云功能部署為:
gcloud functions deploy storage_to_gae --runtime python37 --trigger-resource $BUCKETNAME --trigger-event google.storage.object.finalize --region $REGION --source gcf/ --entry-point main --service-account [email protected]
Fuction 使用的服務帳戶已roles/iam.serviceAccountUser授予服務帳戶用戶 ( ) 角色。
應用引擎
應用程式.yml
runtime: python37
service: default
但是,請求不會到達 App Engine,因為 GAE 服務上沒有出現日志。請求回傳<Response [401]>錯誤代碼,因此 CF 似乎無法訪問 App Engine 服務。
我需要哪些額外的角色來提供我的[email protected]服務帳戶?我在客戶端環境中部署,所以我的權限有限,我必須詢問所需的確切角色。
uj5u.com熱心網友回復:
在詢問了我客戶的 GCP 團隊后,他們使用 IAP 來管理訪問。
我按照本檔案中的說明操作,并且能夠向 GAE 端點發送請求。
這是我的最終代碼:
import requests
from google.oauth2 import id_token
from google.auth.transport.requests import Request
def make_iap_request(url, client_id, method='POST', **kwargs):
"""Makes a request to an application protected by Identity-Aware Proxy.
Args:
url: The Identity-Aware Proxy-protected URL to fetch.
client_id: The client ID used by Identity-Aware Proxy.
method: The request method to use
('GET', 'OPTIONS', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE')
**kwargs: Any of the parameters defined for the request function:
https://github.com/requests/requests/blob/master/requests/api.py
If no timeout is provided, it is set to 90 by default.
Returns:
The page body, or raises an exception if the page couldn't be retrieved.
"""
# Set the default timeout, if missing
if 'timeout' not in kwargs:
kwargs['timeout'] = 90
# Obtain an OpenID Connect (OIDC) token from metadata server or using service
# account.
open_id_connect_token = id_token.fetch_id_token(Request(), client_id)
# Fetch the Identity-Aware Proxy-protected URL, including an
# Authorization header containing "Bearer " followed by a
# Google-issued OpenID Connect token for the service account.
resp = requests.request(
method, url,
headers={'Authorization': 'Bearer {}'.format(
open_id_connect_token)}, **kwargs)
return resp.text
def main(event, context):
bucketname = event['bucket']
filename = event['name']
endpoint = # Some logic extracting the endpoint to be used
url = 'https://myproject.ew.r.appspot.com/{}'.format(endpoint)
data = {
'bucketname': bucketname,
'filename': filename
}
client_id = 'myclientid'
r = make_iap_request(url, client_id, 'POST', json=data)
logging('info', r)
return str(r)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/334367.html
標籤:Python 谷歌应用引擎 谷歌云平台 谷歌云功能 google-cloud-iam
上一篇:MVC中的正確結構與spring
下一篇:GoogleAppEngineJava11-com.google.apphosting.api.ApiProxy$CallNotFoundException不明錯誤
