Google Cloud Platform: Hello World with Service Account

In my last post, I showed a sample with OAuth. It works well for application on others’ behalves. For the hello world program, it’s better to run without any user’s manual interaction. Google has provided “Service Account Key” for that purpose.

When you create a new credential, the console asks the type of key. You can select the service account key, and then select the “Compute engine default service account” with P12 as the key type. The generated key will be downloaded automatically. Save it safely and it cannot download again. You can then copy the key to the project home with a name as key.p12.

Lost VMs or Containers? Too Many Consoles? Too Slow GUI? Time to learn how to "Google" and manage your VMware and clouds in a fast and secure HTML5 App.

For the service account id, I did not find it anywhere on the console GUI. But luckily I found one from the OAuth JSON file. Just copy it over.

package org.doublecloud.googleclouddemo;
 
import com.google.api.client.auth.oauth2.Credential;
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.jackson2.JacksonFactory;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.ComputeScopes;
import com.google.api.services.compute.model.Disk;
import com.google.api.services.compute.model.DiskList;
import com.google.api.services.compute.model.Instance;
import com.google.api.services.compute.model.InstanceList;
import com.google.api.services.compute.model.Network;
import com.google.api.services.compute.model.NetworkList;
import com.google.api.services.compute.model.Project;
import java.io.File;
 
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
 
public class ComputeEngineServiceAccount
{
  private static final String APPLICATION_NAME = "doublecloud/1.0";
 
  /** project name must be lower case even you see ComputeEngineDemo on GUI */
  private static final String projectId = "computeenginedemo";
  private static final List<String> SCOPES = Arrays.asList(ComputeScopes.COMPUTE);
 
  public static void main(String[] args) throws IOException, GeneralSecurityException, Exception
  {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
 
    // Authorize
    Credential credential = new GoogleCredential.Builder()
      .setTransport(httpTransport)
      .setJsonFactory(JacksonFactory.getDefaultInstance())
      .setServiceAccountId("1007174531741-compute@developer.gserviceaccount.com")
      .setServiceAccountScopes(SCOPES)
      .setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
      .build();
 
    // Create compute engine object
    Compute compute = new Compute.Builder(httpTransport, JacksonFactory.getDefaultInstance(), null)
      .setApplicationName(APPLICATION_NAME)
      .setHttpRequestInitializer(credential)
      .build();
 
    Project proj = compute.projects().get(projectId).execute();
    System.out.println(proj.toPrettyString());
 
 
    Compute.Instances.List instances = compute.instances().list(projectId, "us-central1-a");
    InstanceList list = instances.execute();
    for (Instance instance : list.getItems())
    {
      System.out.println(instance.toPrettyString());
    }
  }
}

The program runs by itself and you will see output similar to that of last program using OAuth. Therefore, the output is omitted here.

This entry was posted in Cloud Computing, Software Development and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Posted April 15, 2016 at 9:02 am | Permalink

    Thanks for this guys – I will be sure to try a few of these out and I will be sharing – Great work.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  • NEED HELP?


    My company has created products like vSearch ("Super vCenter"), vijavaNG APIs, EAM APIs, ICE tool. We also help clients with virtualization and cloud computing on customized development, training. Should you, or someone you know, need these products and services, please feel free to contact me: steve __AT__ doublecloud.org.

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.