如何以编程方式在Google Cloud Run API中获取当前项目ID
问题描述:
我有一个已容器化并在云运行内部运行的API.如何获取我的云运行所在的当前项目ID?我尝试过:
I have an API that is containerized and running inside cloud run. How can I get the current project ID where my cloud run is executing? I have tried:
- 我在日志的textpayload中看到了它,但是我不确定如何在post函数中读取textpayload吗?我收到的pub子消息缺少此信息.
- 我已经阅读了查询元数据api的书,但是关于如何再次从api内进行操作尚不清楚.有链接吗?
还有其他方法吗?
在下面进行了一些评论之后,我最终在运行在 Cloud Run 中的.net API中使用了此代码.
After some comments below, I ended up with this code inside my .net API running inside Cloud Run.
private string GetProjectid()
{
var projectid = string.Empty;
try {
var PATH = "http://metadata.google.internal/computeMetadata/v1/project/project-id";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Metadata-Flavor", "Google");
projectid = client.GetStringAsync(PATH).Result.ToString();
}
Console.WriteLine("PROJECT: " + projectid);
}
catch (Exception ex) {
Console.WriteLine(ex.Message + " --- " + ex.ToString());
}
return projectid;
}
更新,它可以正常工作.我的构建推送失败了,我没有看到.谢谢大家.
Update, it works. My build pushes had been failing and I did not see. Thanks everyone.
答
您可以通过向 http://metadata.google.internal/computeMetadata/v1/project/project-id发送GET请求来获取项目ID
和 Metadata-Flavor:Google
标头.
请参见本文档
例如在Node.js中:
In Node.js for example:
index.js
:
const express = require('express');
const axios = require('axios');
const app = express();
const axiosInstance = axios.create({
baseURL: 'http://metadata.google.internal/',
timeout: 1000,
headers: {'Metadata-Flavor': 'Google'}
});
app.get('/', (req, res) => {
let path = req.query.path || 'computeMetadata/v1/project/project-id';
axiosInstance.get(path).then(response => {
console.log(response.status)
console.log(response.data);
res.send(response.data);
});
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log('Hello world listening on port', port);
});
package.json
:
{
"name": "metadata",
"version": "1.0.0",
"description": "Metadata server",
"main": "app.js",
"scripts": {
"start": "node index.js"
},
"author": "",
"license": "Apache-2.0",
"dependencies": {
"axios": "^0.18.0",
"express": "^4.16.4"
}
}