CreateInstance creates a GCE instance with provided spec.
(instance Instance, imageName string, imageProject string)
| 41 | |
| 42 | // CreateInstance creates a GCE instance with provided spec. |
| 43 | func CreateInstance(instance Instance, imageName string, imageProject string) (Instance, error) { |
| 44 | if instance.MachineType == "" { |
| 45 | instance.MachineType = "n1-standard-1" |
| 46 | } |
| 47 | |
| 48 | p, err := instance.ComputeService.Projects.Get(instance.Project).Do() |
| 49 | if err != nil { |
| 50 | return instance, fmt.Errorf("failed to get project info %q: %v", instance.Project, err) |
| 51 | } |
| 52 | |
| 53 | i := &compute.Instance{ |
| 54 | Name: instance.Name, |
| 55 | MachineType: fmt.Sprintf("zones/%s/machineTypes/%s", instance.Zone, instance.MachineType), |
| 56 | NetworkInterfaces: []*compute.NetworkInterface{ |
| 57 | { |
| 58 | AccessConfigs: []*compute.AccessConfig{ |
| 59 | { |
| 60 | Type: "ONE_TO_ONE_NAT", |
| 61 | Name: "External NAT", |
| 62 | }, |
| 63 | }}, |
| 64 | }, |
| 65 | Disks: []*compute.AttachedDisk{ |
| 66 | { |
| 67 | AutoDelete: true, |
| 68 | Boot: true, |
| 69 | Type: "PERSISTENT", |
| 70 | InitializeParams: &compute.AttachedDiskInitializeParams{ |
| 71 | SourceImage: fmt.Sprintf("projects/%s/global/images/%s", imageProject, imageName), |
| 72 | DiskSizeGb: 20, |
| 73 | }, |
| 74 | }, |
| 75 | }, |
| 76 | ServiceAccounts: []*compute.ServiceAccount{ |
| 77 | { |
| 78 | Email: p.DefaultServiceAccount, |
| 79 | Scopes: []string{ |
| 80 | "https://www.googleapis.com/auth/cloud-platform", |
| 81 | }, |
| 82 | }, |
| 83 | }, |
| 84 | } |
| 85 | |
| 86 | if _, err := instance.ComputeService.Instances.Get(instance.Project, instance.Zone, instance.Name).Do(); err != nil { |
| 87 | op, err := instance.ComputeService.Instances.Insert(instance.Project, instance.Zone, i).Do() |
| 88 | if err != nil { |
| 89 | ret := fmt.Sprintf("could not create instance %s: API error: %v", instance.Name, err) |
| 90 | if op != nil { |
| 91 | ret = fmt.Sprintf("%s: %v", ret, op.Error) |
| 92 | } |
| 93 | return instance, fmt.Errorf(ret) |
| 94 | } else if op.Error != nil { |
| 95 | return instance, fmt.Errorf("could not create instance %s: %+v", instance.Name, op.Error) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | instanceRunning := false |
| 100 | // Waiting for the instance to be SSH-able by retrying SSH with timeout of 5 min (15*20sec) |
no test coverage detected