4

There is 'gcloud compute ssh' command that allows to connect to Google Cloud instance and execute commands in console. How can I do that via Java GCloud API?

2 Answers2

0

Although this isn't exactly what the question asks, in some instances one might want to open an SSH terminal to start something when the instance comes up. One alternative, using the Java API, is to attach a startup-script metadata value:

Metadata meta = new Metadata();
meta.put("startup-script", "#! /bin/bash\necho \"hello\"" );
instance.setMetadata(meta);

Documentation: https://cloud.google.com/compute/docs/startupscript

Charlie
  • 8,530
  • 2
  • 55
  • 53
0

To achieve this you need the following:

  1. SSH Client Library for Java, such as Java Secure Channel
  2. Authenticate the SSH session using this tutorial

Based on the tutorial you are going to follow:

To run an SSH application on an instance

When applications running on your instances require SSH access to other instances, you can manage the SSH key pairs for your service account and execute SSH commands programmatically. This is the guide that you need.

To run an SSH application outside of Compute Engine

Otherwise, if you run this application outside of a Compute Engine instance, the client library cannot access the service account and its permissions unless you provide the service account key manually. This is the guide that you need.


Notice that the example used in the tutorial I shared with you, they use Python; nonetheless, it should be the same for Java.

sllopis
  • 2,292
  • 1
  • 8
  • 13