Hello,
Thank you all for some great advice and help!
As I am really not that familiar with Python, I choose to write in Powershell (with some help of AI). For reference → REST API Host anlegen mit Label (Powershell) - #3 by Lars
# Configuration
$HOST_NAME = "hostname"
$SITE_NAME = "sitename"
$API_URL_BASE = "http://$HOST_NAME/$SITE_NAME/check_mk/api/1.0"
$USERNAME = "username"
$PASSWORD = "password"
# Prepare headers for API requests
$Credentials = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${USERNAME}:${PASSWORD}"))
$Headers = @{
'Accept' = 'application/json'
'Authorization' = "Basic $Credentials"
'Content-Type' = 'application/json'
}
# Function to get all hosts
function Get-Hosts {
$url = "$API_URL_BASE/domain-types/host_config/collections/all"
$response = Invoke-RestMethod -Uri $url -Method Get -Headers $Headers
return $response._embedded.host_config
}
# Function to get services for a host
function Get-ServicesForHost {
param(
[string]$HostId
)
$url = "$API_URL_BASE/domain-types/service_config/collections/all?host=$HostId"
$response = Invoke-RestMethod -Uri $url -Method Get -Headers $Headers
return $response._embedded.service_config
}
# Function to update a host with a label
function Update-HostLabel {
param(
[string]$HostId,
[string]$LabelKey,
[string]$LabelValue
)
$url = "$API_URL_BASE/domain-types/host_config/objects/$HostId"
$body = @{
"attributes" = @{
"labels" = @{
$LabelKey = $LabelValue
}
}
} | ConvertTo-Json
Write-Output ("Updating host " + $HostId + " with label " + $LabelKey + ": " + $LabelValue)
Write-Output ("Request Body: " + $body)
try {
$response = Invoke-RestMethod -Uri $url -Method Put -Headers $Headers -Body $body
Write-Output ("Response: " + ($response | ConvertTo-Json))
} catch {
Write-Output ("Error updating label: " + $_.Exception.Message)
}
}
# Main script
$hosts = Get-Hosts
foreach ($host in $hosts) {
$hostId = $host.id
$services = Get-ServicesForHost -HostId $hostId
$labels = @{}
foreach ($service in $services) {
if ($service.title -eq "Service1") {
$labels["Service1"] = "yes"
}
if ($service.title -eq "Service2") {
$labels["Service2"] = "yes"
}
}
foreach ($label in $labels.GetEnumerator()) {
Update-HostLabel -HostId $hostId -LabelKey $label.Key -LabelValue $label.Value
}
}
Write-Output "Labels updated successfully."
As I execute the .ps1 script I only get the “Labels updated successfully.” When I check the hosts there are still no labels.
Am I missing something here?
Thank you!