我希望能够等效于:从go113云函数gcloud compute instances add-labels --zone asia-east1-c foobar --labels=hostname=foobar
通过protoPayload.methodName="v1.compute.instances.insert"
触发。
我可以看到这里有一个 API https://cloud.google.com/compute/docs/reference/rest/v1/instances/setLabels,但我希望某种 SDK 能够使这更容易,特别是因为我不太确定 Oauth 是如何工作的,所以我希望找到一个简单的例子来处理这个问题。
我在go链接中找到了方法IDcompute.instances.setLabels
:
type InstancesSetLabelsCall struct {
s *Service
project string
zone string
instance string
instancessetlabelsrequest *InstancesSetLabelsRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// SetLabels: Sets labels on an instance. To learn more about labels,
// read the Labeling Resources documentation.
func (r *InstancesService) SetLabels(project string, zone string, instance string, instancessetlabelsrequest *InstancesSetLabelsRequest) *InstancesSetLabelsCall {
c := &InstancesSetLabelsCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.zone = zone
c.instance = instance
c.instancessetlabelsrequest = instancessetlabelsrequest
return c
}
你可以在这里找到一个简单的例子
您可以为云函数使用的服务账户设置正确的 IAM 权限。 谷歌云功能将使用附加的服务帐户和权限。
参考: https://cloud.google.com/functions/docs/concepts/iam
有关在 Google 计算引擎上以go
语言设置标签的参考 - https://godoc.org/google.golang.org/api/compute/v1#InstancesService.SetLabels
Terraform 是用go
语言编写的,我发现它的源代码对golang
与 GCP 交互的示例很有帮助。例如,https://github.com/terraform-providers/terraform-provider-google/blob/master/google/resource_compute_instance.go#L1039
我遇到困难的原因是我在计算中缺少LabelFingerprint。InstancesSetLabelsRequest call.文档不清楚它是必需的,并且没有抛出错误,因为我相信该操作是异步操作。
s := strings.Split(instanceEvent.ProtoPayload.ResourceName, "/")
project, zone, instance := s[1], s[3], s[5]
log.Printf("Split %s, to project: %s, zone: %s, instance: %s",
s,
project,
zone,
instance)
inst, err := computeService.Instances.Get(project, zone, instance).Do()
if err != nil {
log.Fatal(err)
}
existingLabels := inst.Labels
if existingLabels == nil {
existingLabels = make(map[string]string)
}
existingLabels["hostname"] = instance
log.Println("Applying labels:", existingLabels)
rb := &compute.InstancesSetLabelsRequest{
LabelFingerprint: inst.LabelFingerprint,
Labels: existingLabels,
}