adebrito
adebrito

Reputation: 51

Add startup-script while creating instance in gcp using golang

I am trying to create an instance with a startup-script in gcp using google.golang.org/api/compute/v1. However I am having some problems setting up the metadata to pass the startup-script.

Link to a similar example.

Link to do library documentation.

The function I created is the following one:

func CreateInstance(service *compute.Service, projectId string, instanceName string, zone string) {
    imageURL := "https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140606"
    prefix := "https://www.googleapis.com/compute/v1/projects/" + projectId
    file, err := os.Open("startup-script.sh")
    if err != nil {
        log.Fatal(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,
                },
            },
        },
        ServiceAccounts: []*compute.ServiceAccount{
            {
                Email: "default",
                Scopes: []string{
                    compute.DevstorageFullControlScope,
                    compute.ComputeScope,
                },
            },
        },
        Metadata: &compute.Metadata{
            {
                Items: &compute.MetadataItems{
                    {
                        Key: "startup-script",
                        Value : file,
                    },
                },
            },
        },
    }

    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)
}

However I am getting the following error:

./createInstance.go:54:4: missing type in composite literal
./createInstance.go:54:4: too few values in &compute.Metadata literal

Can someone point what I am doing wrong?

Upvotes: 4

Views: 406

Answers (1)

adebrito
adebrito

Reputation: 51

The problem are the brackets around Metadata. It should be:

Metadata: &compute.Metadata{
                Items: &compute.MetadataItems{
                    {
                        Key: "startup-script",
                        Value : file,
                    },
                },
        }, 

Upvotes: 1

Related Questions