Levun
Levun

Reputation: 37

GCP Set label for compute instances and getting googleapiclient.errors

Using below python code to add the labels on specific instances:

from pprint import pprint
import googleapiclient.discovery


compute = googleapiclient.discovery.build('compute', 'v1')
projectid='XXXXXXXXX'
zones=['australia-southeast1-b','australia-southeast1-a']
ip_list=[]
instance_list=[]

with open(r"D:\Users\xxxxxxxDesktop\Scripts\GCP\GCP-IP.txt") as f:
    for line in f:
        line = line.strip()
        ip_list.append(line)
print(ip_list)

for zo in zones:
    result = compute.instances().list(project=projectid, zone=zo).execute()
    for i in result['items']:
        for ip in ip_list:
            if i["networkInterfaces"][0]["networkIP"] == ip:
                instance_list.append({"ins_name" : i["name"], 
                                    "fp" : i["tags"]["fingerprint"], 
                                    "ins_zon":(i["zone"]).split("/")[-1]})
print(instance_list)

for instance in instance_list:
    print(instance.get('fp'))
    instances_set_labels_request_body = {
        "labels": {
            "shutdown": "no"
            },
        "LabelFingerprint":instance.get('fp')
        }
    request=compute.instances().setLabels(project=projectid, zone=instance.get('ins_zon'), instance=instance.get('ins_name'), body=instances_set_labels_request_body)
    response = request.execute()

======================================================================================= Error: googleapiclient.errors.HttpError: <HttpError 412 when requesting https://compute.googleapis.com/compute/v1/projects/xxxxxxx/zones/australia-southeast1-b/instances/dxxxxxx/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'}]">

Upvotes: 0

Views: 596

Answers (1)

JGBMattos
JGBMattos

Reputation: 1

I had the same issue, except I was building a bash script.

In my case I forgot to add the Content-Type header to application/json (-H "Content-Type: application/json")

Curl was sending the request as application/x-www-form-urlencoded and likely was breaking GCP parsing of my request.

Upvotes: 0

Related Questions