【问题标题】: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


【解决方案1】:

您可以使用适用于 Python 的 Cloud SQL Admin API 客户端库,该库将使用默认服务帐号凭据为您包含此授权令牌。查看Client libraries and sample code 页面了解更多信息。

或者,如果您更喜欢手动创建请求,您可以使用 Oauth 2.0 令牌。 Authorizing requests 页面有更多关于如何创建这些的信息。

【讨论】:

    【解决方案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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-13
      • 2018-08-28
      • 1970-01-01
      • 2022-09-28
      • 2021-09-08
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多