REST API how to add/delete hosts to/from a host group

Hi all,

I am using the Check_MK REST API in conjunction with our own internal CMDB, to populate hosts in Check_MK based on the information in our CMDB(which is automatically updated via a discovery mechanism). The following all works well;-
Add Hosts (including folder and label assignments)
Delete Hosts
Update Hosts (including folder and label assignments)
Perform Service Discovery
Activate Changes

What I cant seem to find is a way to add hosts to a host groups. I can create host groups with the REST API without issue, but there does not appear to be a way to add hosts to the host groups, or create/delete host group rules. Is this not possible with the V2 REST API?

Any suggestions on how I might achieve this, I need to create the rules in a script as they are dynamic in nature due to the information I extract from our CMDB.

Thanks

Mark

With the REST API you can create rules in the ruleset “Assignment of hosts to host groups”. There you can assign X hosts to one host group per rule. If you want to delete a host from a group you then would need to edit the rule.

Thanks for the quick response, can you point me to the documentation for this, I cannot find anything in the REST API docs that allows me to create rules?..or have I lost the plot :rofl:

Editing rules with the REST API is possible with version 2.1 onwards.

You can just go to “Help” in the lower-left corner and go to REST API documentation. There you can find anything including “Rules” under “SETUP”.

FYI I’m running 2.1.0p4 (if the documentation differs from yours)

That explains it I was on v2.0, not v2.1…thought I was going mad :upside_down_face:

Thanks

Could you please explain how this should function? In the docs I can only find GET for rulesets but no POST.

I also want to create a rule for “Assignment of hosts to host groups” but can’t find how.

Thanks
Martin

1 Like

What doc are you using? POST to create a rule is documented.
Just go to the i on the top left corner of your checkmk instance and click on REST API documentation

I used the checkmk built-in Swagger UI and also ReDoc but on rulesets there are no POST requests available. I can find POST only on rules but there is no “Assignment of hosts to host groups” possible like in the checkmk webfrontend (if you create a hostgroup rule manually).

Thanks
Martin

Edit: I have Checkmk Raw Edition 2.2.0b5, maybe this is only available on a higher tier level?

Well, you won’t find a POST in the rulesets - because you can’t create rulesets, only rules.
The “internal” name you can use with the API for Assignment of Hosts to host groups is host_groups.

An python example would be:

#!/usr/bin/env python3
import pprint
import requests

HOST_NAME = "localhost"
SITE_NAME = "cmk"
API_URL = f"http://{HOST_NAME}/{SITE_NAME}/check_mk/api/1.0"

USERNAME = "automation"
PASSWORD = "test123"

session = requests.session()
session.headers['Authorization'] = f"Bearer {USERNAME} {PASSWORD}"
session.headers['Accept'] = 'application/json'

resp = session.post(
    f"{API_URL}/domain-types/rule/collections/all",
    headers={
        "Content-Type": 'application/json',  # (required) A header specifying which type of content is in the request/response body.
    },
    json={
        'ruleset': 'host_groups',
        'folder': '~some_folder',
        'properties': {
            'disabled': False
        },
        'value_raw': "'the_host_group'",
        'conditions': {}
    },
)
if resp.status_code == 200:
    pprint.pprint(resp.json())
elif resp.status_code == 204:
    print("Done")
else:
    raise RuntimeError(pprint.pformat(resp.json()))
1 Like

Thanks for your reply paulr282, but with your code I get this error:

RuntimeError: {'detail': 'These fields have problems: ruleset_name',
 'fields': {'ruleset_name': ['Missing data for required field.']},
 'status': 400,
 'title': 'Bad Request'}

In bash I get:

{
  "title": "Bad Request",
  "status": 400,
  "detail": "These fields have problems: value_raw",
  "fields": {
    "value_raw": [
      "Not a Python data structure: 'MyHostGroup'"
    ]
  }
}

Any ideas?

Thanks
Martin

1 Like

Sorry, i did this one a bit freestyle without testing. This is out of the interactive API:

{
  "ruleset": "host_label_rules",
  "folder": "~hosts~linux",
  "properties": {
    "disabled": false
  },
  "value_raw": "\"{'cmk/os_family': 'linux'}\"",
  "conditions": {}
}

Place this in the json from above and edit the attributes to your needs.
1 Like

Thanks for you suggestion, but this does not work. I’m a little lost on this. What am I doing wrong?

I tried both:

  json={
        'ruleset': 'host_label_rules',
        'folder': '/folder/subfolder',
        'properties': {
            'disabled': False
        },
        'value_raw': "\"{'MyHostGroup'}\"",
        'conditions': {}
  }

and:

  json={
        'ruleset': 'host_label_rules',
        'folder': '/folder/subfolder',
        'properties': {
            'disabled': False
        },
        'value_raw': "\"{'Assignment of hosts to host groups': 'MyHostGroup'}\"",
        'conditions': {}
  }

Throws:

raise RuntimeError(pprint.pformat(resp.json()))
RuntimeError: {‘detail’: ‘These fields have problems: ruleset_name’,
‘fields’: {‘ruleset_name’: [‘Missing data for required field.’]},
‘status’: 400,
‘title’: ‘Bad Request’

Thanks
Martin

1 Like

Hi,

The ruleset should be host_groups, your folder should be ~folder (at least I had the best experience doing it like that) and the value_raw should be your Hostgroup like you did. I would recommend you to create a rule in the UI and then make a GET request, look at the JSON structure and compare it with yours and edit it to your needs.

1 Like

Thanks paulr282 for your help! I got it to work like this:

--data '{
        "ruleset": "host_groups",
        "folder": "~folder/subfolder",
        "properties": {
                "description": "MyHostGroup",
                "disabled": false
        },
        "value_raw": "\"MyHostGroup\"",
        "conditions": {}
    }'

Thanks
Martin

1 Like

Great. That looks good.

1 Like

Worked here. Thanks a lot!