如何以编程方式在Google Cloud Run API中获取当前项目ID [英] How to programmatically get current project id in Google cloud run api

查看:146
本文介绍了如何以编程方式在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"
  }
}

这篇关于如何以编程方式在Google Cloud Run API中获取当前项目ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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