如何在Google Cloud Run API中以编程方式获取当前项目ID

时间:2019-12-19 20:52:14

标签: google-cloud-platform google-cloud-pubsub google-cloud-run

我有一个已容器化并在云运行内部运行的API。如何获得执行云的当前项目ID?我尝试过:

  • 我在日志的textpayload中看到了它,但是我不确定如何在post函数中读取textpayload吗?我收到的pub子消息缺少此信息。
  • 我已经阅读了查询元数据api的方法,但是关于如何从api再次执行此操作尚不清楚。有链接吗?

还有其他方法吗?

编辑:

在下面进行了一些评论之后,我最终在运行在 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;
        }

更新,它可以工作。我的构建推送失败了,我没有看到。感谢大家。

4 个答案:

答案 0 :(得分:1)

通过向标头为http://metadata.google.internal/computeMetadata/v1/project/project-id的{​​{1}}发送GET请求,即可获得项目ID。

请参见this documentation

例如在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)

  1. 我遵循了教程Using Pub/Sub with Cloud Run tutorial

  2. 我将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
    
  3. 我更改了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)
    
    1. 我检查了日志:

        Hello (pubsub message).
        This is the project my-project-id.
      

答案 2 :(得分:0)

应该可以使用Platformhttps://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_PROJECTGCLOUD_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();
            }