網頁

2024/1/8

Golang 建立GCP執行個體 Create GCP Compute VM instance

Go以Google API Client Libraries來建立GCP執行個體(vm instance)。



事前要求

參考「GCP 設定本機應用程式存取憑證 Application Default Credentials」設定credential。


下載API modules

在專案根目錄執行以下命令下載需要的google-api-go-client modules。



建立執行個體

呼叫compute.InstancesService.Insert輸入project id、zone,和參數compute.Instance建立執行個體。

compute.Instance.MachineType填入機器類型的selflink

compute.Instance.NetworkInterfaces的值為compute.NetworkInterfacecompute.NetworkInterface.Subnetwork填入執行個體所屬子網路(subnet)的selflink。

compute.Instance.Disks的值為compute.AttachedDiskcompute.AttachedDisk.Boot設定是否為開機磁碟。compute.AttachedDisk.InitializeParams的值為compute.AttachedDiskInitializeParamscompute.AttachedDiskInitializeParams.DiskType填入磁碟類型的selflink;compute.AttachedDiskInitializeParams.SourceImage填入OS映像檔的selflink

main.go

package main

import (
    "context"

    compute "google.golang.org/api/compute/v1"
)

func main() {
    ctx := context.Background()
    computeService, err := compute.NewService(ctx)
    if err != nil {
        panic(err)
    }
    projectId := "project-id-1"
    zone := "asia-east1-b"

    instancesService := compute.NewInstancesService(computeService)

    attachDisks := []*compute.AttachedDisk{
        {
            AutoDelete: true,
            Boot:       true,
            InitializeParams: &compute.AttachedDiskInitializeParams{
                DiskName:    "instance-1-boot-disk",
                DiskSizeGb:  20,
                DiskType:    "projects/project-id-1/zones/asia-east1-b/diskTypes/pd-balanced",
                SourceImage: "projects/debian-cloud/global/images/debian-11-bullseye-arm64-v20231212", // OS Image
            },
        },
    }

    instance := &compute.Instance{
        Name:               "instance-1",
        DeletionProtection: false,
        MachineType:        "https://www.googleapis.com/compute/v1/projects/project-id-1/zones/asia-east1-b/machineTypes/e2-small",
        NetworkInterfaces: []*compute.NetworkInterface{
            {
                StackType:  "IPV4_ONLY",
                Subnetwork: "projects/project-id-1/regions/asia-east1/subnetworks/test-east1-b",
            },
        },
        Disks: attachDisks,
    }

    call := instancesService.Insert(projectId, zone, instance)
    _, err = call.Do()
    if err != nil {
        panic(err)
    }

}

github


測試

執行Go應用程式,然後前往GCP console檢視新建的執行個體如下。

執行個體的基本資訊與機器類型資訊。



執行個體的網路與磁碟資訊。




沒有留言:

張貼留言