GCP API 客户端库 Java 示例 - com.google.api.services.deploymentmanager.DeploymentManager

GCP API Client Libraries Java Examples - com.google.api.services.deploymentmanager.DeploymentManager

我希望使用 Deployment Manager 自动配置 google 云资源。只有我想使用 JAVA API 库而不是 gcloud。

具体需要使用 DeploymentManager 配置以下组件。

  1. 云 SQL - MSSQL
  2. 云运行服务
  3. 带有连接器的 VPC 网络用于连接云 运行 云 SQL。

我认为com.google.api.services.deploymentmanager.DeploymentManager是起点,但我不太确定。

这是我目前所拥有的


        Builder builder = new Builder(
                com.google.api.client.googleapis.javanet.GoogleNetHttpTransport.newTrustedTransport(),
                new com.google.api.client.json.gson.GsonFactory(), null);
        builder.setApplicationName("spatial-cat-319209");
        builder.setDeploymentManagerRequestInitializer(new DeploymentManagerRequestInitializer());
        DeploymentManager deploymentManager = builder.build();

        deploymentManager.deployments().list("spatial-cat-319209").entrySet().stream().forEach(entry -> {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        });
        
        System.out.println(System.getProperty("GOOGLE_APPLICATION_CREDENTIALS"));
        System.out.println(System.getenv("GOOGLE_APPLICATION_CREDENTIALS"));
        
        deploymentManager.deployments().list("spatial-cat-319209").execute();

我在最后一行收到以下错误:

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
GET https://deploymentmanager.googleapis.com/deploymentmanager/v2/projects/spatial-cat-319209/global/deployments
{
  "code": 401,
  "errors": [
    {
      "domain": "global",
      "location": "Authorization",
      "locationType": "header",
      "message": "Login Required.",
      "reason": "required"
    }
  ],
  "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
  "status": "UNAUTHENTICATED"
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:118)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:37)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.interceptResponse(AbstractGoogleClientRequest.java:428)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1111)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:514)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:455)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:565)

我确实有环境变量 GOOGLE_APPLICATION_CREDENTIALS 指向包含服务帐户密钥的文件(使用 gcloud auth application-default login 命令生成)

任何见解都会很有帮助。

好的,看来我已经可以使用下面的代码了。

我已经演示了如何使用 processbuilder 和 DeploymentManager API 使用 gcloud 命令。我必须使用 GoogleCredentials 来读取服务帐户密钥文件并将其传递给 HttpCredentialsAdapter。

很难找到,但 this guide 派上用场了。发布 link 作为后来偶然发现的人的参考。

让我知道是否可以用更好的方式来完成。

        GoogleCredentials googleCredentials = GoogleCredentials
                .fromStream(new FileInputStream(System.getenv("GOOGLE_APPLICATION_CREDENTIALS")));
        HttpRequestInitializer httpRequestInitializer = new HttpCredentialsAdapter(googleCredentials);

        Builder builder = new Builder(
                com.google.api.client.googleapis.javanet.GoogleNetHttpTransport.newTrustedTransport(),
                com.google.api.client.json.gson.GsonFactory.getDefaultInstance(), httpRequestInitializer);
        builder.setApplicationName("spatial-cat-319209");
        builder.setDeploymentManagerRequestInitializer(new DeploymentManagerRequestInitializer());
        DeploymentManager deploymentManager = builder.build();

        deploymentManager.deployments().list("spatial-cat-319209").entrySet().stream().forEach(entry -> {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        });

        System.out.println(System.getProperty("GOOGLE_APPLICATION_CREDENTIALS"));
        System.out.println(System.getenv("GOOGLE_APPLICATION_CREDENTIALS"));
        System.out.println("Listing deployments in project using gcloud command ...");
        // Runtime.getRuntime().exec("gcloud deployment-manager deployments list");
        ProcessBuilder processBuilder = new ProcessBuilder();
        Process process = processBuilder.command("powershell", "gcloud", "deployment-manager", "deployments", "list")
                .start();
        InputStreamReader isr = new InputStreamReader(process.getInputStream());
        BufferedReader rdr = new BufferedReader(isr);
        String line = "";
        while ((line = rdr.readLine()) != null) {
            System.out.println(line);
        }

        isr = new InputStreamReader(process.getErrorStream());
        rdr = new BufferedReader(isr);
        while ((line = rdr.readLine()) != null) {
            System.out.println(line);
        }
        int rc = process.waitFor(); // Wait for the process to complete
        System.out.println("Return Code = " + rc);

        System.out.println("Listing deployments in project using DeploymentManager API...");

        DeploymentsListResponse deploymentsListResponse = deploymentManager.deployments().list("spatial-cat-319209")
                .execute();

        System.out.println("Number of deployments = " + deploymentsListResponse.size());
        deploymentsListResponse.forEach((depl, a) -> System.out.println(depl + " - " + a));

        System.out.println("Done");