【问题标题】:How do I use a Google Cloud Function to add an ip to the authorized networks of a Cloud SQL instance?如何使用 Google Cloud Function 将 ip 添加到 Cloud SQL 实例的授权网络?
【发布时间】:2020-11-13 08:11:53
【问题描述】:
正如标题所说,我有一个 gcp sql 实例,并希望使用云函数(在 Python 中)将 ip 添加到它的授权网络列表中。根据https://cloud.google.com/sql/docs/mysql/configure-ip#rest,我可以使用这个休息电话:
curl -X PATCH \
-H "Authorization: Bearer "$(gcloud auth print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://www.googleapis.com/sql/v1beta4/projects/project-id/instances/instance-id
所以我的想法是使用请求从云功能中进行此调用。但是,我不知道如何在云函数中获取gcloud auth print-access-token 的结果。
【问题讨论】:
-
您需要从元数据服务器获取云函数服务帐户的访问令牌,或者使用可以为您执行此操作的 API。详情请见this page。
标签:
python
google-cloud-platform
google-cloud-functions
google-cloud-sql
【解决方案2】:
这里是发出授权请求的 python 代码示例(这里是 GET 版本。使用您想要的动词对其进行自定义)
from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
import google.auth
base_url = 'https://www.googleapis.com/sql/v1beta4/projects/'
credentials, project_id = google.auth.default(scopes=['https://www.googleapis.com/auth/cloud-platform'])
project_id = 'yourProjectID'
instance_id = 'yourInstanceID'
authed_session = AuthorizedSession(credentials)
response = authed_session.request('GET', f'{base_url}{project_id}/instances/{instance_id}')
print(response.json())