Milad Jahandideh
Milad Jahandideh

Reputation: 751

Setting labels on GCP Compute Instances using Golang

I was looking for ways to set or update instance Labels on GCP Compute Instance and labelFingerprint confused me.

then I figure it out and I'm putting the code in the answer section.

Upvotes: 1

Views: 282

Answers (1)

Milad Jahandideh
Milad Jahandideh

Reputation: 751

I used this simple code to add new labels to GCP instances.

package main

import (
    "context"
    "log"
    "os"

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

func main() {
    addLabelToGCPInstances()
}

func addLabelToGCPInstances() error {

    // You can pass these as args
    project := "Your GCP Project ID"
    zone := "europe-west2-a"
    instance := "milad-test-instance"
    prodLablesMap := map[string]string{
        "production":  "true",
        "environment": "production",
    }

    ctx := context.Background()

    os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", "gke.json")

    c, err := google.DefaultClient(ctx, compute.CloudPlatformScope)
    if err != nil {
        return err
    }

    computeService, err := compute.New(c)
    if err != nil {
        return err
    }

    respInstance, err := computeService.Instances.Get(project, zone, instance).Context(ctx).Do()
    if err != nil {
        log.Fatal(err)
    }

    rb := &compute.InstancesSetLabelsRequest{
        Labels:           prodLablesMap,
        LabelFingerprint: respInstance.LabelFingerprint,
    }

    respLabels, err := computeService.Instances.SetLabels(project, zone, instance, rb).Context(ctx).Do()
    if err != nil {
        log.Fatal(err)
    }
    _ = respLabels
    return err
}

This is just an example you can work around and do more error handling and etc.

Upvotes: 1

Related Questions