GCP:如何获得计算引擎访问令牌?

问题描述 投票:1回答:1

我想获得计算引擎的访问令牌。通过使用此访问令牌,我想调用REST api。进一步的Rest api将使用python 2.0 HTTP库调用。 (并非所有谷歌库都可用,因此考虑使用REST API)

您能否提供获取计算引擎访问令牌的方法?以下代码可以启动,但是如何从此处获取访问令牌尚不清楚:

from google.auth import compute_engine
credentials = compute_engine.Credentials() 

请提出不同的建议......提前致谢。

google-cloud-platform google-api-python-client
1个回答
4
投票

每个Compute Engine实例都将其元数据存储在元数据服务器上。您可以在实例中以编程方式查询此元数据服务器,以获取有关实例的信息,例如服务帐户信息。您可以在Python中从元数据服务器请求访问令牌,如下所示:

import requests

METADATA_URL = 'http://metadata.google.internal/computeMetadata/v1/'
METADATA_HEADERS = {'Metadata-Flavor': 'Google'}
SERVICE_ACCOUNT = 'default'


def get_access_token():
    url = '{}instance/service-accounts/{}/token'.format(
        METADATA_URL, SERVICE_ACCOUNT)

    # Request an access token from the metadata server.
    r = requests.get(url, headers=METADATA_HEADERS)
    r.raise_for_status()

    # Extract the access token from the response.
    access_token = r.json()['access_token']

    return access_token

请注意,此示例假定您的实例正在使用Compute Engine default service account

© www.soinside.com 2019 - 2024. All rights reserved.