I am trying to set label and labels fingerprint for a VM instance programmatically, on Java.
Here is how I implemented it.
public void addLabelsToInstance(String projectId, String zone,String instanceName,String labelKey, String labelVal) throws IOException, ApiException {
try (InstancesClient instancesClient = InstancesClient.create()) {
Instance instance = instancesClient.get(projectId, zone, instanceName);
// String fprintVal = instance.getMetadata().getFingerprint();
Map<String, String> labels = new HashMap<>(instance.getLabelsMap());
labels.put(labelKey, labelVal);
/* Map<String, String> labelsMap = instance.getLabelsMap();
labelsMap.put(labelKey,labelVal);*/
String fingerprint = instance.getLabelFingerprint();
// Add the label to the current instance
instance = instance.toBuilder().putAllLabels(labels).setLabelFingerprint(fingerprint).build();
int labelsCount = instance.getLabelsCount();
SetLabelsInstanceRequest request = SetLabelsInstanceRequest.newBuilder()
.setProject(projectId)
.setZone(zone)
.setInstance(instance.getName()).build();
// Update the labels for the instance
ApiFuture<Operation> operationFuture = instancesClient.setLabelsAsync(request);
Operation operation = operationFuture.get();
if (operation.hasError()) {
System.err.println("Error updating instance labels: " + operation.getError());
} else {
System.out.println("Instance labels updated successfully.");
}
// Print the updated instance with labels
System.out.println("Labels Count :"+labelsCount);
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
}
I am getting below error stack.
Caused by: com.google.api.client.http.HttpResponseException: 412 Precondition Failed
POST https://compute.googleapis.com:443/compute/v1/projects/sab-dev-avps-1715/zones/us-central1-a/instances/ansible01/setLabels
{
"error": {
"code": 412,
"message": "Labels fingerprint either invalid or resource labels have changed",
"errors": [
{
"message": "Labels fingerprint either invalid or resource labels have changed",
"domain": "global",
"reason": "conditionNotMet",
"location": "If-Match",
"locationType": "header"
}
]
}
}
After adding label fingerprints still, I am facing issues. How to resolve this?