Skip to content

Commit fef4bb0

Browse files
committed
Add jenkins public key to instance
1 parent 4ce4008 commit fef4bb0

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

test/remote/run_remote/run_remote.go

+56
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"context"
2121
"flag"
2222
"fmt"
23+
"io/ioutil"
2324
"math/rand"
2425
"net/http"
2526
"os"
@@ -320,6 +321,18 @@ func createInstance(serviceAccount string) (string, error) {
320321
glog.Infof("Compute service GOT instance %v: %#v", i.Name, gotInstance)
321322
}
322323

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+
323336
then := time.Now()
324337
err = wait.Poll(15*time.Second, 10*time.Minute, func() (bool, error) {
325338
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) {
359372
return name, nil
360373
}
361374

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+
362418
func getexternalIP(instance *compute.Instance) string {
363419
for i := range instance.NetworkInterfaces {
364420
ni := instance.NetworkInterfaces[i]

0 commit comments

Comments
 (0)