Skip to content

Instantly share code, notes, and snippets.

@OsamuTakahashi
Created April 20, 2016 06:50
Show Gist options
  • Save OsamuTakahashi/eaafb3358d558e647946f9fe2e809535 to your computer and use it in GitHub Desktop.
Save OsamuTakahashi/eaafb3358d558e647946f9fe2e809535 to your computer and use it in GitHub Desktop.
Accessing GCE Resources with using the Google API Library
libraryDependencies += "com.google.apis" % "google-api-services-compute" % "v1-rev105-1.21.0"
import com.google.api.client.auth.oauth2.Credential
import com.google.api.client.googleapis.auth.oauth2.{GoogleAuthorizationCodeFlow,GoogleClientSecrets,GoogleCredential}
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.services.compute.{Compute,ComputeScopes}
import java.io.{File,InputStreamReader}
import scala.collection.JavaConversions._
object Main extends App {
final val SERVICE_ACCT = "<<YOUR ACCOUNT>>.apps.googleusercontent.com"
final val SERVICE_ACCT_KEYFILE = "<< YOUR KEY FILE >>.p12"
final val PROJECT_NAME = "<< YOUR PROJECT NAME >>"
final val ZONE_NAME = "us-central1-a"
val httpTransport = GoogleNetHttpTransport.newTrustedTransport()
val jsonFactory = JacksonFactory.getDefaultInstance()
def authorize():Option[GoogleCredential] =
Option(new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCT)
.setServiceAccountPrivateKeyFromP12File(new File(
Main.getClass().getResource("/"+SERVICE_ACCT_KEYFILE).getFile()))
.setServiceAccountScopes(List(ComputeScopes.COMPUTE_READONLY)).build())
def printResources(compute:Compute):Unit = {
Option(compute.instances().list(PROJECT_NAME, ZONE_NAME).execute().getItems()).foreach {
items =>
items.foreach(item => println(item))
}
Option(compute.disks().list(PROJECT_NAME, ZONE_NAME).execute().getItems()).foreach {
disks =>
disks.foreach(println(_))
}
}
authorize().foreach {
c =>
val compute = new Compute.Builder(httpTransport, jsonFactory, null)
.setApplicationName(PROJECT_NAME)
.setHttpRequestInitializer(c)
.build()
printResources(compute)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment