@@ -20,6 +20,7 @@ import (
20
20
"context"
21
21
"flag"
22
22
"fmt"
23
+ "io/ioutil"
23
24
"math/rand"
24
25
"net/http"
25
26
"os"
@@ -320,6 +321,18 @@ func createInstance(serviceAccount string) (string, error) {
320
321
glog .Infof ("Compute service GOT instance %v: %#v" , i .Name , gotInstance )
321
322
}
322
323
324
+ pubkey , ok := os .LookupEnv ("JENKINS_GCE_SSH_PUBLIC_KEY_FILE" )
325
+ if ok {
326
+ glog .Infof ("Running on Jenkins and JENKINS_GCE_SSH_PUBLIC_KEY_FILE set" )
327
+ // If we're on CI add ServiceAccount Keys to the instance
328
+ err = addPubKeyToInstance (* project , * zone , i .Name , pubkey )
329
+ if err != nil {
330
+ return "" , fmt .Errorf ("could not add Jenkins Public Key %v to instance %v: %v" , pubkey , i .Name , err )
331
+ }
332
+ } else {
333
+ glog .Infof ("JENKINS_GCE_SSH_PUBLIC_KEY_FILE not set, not adding SSH Public Key to Instance" )
334
+ }
335
+
323
336
then := time .Now ()
324
337
err = wait .Poll (15 * time .Second , 10 * time .Minute , func () (bool , error ) {
325
338
glog .V (2 ).Infof ("Waiting for instance %v to come up. %v elapsed" , name , time .Since (then ))
@@ -359,6 +372,49 @@ func createInstance(serviceAccount string) (string, error) {
359
372
return name , nil
360
373
}
361
374
375
+ func addPubKeyToInstance (project , zone , name , pubKeyFile string ) error {
376
+ found := false
377
+ i , err := computeService .Instances .Get (project , zone , name ).Do ()
378
+ if err != nil {
379
+ return err
380
+ }
381
+ fingerprint := i .Metadata .Fingerprint
382
+ items := i .Metadata .Items
383
+ for _ , item := range items {
384
+ if item .Key == "ssh-keys" {
385
+ found = true
386
+ }
387
+ }
388
+ newKeys := ""
389
+ if found {
390
+ // Append these to newKeys first
391
+ glog .Infof ("Found existing public keys on instance %v" , name )
392
+ }
393
+ glog .Infof ("Public key file: %v" , pubKeyFile )
394
+ publicKey , err := ioutil .ReadFile (pubKeyFile )
395
+ if err != nil {
396
+ return err
397
+ }
398
+
399
+ newKeys += string (publicKey ) + "\n "
400
+ glog .Infof ("New Keys: %v" , newKeys )
401
+ newMeta := & compute.Metadata {
402
+ Fingerprint : fingerprint ,
403
+ Items : []* compute.MetadataItems {
404
+ & compute.MetadataItems {
405
+ Key : "ssh-keys" ,
406
+ Value : & newKeys ,
407
+ },
408
+ },
409
+ }
410
+ _ , err = computeService .Instances .SetMetadata (project , zone , name , newMeta ).Do ()
411
+ if err != nil {
412
+ return err
413
+ }
414
+ return nil
415
+
416
+ }
417
+
362
418
func getexternalIP (instance * compute.Instance ) string {
363
419
for i := range instance .NetworkInterfaces {
364
420
ni := instance .NetworkInterfaces [i ]
0 commit comments