Google Cloud Build获取身份令牌 [英] Google Cloud Build fetch Identity token

查看:116
本文介绍了Google Cloud Build获取身份令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的方案中,我想在Google Cloud Build期间基于HTTP端点触发Google Cloud Function.使用带有python:3.7-slim容器的步骤来完成HTTP请求.

in my scenario, I would like to trigger an Google Cloud Function based on HTTP endpoint during a Google Cloud Build. The HTTP request is done using a step with a python:3.7-slim container.

基于示例文档,我想使用以下代码:

Based on this and this examples from the documentation, I wanted to use the following code:

REGION = 'us-central1'
PROJECT_ID = 'name-of-project'
RECEIVING_FUNCTION = 'my-cloud-function'

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'}

token_response = requests.get(token_full_url, headers=token_headers)
jwt = token_response.text
print(jwt)

r = requests.post(url=function_url, headers=function_headers, json=payload)

令人惊讶的是,代码失败,因为jwtNot Found(根据print语句). 我已经通过硬编码有效的身份令牌来测试代码和IAM设置,并且还在同一项目内的测试VM上测试了完全相同的提取机制. 问题似乎是获取某些元数据的功能无法在云构建内部运行.

Surprisingly, the code fails because jwt is Not Found (according to the print statement). I already tested the code and IAM settings by hard coding a valid identity token and also tested the exact same fetching mechanism on a test VM inside the same project. The problem seems to be that the meta data fetching some is not working inside cloud build.

我错过了什么吗? 谢谢您的帮助!

Am I missing something? Thank you for any help!

推荐答案

解决方案是使用

The solution is to use a new IAM api to generate an ID_TOKEN, on a service account with an access token, if the requester (this one who generate the access token) has the role Service Account Token Creator on the service account (or widely on the project).

第一个示例使用直接API调用

This first example use direct API calls

 - name: gcr.io/cloud-builders/gcloud
   entrypoint: "bash"
   args:
    - "-c"
    - |
        curl -X POST -H "content-type: application/json" \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -d '{"audience": "YOUR AUDIENCE"}' \
         "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/YOUR SERVICE ACCOUNT:generateIdToken"
        # Use Cloud Build Service Account
        # service_account_email=$(gcloud config get-value account) 

这里是Python代码版本

And here the Python code version

- name: python:3.7
          entrypoint: "bash"
          args:
            - "-c"
            - |
                    pip3 install google-auth requests
                    python3 extract-token.py

并且extract-token.py包含以下代码

REGION = 'us-central1'
PROJECT_ID = 'name-of-project'
RECEIVING_FUNCTION = 'my-cloud-function'
function_url = f'https://{REGION}-{PROJECT_ID}.cloudfunctions.net/{RECEIVING_FUNCTION}'

import google.auth
credentials, project_id = google.auth.default(scopes='https://www.googleapis.com/auth/cloud-platform')

# To use the Cloud Build service account email
service_account_email = credentials.service_account_email
#service_account_email = "YOUR OWN SERVICE ACCOUNT"

metadata_server_url = f'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{service_account_email}:generateIdToken'
token_headers = {'content-type': 'application/json'}

from google.auth.transport.requests import AuthorizedSession
authed_session = AuthorizedSession(credentials)
import json
body = json.dumps({'audience': function_url})

token_response = authed_session.request('POST',metadata_server_url, data=body, headers=token_headers)
jwt = token_response.json()
print(jwt['token'])

如果您需要更多详细信息,请不要犹豫.

Don't hesitate if you need more details.

我想我会在Medium上写一篇有关此的文章,如果您想给我起个名字,请告诉我

这篇关于Google Cloud Build获取身份令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆