如何解决Google Cloud Build获取身份令牌
在我的方案中,我想在Google Cloud Build期间基于HTTP端点触发Google Cloud Function。通过使用带有python:3.7-slim容器的步骤来完成HTTP请求。
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)
令人惊讶的是,由于jwt
为Not Found
(根据print
语句),代码失败。
我已经通过硬编码有效的身份令牌来测试代码和IAM设置,并且还在同一项目内的测试VM上测试了完全相同的提取机制。
问题似乎是获取某些元数据的功能无法在云构建内部运行。
我错过了什么吗? 谢谢您的帮助!
解决方法
解决方案是,如果请求者(生成访问令牌的请求者)在服务帐户(或广泛使用)上具有服务帐户令牌创建者角色,则在具有访问令牌的服务帐户上使用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上写一篇有关此的文章,如果您想给自己起个名字,请告诉我
,最好的做法是在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。
我使用了来自github的this example,在文档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。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。