1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
compute "google.golang.org/api/compute/v1"
"google.golang.org/api/googleapi"
)
func init() {
scopes := strings.Join([]string{
compute.DevstorageFullControlScope,
compute.ComputeScope,
}, " ")
registerDemo("compute", scopes, computeMain)
}
func computeMain(client *http.Client, argv []string) {
if len(argv) != 2 {
fmt.Fprintln(os.Stderr, "Usage: compute project_id instance_name (to start an instance)")
return
}
service, err := compute.New(client)
if err != nil {
log.Fatalf("Unable to create Compute service: %v", err)
}
projectId := argv[0]
instanceName := argv[1]
prefix := "https://www.googleapis.com/compute/v1/projects/" + projectId
imageURL := "https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140606"
zone := "us-central1-a"
// Show the current images that are available.
res, err := service.Images.List(projectId).Do()
log.Printf("Got compute.Images.List, err: %#v, %v", res, err)
instance := &compute.Instance{
Name: instanceName,
Description: "compute sample instance",
MachineType: prefix + "/zones/" + zone + "/machineTypes/n1-standard-1",
Disks: []*compute.AttachedDisk{
{
AutoDelete: true,
Boot: true,
Type: "PERSISTENT",
InitializeParams: &compute.AttachedDiskInitializeParams{
DiskName: "my-root-pd",
SourceImage: imageURL,
},
},
},
NetworkInterfaces: []*compute.NetworkInterface{
&compute.NetworkInterface{
AccessConfigs: []*compute.AccessConfig{
&compute.AccessConfig{
Type: "ONE_TO_ONE_NAT",
Name: "External NAT",
},
},
Network: prefix + "/global/networks/default",
},
},
ServiceAccounts: []*compute.ServiceAccount{
{
Email: "default",
Scopes: []string{
compute.DevstorageFullControlScope,
compute.ComputeScope,
},
},
},
}
op, err := service.Instances.Insert(projectId, zone, instance).Do()
log.Printf("Got compute.Operation, err: %#v, %v", op, err)
etag := op.Header.Get("Etag")
log.Printf("Etag=%v", etag)
inst, err := service.Instances.Get(projectId, zone, instanceName).IfNoneMatch(etag).Do()
log.Printf("Got compute.Instance, err: %#v, %v", inst, err)
if googleapi.IsNotModified(err) {
log.Printf("Instance not modified since insert.")
} else {
log.Printf("Instance modified since insert.")
}
}
|