使用api和python在gcloud上设置标签

2jcobegt  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(300)

我正在尝试使用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

返回“指纹标签无效或资源标签已更改”。详细信息:“[{'message':'标签指纹无效或资源标签已更改','域':'全局','原因':'条件不满足','位置':'如果匹配','位置类型':'标题'}]”>
我做错了什么?
非常感谢。

e4eetjau

e4eetjau1#

正如错误消息中所述,指纹不匹配,因此无法更新标签,这正是为什么首先要使用指纹-以确保您正在更新您认为正在更新的内容。我同意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'}]

相关问题