我有一个已容器化并在云运行内部运行的API。如何获得执行云的当前项目ID?我尝试过:
还有其他方法吗?
编辑:
在下面进行了一些评论之后,我最终在运行在 Cloud Run 中的.net API中使用了此代码。
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;
}
更新,它可以工作。我的构建推送失败了,我没有看到。感谢大家。
答案 0 :(得分:1)
通过向标头为http://metadata.google.internal/computeMetadata/v1/project/project-id
的{{1}}发送GET请求,即可获得项目ID。
例如在Node.js中:
Metadata-Flavor:Google
:
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
答案 1 :(得分:0)
我将requirements.txt
模块添加到了gcloud
Flask==1.1.1
pytest==5.3.0; python_version > "3.0"
pytest==4.6.6; python_version < "3.0"
gunicorn==19.9.0
gcloud
我更改了main.py中的index
函数:
def index():
envelope = request.get_json()
if not envelope:
msg = 'no Pub/Sub message received'
print(f'error: {msg}')
return f'Bad Request: {msg}', 400
if not isinstance(envelope, dict) or 'message' not in envelope:
msg = 'invalid Pub/Sub message format'
print(f'error: {msg}')
return f'Bad Request: {msg}', 400
pubsub_message = envelope['message']
name = 'World'
if isinstance(pubsub_message, dict) and 'data' in pubsub_message:
name = base64.b64decode(pubsub_message['data']).decode('utf-8').strip()
print(f'Hello {name}!')
#code added
from gcloud import pubsub # Or whichever service you need
client = pubsub.Client()
print('This is the project {}'.format(client.project))
# Flush the stdout to avoid log buffering.
sys.stdout.flush()
return ('', 204)
我检查了日志:
Hello (pubsub message).
This is the project my-project-id.
答案 2 :(得分:0)
应该可以使用Platform
(https://github.com/googleapis/gax-dotnet/blob/master/Google.Api.Gax/Platform.cs)中的Google.Api.Gax
类。通常将Google.Api.Gax
软件包作为对其他Google .NET软件包(如Google.Cloud.Storage.V1
var projectId = Google.Api.Gax.Platform.Instance().ProjectId;
在GAE平台上,您还可以简单地检查环境变量GOOGLE_CLOUD_PROJECT
和GCLOUD_PROJECT
var projectId = Environment.GetEnvironmentVariable("GOOGLE_CLOUD_PROJECT")
?? Environment.GetEnvironmentVariable("GCLOUD_PROJECT");
答案 3 :(得分:0)
这是获取当前项目 ID 的 Java 代码片段:
String url = "http://metadata.google.internal/computeMetadata/v1/project/project-id";
HttpURLConnection conn = (HttpURLConnection)(new URL(url).openConnection());
conn.setRequestProperty("Metadata-Flavor", "Google");
try {
InputStream in = conn.getInputStream();
projectId = new String(in.readAllBytes(), StandardCharsets.UTF_8);
} finally {
conn.disconnect();
}