Google Cloud Build 获取身份令牌

Google Cloud Build fetch Identity token

在我的场景中,我想在 Google 云构建期间触发基于 HTTP 端点的 Google 云函数。 HTTP 请求是使用 python:3.7-slim 容器的步骤完成的。

基于文档中的 this and this 个示例,我想使用以下代码:

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 设置,并且还在同一项目内的测试虚拟机上测试了完全相同的获取机制。 问题似乎是获取一些元数据在云构建中不起作用。

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

这里最好的办法是在 Public Issue Tracker 中创建一个功能请求 (FR)。提交问题和 FR 是有区别的。 FR 让工程团队了解真正的需求;根据受此影响的用户数量,他们优先考虑开发这些用户。我还建议创建一个 guthub 存储库,以便他们可以轻松复制它并参考上述问题。

另一方面,作为解决方法,您可以 create a topic in Pub/Sub to receive build notifications:

gcloud pubsub topics create cloud-builds

每次提交构建时,都会向主题推送一条消息,然后您可以创建一个 PubSub Cloud Function 并从那里调用您的 HTTP CF。

我用了this example from github, mentioned in the docs Authenticating Function to function

const {get} = require('axios');

// TODO(developer): set these values
const REGION = 'us-central1';
const PROJECT_ID = 'YOUR PROJECTID';
const RECEIVING_FUNCTION = 'FUNCTION TO TRIGGER';

// Constants for setting up metadata server request
// See https://cloud.google.com/compute/docs/instances/verifying-instance-identity#request_signature
const functionURL = `https://${REGION}-${PROJECT_ID}.cloudfunctions.net/${RECEIVING_FUNCTION}`;
const metadataServerURL =
  'http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=';
const tokenUrl = metadataServerURL + functionURL;

exports.helloPubSub = async (event, context) => {
// Fetch the token
  const message = event.data
    ? Buffer.from(event.data, 'base64').toString()
    : 'Hello, World';
    
  const tokenResponse = await get(tokenUrl, {
    headers: {
      'Metadata-Flavor': 'Google',
    },
  });
  const token = tokenResponse.data;

  // Provide the token in the request to the receiving function
  try {
    const functionResponse = await get(functionURL, {
      headers: {Authorization: `bearer ${token}`},
    });
    console.log(message);
  } catch (err) {
    console.error(err);
  }
};

最后,当ClouBuild提交时,你的PubSub CF会被触发,你可以在里面调用你的CF。

解决方案是在具有访问令牌的服务帐户上使用 new IAM api to generate an ID_TOKEN,如果请求者(生成访问令牌的人)在服务帐户上具有服务帐户令牌创建者角色(或广泛参与项目)。

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

 - 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 代码版本

- 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'])

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

我想我会在 Medium 上写一篇关于这个的文章,如果你想要我说出你的名字,请告诉我