使用其Id获取Google云项目编号

3okqufwl  于 2022-10-22  发布在  Go
关注(0)|答案(8)|浏览(192)

我有谷歌云服务帐户和projectId,希望从Java以编程方式获取projectNumber。


小时
我怎样才能得到它?
基本上,我有服务帐户,并希望使用它为帐户授予角色“roles/storage.legacyBucketWriter”project-XXXXXXX@storage-transfer-service.iam.gserviceaccount.com“在谷歌云存储桶中。

ghhkc1vu

ghhkc1vu1#

不确定他们为什么不直接公开它,但您可以这样做(假设您当前的配置项目与所需的项目编号相对应):

gcloud projects list \
--filter="$(gcloud config get-value project)" \
--format="value(PROJECT_NUMBER)"
c0vxltue

c0vxltue2#

我认为GCP没有提供将项目IDMap到项目编号的API。但是在你得到项目列表之后,他们确实提供了一个项目列表API。您可以自己绘制项目编号。

kuhbmx9i

kuhbmx9i3#

现在有一个API。
cloudresourcemanager java库的jar版本直接支持它,如这里的示例https://cloud.google.com/resource-manager/reference/rest/v1/projects/get所示
使用maven依赖项,您可以
pom.xml

<!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-cloudresourcemanager -->
<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-cloudresourcemanager</artifactId>
    <version>v2-rev20200617-1.30.9</version>
</dependency>

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.7</version>
</dependency>

CloudResourceManager示例。java(改编自Google的示例)

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.cloudresourcemanager.CloudResourceManager;
import com.google.api.services.cloudresourcemanager.model.Project;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;

import org.apache.commons.io.IOUtils
import com.google.api.client.http.GenericUrl;
import java.nio.charset.StandardCharsets;

public class CloudResourceManagerExample {
  public static void main(String args[]) throws IOException, GeneralSecurityException {
    // The Project ID (for example, `my-project-123`).
    // Required.
    String projectId = "my-project-id"; // TODO: Update placeholder value.

    CloudResourceManager cloudResourceManagerService = createCloudResourceManagerService();

    String response = IOUtils.toString(cloudResourceManagerService.getRequestFactory().buildGetRequest(new GenericUrl("https://cloudresourcemanager.googleapis.com/v1/projects/" + projectId)).execute().getContent(), StandardCharsets.UTF_8);

    // TODO: Change code below to process the `response` object:
    System.out.println(response);
  }

  public static CloudResourceManager createCloudResourceManagerService()
      throws IOException, GeneralSecurityException {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    if (credential.createScopedRequired()) {
      credential =
          credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
    }

    return new CloudResourceManager.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName("Google-CloudResourceManagerSample/0.1")
        .build();
  }
}

response将类似于{"projectNumber": "123456", ...}
在python中,你可以


# python3 -m pip install google.auth google-api-python-client

# from https://github.com/GoogleCloudPlatform/python-docs-samples/blob/main/iam/api-client/quickstart.py

import google.auth
import googleapiclient.discovery
def initialize_service():
    """Initializes a Cloud Resource Manager service."""

    credentials, _ = google.auth.default(
        scopes=["https://www.googleapis.com/auth/cloud-platform"]
    )
    crm_service = googleapiclient.discovery.build(
        "cloudresourcemanager", "v1", credentials=credentials
    )
    return crm_service

crm_service = initialize_service()
project = r.get(projectId=MY_PROJECT_ID).execute()
yqyhoc1h

yqyhoc1h4#

尽管这个问题是针对Java的,但对于那些可能觉得它有用的人来说,这里有一个程序可以从Go中的ID获取Google项目编号:

package main

import (
    "context"
    "flag"
    "fmt"
    "log"

    "google.golang.org/api/cloudresourcemanager/v1"
)

var projectID string

func main() {
    flag.StringVar(&projectID, "projectID", "", "Google Cloud Project ID")
    flag.Parse()

    cloudresourcemanagerService, err := cloudresourcemanager.NewService(context.Background())
    if err != nil {
        log.Fatalf("NewService: %v", err)
    }

    project, err := cloudresourcemanagerService.Projects.Get(projectID).Do()
    if err != nil {
        log.Fatalf("Get project: %v", err)
    }

    fmt.Printf("Project number for project %s: %d\n", projectID, project.ProjectNumber)
}

您可以这样运行:

> go run main.go --projectID="my-project"
Project number for project my-project: 123456789817

(请注意,此示例使用Google应用程序默认凭据(参见。https://godoc.org/google.golang.org/api/cloudresourcemanager/v1#hdr-Creating_a_client))。

bq8i3lrv

bq8i3lrv5#

您只需使用gcloud projects describe <<project_id>>documentation

$ gcloud projects describe XXX
createTime: ...
lifecycleState: ...
name: ...
parent:
  id: ...
  type: ...
projectId: XXX
projectNumber: 'YYY'
bf1o4zei

bf1o4zei6#

我的答案在Java中没有任何作用,但应该在许多环境中工作,例如bashzsh,使用开发期间或容器化环境中大多数人都可以访问的工具。
假设您正在使用某种类型的构建过程,您可以简单地:
1.将以下命令放入docker容器,
1.在构建步骤中输出结果(项目编号),以及
1.将其存储在环境变量中,以便在其他步骤中使用。

使用gcloudgrepawk

  • 这假设您在PROJECT_NAME环境变量中设置了字符串项目名称*

这是一个使用Google Cloud SDK和常用CLI工具grepawk的超级简单的解决方案:

gcloud projects list | grep '${PROJECT_NAME} ' | awk '{print $3}'
  • 注:我怀疑很多项目的大客户可能不想在每次需要单个项目编号时查询整个列表。对于这些情况,@erkolson的答案可能是最好的解决方案*
pbpqsu0x

pbpqsu0x7#

有一个api列表可以提供它,从命令行可以是:

gcloud projects list --filter="$(gcloud config get-value project)" --format="value(PROJECT_NUMBER)"

还可以获得项目id:

gcloud projects list --filter="$(gcloud config get-value project)" --format="value(PROJECT_ID)"
c2e8gylq

c2e8gylq8#

此gcloud命令将返回项目编号:

gcloud projects describe $PROJECT_ID --format="value(projectNumber)"

然后,您可以在命令中使用它来授予访问权限,例如:

gcloud projects add-iam-policy-binding $PROJECT_ID  --member=serviceAccount:$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")@@storage-transfer-service.iam.gserviceaccount.com --role=roles/storage.legacyBucketWriter

相关问题