使用API和Python在Gcloud上设置标签

2024-09-24 06:28:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用API和Python添加一个新标签。我有下面的代码,无论我如何修改它,我总是会出错

我在这里使用了指南: https://cloud.google.com/compute/docs/reference/rest/v1/instances/setLabels

instances_list=list_instances(compute, "terraform-313709", "europe-west3-a")
#Getting the current labelFingerprint
labelFingerprint_value=instances_list[0]['labelFingerprint']

#Setting the labels
instances_set_labels_request_body = {
"labels": {
    "key": "value"
},
"LabelFingerprint": labelFingerprint_value
}
request = service.instances().setLabels(project="terraform-313709", zone="europe-west3-a", instance="terraform-instance", body=instances_set_labels_request_body)
print(request)
response = request.execute()

我得到的全部错误是:

googleapiclient.errors.HttpError: <HttpError 412 when requesting https://compute.googleapis.com/compute/v1/projects/terraform-313709/zones/europe-west3-a/instances/terraform-instance/setLabels?alt=json

returned "Labels fingerprint either invalid or resource labels have changed". Details: "[{'message': 'Labels fingerprint either invalid or resource labels have changed', 'domain': 'global', 'reason': 'conditionNotMet', 'location': 'If-Match', 'locationType': 'header'}]">

我做错了什么

多谢各位


Tags: instancesinstancehttpscomlabelsvaluerequestbody
1条回答
网友
1楼 · 发布于 2024-09-24 06:28:26

正如错误消息中所述,指纹不匹配,因此无法更新标签,这正是为什么首先要使用指纹-以确保您正在更新您认为正在更新的内容。我同意John的观点,您正在更新的实例很可能与您从中获取指纹的实例不同。尝试打印实例列表[0],查看“名称”是否与“地形实例”匹配

我尝试了这个小代码(如果它们的名称以“gke”开头,那么它会更新所有的节点,使其具有“goog gke node”的标签),看起来一切都很好:

from pprint import pprint
from time import sleep

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials

credentials = GoogleCredentials.get_application_default()

compute = discovery.build('compute', 'v1', credentials=credentials)
project = '<PROJECT_ID>'
zone = '<INSTANCE_ZONE>'

def get_instances():
    instances = []

    request = compute.instances().list(project=project, zone=zone)
    while request is not None:
        response = request.execute()

        for instance in response['items']:
          instances.append({'name': instance.get('name'),
                            'labels': instance.get('labels', {}),
                            'labelFingerprint': instance.get('labelFingerprint')})

        request = compute.instances().list_next(previous_request=request,
                                                previous_response=response)
    return instances

def set_labels(instances, new_labels={}):
    for instance in instances:
        if instance['name'].startswith('gke'):
            instance['labels'].update(new_labels)

            instances_set_labels_request_body = {
                'labels': instance['labels'],
                'labelFingerprint': instance['labelFingerprint']
            }
            request = compute.instances().setLabels(project=project,
                                                    zone=zone,
                                                    instance=instance['name'],
                                                    body=instances_set_labels_request_body)
            response = request.execute()

# get instances before changes
instances = get_instances()
pprint(instances)

set_labels(instances, {'goog-gke-node': ''})

sleep(10) # just to make sure the labels are updates,
          # terrible, but gets the job done for this example code
          # TODO: needs more elegant solution

# get instances after changes
instances = get_instances()
pprint(instances)

这将产生以下输出:

[{'labelFingerprint': '22Wm4pB8r1M=',
  'labels': {},
  'name': 'gke-cluster-1-default-pool-112c2c29b29-m2hn'},
 {'labelFingerprint': '22Wm4pB8r1M=',
  'labels': {},
  'name': 'gke-cluster-1-default-pool-112c2c29b29-tpdm'},
 {'labelFingerprint': '22Wm4pB8r1M=',
  'labels': {},
  'name': 'gke-cluster-1-default-pool-112c2c29b29-xc2n'}]

[{'labelFingerprint': '3ixRn02sGuM=',
  'labels': {'goog-gke-node': ''},
  'name': 'gke-cluster-1-default-pool-112c2c29b29-m2hn'},
 {'labelFingerprint': '3ixRn02sGuM=',
  'labels': {'goog-gke-node': ''},
  'name': 'gke-cluster-1-default-pool-112c2c29b29-tpdm'},
 {'labelFingerprint': '3ixRn02sGuM=',
  'labels': {'goog-gke-node': ''},
  'name': 'gke-cluster-1-default-pool-112c2c29b29-xc2n'}]

相关问题 更多 >