【问题标题】:Add startup-script while creating instance in gcp using golang使用 golang 在 gcp 中创建实例时添加启动脚本
【发布时间】:2020-03-20 16:13:26
【问题描述】:

我正在尝试使用 google.golang.org/api/compute/v1 在 gcp 中创建一个带有启动脚本的实例。但是我在设置元数据以传递启动脚本时遇到了一些问题。

链接到类似的example

链接到做库documentation

我创建的函数如下:

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

但是我收到以下错误:

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

有人可以指出我做错了什么吗?

【问题讨论】:

  • 您正在指定一个文件句柄,我认为这是不正确的。包括指向您正在使用的 SDK 文档的链接。这样可以加快回答此类问题的速度。

标签: go google-cloud-platform startupscript


【解决方案1】:

问题是元数据周围的括号。应该是:

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

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 2021-06-19
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2017-08-15
    相关资源
    最近更新 更多