Helllo.
I’m trying to add some new labels to some existing hosts with the following python code but can’t get it to work. What part am I missing?
The Json host_config from “https://admin.example.com/site/check_mk/api/1.0/objects/host_config/server1.example.com” looks like this:
"63a23228b9589b9c29c2241339e100f3530761c17c7821b1caefc5ff0c"
{'domainType': 'host_config',
'extensions': {'attributes': {'labels': {'Test1': 'test1', 'Test2': 'test2'},
'meta_data': {'created_at': '2022-12-01T09:05:11+00:00',
'created_by': 'user',
'updated_at': '2023-02-09T22:35:58.956734+00:00'}},
'cluster_nodes': None,
'effective_attributes': None,
'folder': '/admin_folder/customers/customer1/linux-servers/linux',
'is_cluster': False,
'is_offline': False},
'id': 'server1.example.com',
And here is the python script I’m using. But for some reason it’s not adding any new labels or updating the old ones:
#!/usr/bin/env python5
import json
import urllib.request
import pprint
HOST_NAME = "https://admin.example.com"
SITE_NAME = "site"
API_URL = f"https://{HOST_NAME}/{SITE_NAME}/check_mk/api/1.0"
USERNAME = "user"
PASSWORD = "pass"
HOSTNAME = "server1.example.com"
query_string = urllib.parse.urlencode({
})
request = urllib.request.Request(
f"{API_URL}/objects/host_config/{HOSTNAME}?{query_string}",
method="GET",
headers={
"Authorization": f"Bearer {USERNAME} {PASSWORD}",
"Accept": "application/json",
},
)
response = urllib.request.urlopen(request)
if response.status == 200:
etag = str(response.headers["ETag"])
print(etag)
f"{API_URL}/objects/host_config/{HOSTNAME}",
method="PUT",
headers={
"Authorization": f"Bearer {USERNAME} {PASSWORD}",
"Accept": "application/json",
"If-Match": etag, # (required) The value of the, to be modified, object's ETag header.
"Content-Type": 'application/json', # (required) A header specifying which type of content is in the request/response body.
},
data=json.dumps({
"update_attributes": {
"labels":{
"Test2": "test123",
"Test3": "test3"
}
}
}).encode('utf-8'),
response = urllib.request.urlopen(request)
if response.status == 200:
pprint.pprint(json.loads(response.read()))
elif response.status == 204:
print("Done")
else:
raise RuntimeError(response.read())
Thank you.