Checkmk
to checkmk.com

1. Introduction

With the Checkmk REST-API as an application programming interface, you can transmit tasks to the Checkmk server by command or script with HTTP requests and have them executed — tasks that you would otherwise perform in Checkmk via the GUI.

The REST in the name of the REST API stands for REpresentational State Transfer, and it describes an architecture for the exchange of data on distributed systems — especially for web services. An API implemented according to the REST architecture follows certain principles, e.g. the client-server model, stateless communication and a uniform interface. In practice the implementation is preferably carried out via the HTTP protocol, whereby the resources are addressed via the Uniform Resource Identifier (URI) and accessed using HTTP methods (GET, POST, PUT, DELETE).

So much for the principles of the REST. The advantages of these principles can be demonstrated by the concrete features provided by the Checkmk REST API:

Protocol

The Hypertext Transfer Protocol (HTTP/1.1) is used as the transport system for communication.

Coding

The JavaScript Object Notation (JSON) is used as the data format. The payload of the answers is serialized with JSON and encoded in UTF-8. Date and time information is encoded in the ISO-8601 format with valid time zone information.

Language

English is the language for labels, identifiers and API documentation.

Authentication

Access to the API is only granted to a client if it has proven its authorization by means of HTTP authentication — 'Bearer' for example.

Versioning

The API is versioned and uses a numbering scheme according to the Semantic Versioning 2.x standard. For details, refer to the section on versioning below.

Documentation

The API is documented in a machine-readable structure, and in a human-readable, English format, and includes all resources, their input and output parameters and their associated value ranges. The API is created with the OpenAPI Specification (OAS) 3.x, an API description format intended especially for REST APIs. The API document created with this specification is displayed to the user with ReDoc, a responsive web design for OpenAPI documents.

Code example

To demonstrate its use, sample code for various applications is provided for each request — curl and httpie for example.

Error display

In the event of an error, the API sends numeric HTTP status codes and a diagnostic message for the problem, which helps to identify possible causes of incorrect requests.

REST API classification

The API fulfills all four levels (0 to 3) of the Richardson Maturity Model (RMM), which can be used to assess how much REST an API contains. Level 1 requires the introduction of resources to enable communication via the API to individual endpoints rather than to a global one. Level 2 is met if HTTP methods are used for the requests. At the (highest) level 3, the API is effectively self-documenting, in that the server, when responding to a request, communicates any possible next actions and the resources to be addressed, thus enabling the client to discover the available functionality for themselves. This provision of additional information is also known as 'Hypermedia as the Engine of Application State' (HATEOAS).

In addition to these general comfort functions, the REST API is intended to cover the complete functionality that in earlier releases of Checkmk was provided via the GUI and a command interface.

CEE For features that exist only in the commercial editions, such as service level agreement (SLA) or Agent Bakery, the associated REST API methods are also provided only in these editions.

2. The API documentation

2.1. Versioning

One of the advantages of the REST API is that both the software and its documentation come from the same source — the OpenAPI document. Thus the API documentation always matches the software and describes exactly what the API can do. Therefore it is not necessary to describe the reference part of the available resources, methods, parameters etc. in the Checkmk User guide — instead you will find the API documentation separately from this manual, directly in your Checkmk site.

The API with its documentation is versioned and uses a two-level numbering scheme in X.Y format, where X stands for a major version and Y for a minor version. A new minor version only contains backward-compatible changes that have no effect on existing functions. A new major version, on the other hand, contains changes that make the API incompatible with the previous major version (so-called breaking changes). The version numbers of the major and minor versions are part of the URL with which a request is sent to the server. The Checkmk REST API is currently not using the third level (.Z) of the Semantic Versioning standard for a patch version.

Note that the REST API follows a different versioning scheme than that for the Checkmk software. Since a new major version of the API is necessary if there are incompatible API changes, this usually does not match the release cycle of the Checkmk software.

Nevertheless, the correlation between the versions of API documentation and Checkmk software is very straightforward, as you will learn in the next chapter.

2.2. Access

The REST API documentation is available in HTML format for viewing in a Web browser.

In the Checkmk GUI, open the API documentation from the navigation bar via Help > Developer resources > REST API documentation. The API documentation is displayed in a new browser window (or browser tab). We will discuss this in more detail in the next chapter.

Help menu in the navigation bar.
Tip

You will surely have noticed that there are more entries covering the REST API in the Help menu. With REST API introduction you can open this article. With REST API interactive GUI you can open another view of the REST API. The entry is called GUI since not only are you shown the REST API functions, but because you can also interact with the API directly from the browser — by sending requests to the server for example. We will introduce the REST API GUI as an alternative to execution by script later in the chapter on the REST API GUI.

2.3. Structure and content

The API documentation uses a responsive web design consisting of three sections:

API documentation in a responsive web design with three sections.
  • The left-hand section, Navigation, is used for orientation, searching and a quick jump to the exact description of the entries in the central section. The table of contents contains one entry for each API endpoint. An endpoint uses a URL to refer to the resource that the API provides (e.g. hosts), together with the method used to access the resource (e.g. GET to display a host). The endpoints are organized into several folders.

  • The central section, Content, contains the hard facts on the documentation: all information for defining a request (with parameters, value ranges, default values and descriptions) and the corresponding answers (also with all details). The possible answers are displayed in different colors, depending on whether the returned HTTP status code signals success or an error.

  • The right-hand section, Request samples, shows the method and URL for the endpoint selected in the content section, followed by several examples of requests: the payload in JSON format (if relevant for the endpoint) and code examples, e.g. for curl, httpie, Python Requests and Python Urllib. Then follow the responses according to the HTTP status. All code examples can be copied to the clipboard with the Copy button.

The navigation section is scroll-synchronized with the other two sections, which means that if you scroll up or down in the content section, the navigation section automatically scrolls to the appropriate entry in the table of contents.

The responsive web design ensures that the example section does not appear in a very narrow browser window (the examples are then displayed below the corresponding method), and the navigation section is converted into a menu.

In all sections you will find content that you can show and hide, for example, the entries for the endpoints in the navigation section, and nested parameters in the content section. By clicking on > or Expand all you can show the hidden contents, and with or Collapse all you can hide them again.

In the next chapter you will learn how you can use the API documentation to create concrete requests from the information, send these requests to the Checkmk server, have them executed and monitor that execution and results.

3. Using the API

3.1. Authentication

In order to use the REST API in the Checkmk server from a client, the client must prove its identity. The REST API supports the following methods for authentication: Bearer, Web server and Cookie — in this order of precedence. This means, for example, that if authentication with Bearer is successful, none of the other methods will be checked.

Bearer or Header authentication

'Bearer' means the holder of an identity. The client authenticates itself with the credentials of a user set up on the Checkmk server. Ideally, this is the so-called automation user, which is provided in Checkmk for the execution of actions via an API. Bearer authentication is recommended for use in scripts.

For authentication, you need the user name and the corresponding so-called automation secret for machine accounts, i.e. the password for the automation user. Both items of information must be transmitted to the Checkmk server in the header of each request. In a newly-created site, the automation user will have already been created. You can find it, like other users, under Setup > Users > Users. Make sure that the roles and associated permissions for the automation user are set to allow you to execute your requests.

For the scripts presented in this article, the automation user is always used as the default example.

Web server authentication

For web server authentication, the REST API uses the HTTP authentication configured for the web server ('Basic' or 'Digest').

This authentication method is intended for large Checkmk installations with special requirements that are realized by using and configuring software modules for authentication of the Apache web server. If you want to use the web server authentication, you need to reconfigure the Apache web server of the Checkmk site itself.

Cookie authentication

Cookie authentication is a special case of authentication by API key. Every Checkmk user who is logged into Checkmk and has been assigned an HTTP cookie can use the REST API. Cookie authentication is used for trying out and testing with the REST API GUI. Whether requests can be executed depends on whether your Checkmk user account has the appropriate permissions.

3.2. HTTP Status Code

The REST API returns the HTTP status code for each request, which you can use to check whether the request was successful. All possible HTTP status codes for the request are listed in the API documentation.

Note that the HTTP status code only provides information about a successful transmission of the request, but not about a successful execution. The commands are executed on the Checkmk server with Livestatus. To be sure that the request via the REST API really does what you intended, you must verify the success yourself. The API documentation, which you can open with Help > Developer resources > REST API interactive GUI, contains an example of a script for this task in the 'Queries through the REST API' section.

3.3. Testing the API locally

To test the REST API, it is advisable to make the requests directly from the Checkmk server, i.e. in this example, the client sending the request and the server receiving it are on the same computer. If you are working as a site user, you can also use local variables such as $OMD_SITE, which refers to the name of the site.

In the following simple examples, we use the sample code contained in the API documentation for the command line program curl, which enables data to be transferred to or from a server without user interaction, for example via HTTP.

Tip

Especially for complex requests, the curl examples may contain inconsistencies and therefore may not always be reliable. With httpie an alternative is available that is consistent, easy to understand and well suited for use in scripts.

The curl command is executed within a bash script. For the preparation, create a script file for each of the requests to be executed in the next section, into which the sample code will later be copied:

OMD[mysite]:~$ touch create_host.sh service_discovery.sh show_pending_changes.sh activate_changes.sh
OMD[mysite]:~$ chmod +x create_host.sh service_discovery.sh show_pending_changes.sh activate_changes.sh

The REST API outputs all responses in a single-line JSON format. Since formatted output makes it much easier to read, the following examples show the single-line output formatted in multiple lines. There are various websites and tools for processing the JSON format, for example the command line JSON processor jq.

Before starting, gather some basic information specific to your Checkmk configuration:

Variable Example value Meaning

HOST_NAME

myserver

The Checkmk server’s hostname

SITE_NAME

mysite

The Checkmk site name

USERNAME

automation

The automation user’s name

PASSWORD

theautomationsecret

The automation user’s password

These variables are used in the sample code and must be edited by you before sending a request. In the table above you will also find the sample values used in the following.

3.4. Making requests using scripts

With a straightforward example we will now demonstrate how to use the REST API. Create a host with its services using a total of four requests. In principle, you proceed in the same way as you would with the Checkmk GUI:

  1. Create a host

  2. Perform a service discovery on the host

  3. Show pending changes

  4. Activate the changes

Creating a host

Open the API documentation and select the entry for creating a host (Create a host) in the left navigation area:

The entry in the API documentation for creating a host.

In the central part of the panel you can see the details for the selected request, which HTTP authentication is required (this is identical for all requests via the REST API), and the required and optional parameters. The name of the host and the folder in which it should be created is required. By default, the host is created in the Main folder. If you want to create the host in another folder, you may first need to make another API request (Show all folders) to view the existing folders to determine the ID of the one you want to use.

In our example, the host myhost123 is to be created with the IP address 192.168.0.42 in the Main folder.

In the API documentation, click the curl button in the right-hand example area and then click Copy to copy the curl sample code to the clipboard. Open the prepared script create_host.sh and paste the clipboard’s contents into it:

create_host.sh
#!/bin/bash

# NOTE: We recommend all shell users to use the "httpie" examples instead.
#       `curl` should not be used for writing large scripts.
#       This code is provided for debugging purposes only.

HOST_NAME="localhost"
SITE_NAME="mysite"
PROTO="http" #[http|https]
API_URL="$PROTO://$HOST_NAME/$SITE_NAME/check_mk/api/1.0"

USERNAME="automation"
PASSWORD="test123"

curl \
  --request POST \
  --write-out "\nxxx-status_code=%{http_code}\n" \
  --header "Authorization: Bearer $USERNAME $PASSWORD" \
  --header "Accept: application/json" \
  --header "Content-Type: application/json" \
  --data '{
          "attributes": {
            "ipaddress": "192.168.0.123"
          },
          "folder": "/",
          "host_name": "example.com"
        }' \
  "$API_URL/domain-types/host_config/collections/all"

In the first part of the sample code you will find the environment variables, then comes the curl command with the POST method on the resource whose URL is in the last line. The -write-out option finally outputs a line with the HTTP status code. The header lines (one of which defines the HTTP authentication) are followed by the data section in which the parameters for the new host are defined.

Note that the curl sample code may contain more parameters than you might need for a specific situation. For our example this is not the case and you only need to change the two existing parameters, host_name and ipaddress.

Now edit the sample code so that the result looks something like this:

create_host.sh
#!/bin/bash

# NOTE: We recommend all shell users to use the "httpie" examples instead.
#       `curl` should not be used for writing large scripts.
#       This code is provided for debugging purposes only.

HOST_NAME="myserver"
SITE_NAME="mysite"
PROTO="http" #[http|https]
API_URL="$PROTO://$HOST_NAME/$SITE_NAME/check_mk/api/1.0"

USERNAME="automation"
PASSWORD="theautomationsecret"

curl \
  --request POST \
  --write-out "\nxxx-status_code=%{http_code}\n" \
  --header "Authorization: Bearer $USERNAME $PASSWORD" \
  --header "Accept: application/json" \
  --header "Content-Type: application/json" \
  --data '{
          "attributes": {
            "ipaddress": "192.168.0.42"
          },
          "folder": "/",
          "host_name": "myhost123"
        }' \
  "$API_URL/domain-types/host_config/collections/all"

Run the script:

OMD[mysite]:~$ ./create_host.sh
{
  "links":[
    {
      "domainType":"link",
      "rel":"self",
      "href":"http://myserver/mysite/check_mk/api/1.0/objects/host_config/myhost123",
      "method":"GET",
      "type":"application/json"
    },
...
    {
      "domainType":"link",
      "rel":"urn:com.checkmk:rels/folder_config",
      "href":"http://myserver/mysite/check_mk/api/1.0/objects/folder_config/~",
      "method":"GET",
      "type":"application/json",
      "title":"The folder config of the host."
    }
  ],
  "domainType":"host_config",
  "id":"myhost123",
  "title":"myhost123",
  "members":{

  },
  "extensions":{
    "folder":"/",
    "attributes":{
      "ipaddress":"192.168.0.42",
      "meta_data":{
        "created_at":"2024-07-03T12:55:29.165920+00:00",
        "updated_at":"2024-07-03T12:55:29.174520+00:00",
        "created_by":"automation"
      }
    },
    "effective_attributes":null,
    "is_cluster":false,
    "is_offline":false,
    "cluster_nodes":null
  }
}
xxx-status_code=200

Reminder: The single line in JSON format delimited by the curly brackets is displayed here in multiple lines.

The API returns under links a selection of requests (abbreviated in our example above), which can be applied to the host that has just been created — as befits a REST API. Finally, the API returns the ID and name (title) of the host created, the folder name (/ for the main folder) and the attributes assigned to the host, including the IP address.

Finally, the line with the HTTP status code is output. The 200 stands for OK and means that the action was carried out successfully.

Perform a service discovery on the host

Once the host myhost123 has been created, its services can be discovered. To ensure that a service discovery actually delivers the expected services, on Linux and Windows hosts you must first install and register their respective agents.

To execute a service discovery via REST API, select the appropriate entry in the API documentation (Execute a service discovery on a host), copy the sample code into the script file created for this purpose and adapt it.

You can copy the first part with the environment variables 1:1 from the previous example. In the curl command, change the name of the host to myhost123 and, if necessary, use the mode parameter to change the type of service discovery.

service_discovery.sh
#!/bin/bash

# NOTE: We recommend all shell users to use the "httpie" examples instead.
#       `curl` should not be used for writing large scripts.
#       This code is provided for debugging purposes only.

HOST_NAME="myserver"
SITE_NAME="mysite"
PROTO="http" #[http|https]
API_URL="$PROTO://$HOST_NAME/$SITE_NAME/check_mk/api/1.0"

USERNAME="automation"
PASSWORD="theautomationsecret"

curl \
  --request POST \
  --write-out "\nxxx-status_code=%{http_code}\n" \
  --header "Authorization: Bearer $USERNAME $PASSWORD" \
  --header "Accept: application/json" \
  --header "Content-Type: application/json" \
  --data '{
          "host_name": "myhost123",
          "mode": "refresh"
        }' \
  "$API_URL/domain-types/service_discovery_run/actions/start/invoke"

Execute this script as well:

OMD[mysite]:~$ ./service_discovery.sh

xxx-status_code=302

The HTTP status code 302 means that the background job for the service discovery has been initialized.

Show pending changes

Before activating the changes, an intermediate step is necessary: displaying the pending changes with the Show all pending changes request. In addition to the changes that have accumulated, the REST API also provides the HTTP ETag (entity tag) that you need to activate these changes. An object is not changed via the REST API using the ID or title of the object. Instead, the generated ETag is used to prevent multiple competing requests from overwriting values of the same object.

The ETag is returned in the response header. To display this header, extend the example code for this request by calling curl with the -i option (for include response headers). The changed lines are also marked again in the following example:

show_pending_changes.sh
#!/bin/bash

# NOTE: We recommend all shell users to use the "httpie" examples instead.
#       `curl` should not be used for writing large scripts.
#       This code is provided for debugging purposes only.

HOST_NAME="myserver"
SITE_NAME="mysite"
PROTO="http" #[http|https]
API_URL="$PROTO://$HOST_NAME/$SITE_NAME/check_mk/api/1.0"

USERNAME="automation"
PASSWORD="theautomationsecret"

curl \
  -i \
  --request GET \
  --write-out "\nxxx-status_code=%{http_code}\n" \
  --header "Authorization: Bearer $USERNAME $PASSWORD" \
  --header "Accept: application/json" \
  "$API_URL/domain-types/activation_run/collections/pending_changes"

After the script has been executed, the header lines are shown first in the output:

OMD[mysite]:~$ ./show_pending_changes.sh
HTTP/1.1 200 OK
Date: Wed, 03 Jul 2024 13:23:26 GMT
...
ETag: "2156db7032754ec778c75123ec12cdd897592b0a574760fa0963a1782c22472c"
...
Content-Type: application/json

{
...
  "domainType":"activation_run",
  "value":[
    {
      "id":"8cb85882-cdae-4d43-b5af-362b4c1cb717",
      "user_id":"automation",
      "action_name":"create-host",
      "text":"Created new host myhost123.",
      "time":"2024-07-03T13:05:07.466406+00:00"
    }
  ]
}
xxx-status_code=200

For clarity the output is shortened here and only the important lines are marked: the header line with the ETag, the attributes of the one pending change to create a host and the HTTP status code for OK. You will need the ETag in the next and final step.

Activate the changes

Finally, the changes must be activated. The appropriate request is called Activate pending changes.

In the curl command, change the header line If-Match and insert the ETag read in the previous section. In the data section change the parameter sites and set it to the name of the site on which the changes should be activated:

activate_changes.sh
#!/bin/bash

# NOTE: We recommend all shell users to use the "httpie" examples instead.
#       `curl` should not be used for writing large scripts.
#       This code is provided for debugging purposes only.

HOST_NAME="myserver"
SITE_NAME="mysite"
PROTO="http" #[http|https]
API_URL="$PROTO://$HOST_NAME/$SITE_NAME/check_mk/api/1.0"

USERNAME="automation"
PASSWORD="1234567890"

curl -L \
  --write-out "\nxxx-status_code=%{http_code}\n" \
  --header "Authorization: Bearer $USERNAME $PASSWORD" \
  --header "Accept: application/json" \
  --header "If-Match: "2156db7032754ec778c75123ec12cdd897592b0a574760fa0963a1782c22472c"" \
  --header "Content-Type: application/json" \
  --data '{
          "force_foreign_changes": false,
          "redirect": false,
          "sites": [
            "mysite"
          ]
        }' \
  "$API_URL/domain-types/activation_run/actions/activate-changes/invoke"

Execute this script:

OMD[mysite]:~$ ./activate_changes.sh
{
  "links":[
    {
      "domainType":"link",
      "rel":"self",
      "href":"http://myserver/mysite/check_mk/api/1.0/objects/activation_run/eddbef05-438b-4108-9a02-0d010da2b290",
      "method":"GET",
      "type":"application/json"
    },
    {
      "domainType":"link",
      "rel":"urn:com.checkmk:rels/wait-for-completion",
      "href":"http://myserver/mysite/check_mk/api/1.0/objects/activation_run/eddbef05-438b-4108-9a02-0d010da2b290/actions/wait-for-completion/invoke",
      "method":"GET",
      "type":"application/json"
    }
  ],
  "domainType":"activation_run",
  "id":"eddbef05-438b-4108-9a02-0d010da2b290",
  "title":"Activation status: In progress.",
  "members":{

  },
  "extensions":{
    "sites":[
      "mysite"
    ],
    "is_running":true,
    "force_foreign_changes":false,
    "time_started":"2024-07-03T13:45:07.031741+00:00",
    "changes":[
      {
        "id":"8cb85882-cdae-4d43-b5af-362b4c1cb717",
        "user_id":"automation",
        "action_name":"create-host",
        "text":"Created new host myhost123.",
        "time":"2024-07-03T13:05:07.466406+00:00"
      }
    ]
  }
}
xxx-status_code=200

The title text indicates that the activation has been started. Again, the REST API suggests two useful follow-up requests under links: to query the status of this activation, and to wait for its completion.

3.5. Making requests via the REST API GUI

With the REST API GUI you get a new perspective on the API. With this GUI you can interact directly with the API from the browser by sending requests to the server via curl commands, and immediately see the responses. To do this, you have to do without the code examples of the REST API documentation in the API GUI — both views are optimized for their respective functions.

The REST API GUI is generated from the same source as the REST API documentation — the OpenAPI document — and therefore always provides functions that match the API.

You open the API GUI in the Checkmk GUI from the navigation bar, menu Help > Developer resources > REST API interactive GUI. The API GUI is displayed in a new browser window (or browser tab):

The entry in the REST API GUI to create a host.

In the following we outline how you can execute the first request from the above example (create a host) with the REST API GUI instead of using a script:

  1. Authenticate: The REST API GUI offers a dialog box for entering authentication information after clicking the Authorize button (on the right side above the entry for the first endpoint folder). However, if you are logged in as a site user, you do not need to make any entries there, as you are authorized to use the REST API as a Checkmk user via cookie authentication.

  2. Select the endpoint: In the Hosts folder, select the endpoint Create a host and click Try it out.

  3. Enter parameter values: In Request body overwrite the example values for host_name and ipaddress.

  4. Send a request: Click Execute.

  5. Check the response: Under Responses you will first see the sent curl command and the URL of the endpoint. Then under Server response the response is displayed with HTTP status code and in Responses with the (multi-line formatted) REST API response.

The REST API GUI therefore offers you the opportunity to try out the functions of the API quickly and easily, and to familiarize yourself with the functions of the input values as well as with concrete responses.

3.6. Error correction

In contrast to the output from successful commands via script shown so far, the REST API shows you errors in the following way:

{
  "title": "The operation has failed.",
  "status": 401,
  "detail": "There are changes from other users and foreign changes are not allowed in this API call."
}
xxx-status_code=401

Depending on the error, the parameters displayed in the output may vary. However, in status the HTTP status code, and in title they always receive a brief description of the cause of the error.

In most cases, detail will show you detailed information, as the name suggests. In the above example, you can see that there are pending changes in Checkmk, but these were initiated by another user. By default, only changes that have also been made via the API can be activated via the API.

In the next example, the helpful messages are also in the detailed information:

{
  "title":"Bad Request",
  "status":400,
  "detail":"These fields have problems: host_name",
  "fields":{
    "host_name":[
      "'my/host123' does not match pattern '^[-0-9a-zA-Z_.]+\\\\Z'."
    ]
  }
}
xxx-status_code=400

The problem in the above example is that a parameter value does not adhere to the valid value range because the host name contains a slash.

The number of possible errors is of course much greater than the two we have presented here. However, you can see from the examples shown that in its output the REST API usually provides sufficient information on the cause and thus gives you clues for starting the analysis and troubleshooting.

4. Securing the API

Since sensitive data can be transferred during access via the REST API and — depending on the authorization of the automation user — considerable alterations could potentially be made to Checkmk, you should secure such access accordingly. Here you will find some of the available options:

  • Checkmk over HTTPS: Use the API exclusively over Hypertext Transfer Protocol Secure (HTTPS), otherwise user names, passwords, and also configuration data will be transmitted in clear text on the network.

  • Give the automation user a password of sufficient length. Since the password is usually only stored in a script, you can easily assign a very long one.

  • Be sure to pay careful attention to the authorization concept for the scripts you use to make requests to the API. The scripts may contain sensitive data such as configuration data, passwords, etc. Therefore make sure that only authorized users and groups can read these scripts.

5. Examples with REST API requests

In this chapter you will find examples that show how to perform commonly needed actions using the REST API. The examples are again based on the sample code for the curl command line program. In contrast to the procedure in the chapter Using the API, however, here the requests are made as curl commands on the command line rather than by script. This allows you to try out our examples right away — after you have customized them to suit your own environment.

In order to present the commands clearly here, we have only shown the lines from the sample code that are absolutely necessary for the command execution.

As with the sample code in the API documentation, the examples in this chapter contain variables for assembling the base URL for the REST API on your Checkmk server and for setting the credentials for the automation user for the Bearer authentication used:

Variable Example value Description

HOST_NAME

myserver

Name of the Checkmk server

SITE_NAME

mysite

Name of the Checkmk site

API_URL

http://$HOST_NAME/$SITE_NAME/check_mk/api/1.0

Base URL of the REST API

USERNAME

automation

Name of the automation user

PASSWORD

theautomationsecret

Password of the automation user

Before issuing the curl commands, you can tailor the variables to suit your environment using the following shell commands:

user@host:~$ HOST_NAME="myserver"; SITE_NAME="mysite"; API_URL="http://$HOST_NAME/$SITE_NAME/check_mk/api/1.0"; \
USERNAME="automation"; PASSWORD="theautomationsecret";

5.1. Hosts and folders

The requests described in this chapter can be found in the API documentation in the Hosts and Folders subfolders. The titles of the respective endpoints contained in the API documentation are the following headings.

Showing all folders

Here all folders in the Setup are displayed — recursively starting from the Main folder — without listing the hosts they contain:

user@host:~$ curl -G \
--request GET \
--header "Authorization: Bearer $USERNAME $PASSWORD" \
--header "Accept: application/json" \
--data-urlencode 'parent=~' \
--data-urlencode 'recursive=true' \
--data-urlencode 'show_hosts=false' \
"$API_URL/domain-types/folder_config/collections/all"

Showing all hosts in a folder

Here the hosts in the Main > Linux subfolder are requested:

user@host:~$ curl \
--request GET \
--header "Authorization: Bearer $USERNAME $PASSWORD" \
--header "Accept: application/json" \
"$API_URL/objects/folder_config/~linux/collections/hosts"

Creating a folder

Here a subfolder Production Hosts is created in Main > Linux — in the file system as the directory production_hosts. The new folder is thereby assigned the Productive system host tag from the predefined host tag group Criticality:

user@host:~$ curl \
--request POST \
--header "Authorization: Bearer $USERNAME $PASSWORD" \
--header "Accept: application/json"     \
--header "Content-Type: application/json" \
--data '{
    "attributes": {
        "tag_criticality": "prod"
    },
    "name": "production_hosts",
    "parent": "~linux",
    "title": "Production Hosts"
    }' \
"$API_URL/domain-types/folder_config/collections/all"

Creating a host

Here, in the Main > Linux > Production Hosts folder, the host mylinuxserver is created with the IP address 192.168.0.123 and the Use piggyback data from other hosts if present host tag:

user@host:~$ curl \
--request POST \
--header "Authorization: Bearer $USERNAME $PASSWORD" \
--header "Accept: application/json" \
--header "Content-Type: application/json" \
--data '{
    "attributes": {
        "ipaddress": "192.168.0.123",
        "tag_piggyback": "auto-piggyback"
    },
    "folder": "~linux~production_hosts",
    "host_name": "mylinuxserver"
    }' \
"$API_URL/domain-types/host_config/collections/all"

Showing a host

By displaying a host you receive a list of the attributes assigned to it. This additionally provides the HTTP ETag (entity tag) that you need to be able to modify a host. You can find out more about the ETag in the Show pending changes section.

The ETag is returned in the response header. To display this header, call curl with the -v option (for verbose). Here the host mylinuxserver is queried — and from the response only the line containing the ETag is shown:

user@host:~$ curl -vG \
--request GET \
--header "Authorization: Bearer $USERNAME $PASSWORD" \
--header "Accept: application/json" \
"$API_URL/objects/host_config/mylinuxserver"
...
< ETag: "57db3792f23bd81ca7447ba4885fa2865d0c78aed4753229b29e179e539da48b"
...

Updating a host

Before making the change, get that host’s ETag as described in the preceding section Show a host. You then enter the ETag in the request header under If-Match. Here, the host tag from the Piggyback group that was specified when the host was created is deleted, and the predefined tag API integrations if configured, else Checkmk agent is specified to replace it:

user@host:~$ curl \
--request PUT \
--header "Authorization: Bearer $USERNAME $PASSWORD" \
--header "Accept: application/json" \
--header "If-Match: "57db3792f23bd81ca7447ba4885fa2865d0c78aed4753229b29e179e539da48b"" \
--header "Content-Type: application/json" \
--data '{
    "remove_attributes": [
        "tag_piggyback"
    ],
    "update_attributes": {
        "tag_agent": "cmk-agent"
    }
    }' \
"$API_URL/objects/host_config/mylinuxserver"

Executing a service discovery on a host

To ensure that a service discovery actually delivers the expected services, on Linux and Windows hosts you must first install and register their respective monitoring agents.

Here, a service discovery is performed on the host mylinuxserver with the refresh option, which corresponds to the Full service scan button in the Checkmk GUI:

user@host:~$ curl \
--request POST \
--header "Authorization: Bearer $USERNAME $PASSWORD" \
--header "Accept: application/json" \
--header "Content-Type: application/json" \
--data '{
    "host_name": "mylinuxserver",
    "mode": "refresh"
    }' \
"$API_URL/domain-types/service_discovery_run/actions/start/invoke"

Bulk host creation

Here, two hosts are created in the Main > Linux > Production Hosts folder: the first host with only an IP address, and the second host with a parent host and two labels in addition to its IP address:

user@host:~$ curl \
--request POST \
--header "Authorization: Bearer $USERNAME $PASSWORD" \
--header "Accept: application/json" \
--header "Content-Type: application/json" \
--data '{
	"entries": [
	{
	"attributes": {
	    "ipaddress": "192.168.0.130"
	},
	"folder": "~linux~production_hosts",
	"host_name": "mylinuxserver02"
	},
	{
	"attributes": {
	    "ipaddress": "192.168.0.131",
	    "parents": [ "router01" ],
	    "labels": {
	    	"color": "blue-metallic",
	    	"admin": "Fozzie Bear"
	    }
	},
	"folder": "~linux~production_hosts",
	"host_name": "mylinuxserver03"
	}
	]
	}' \
"$API_URL/domain-types/host_config/actions/bulk-create/invoke"

Activate pending changes

Before the complex action of renaming a host can be tackled, it is necessary to activate all changes that have accumulated in its configuration environment. Here the changes for the site mysite are all activated in a single action:

user@host:~$ curl \
--request POST \
--header "Authorization: Bearer $USERNAME $PASSWORD" \
--header "Accept: application/json" \
--header "Content-Type: application/json" \
--data '{
    "force_foreign_changes": false,
    "redirect": false,
    "sites": [
        "mysite"
     ]
     }' \
"$API_URL/domain-types/activation_run/actions/activate-changes/invoke"

Renaming a host

A new name is also going to change the host. Therefore, first get the host’s current ETag, e.g. from mylinuxserver, as described in the Show a host section, and enter this into the request header under If-Match. Here the host is being renamed as mylinuxserver01:

user@host:~$ curl \
--request PUT \
--header "Authorization: Bearer $USERNAME $PASSWORD" \
--header "Accept: application/json" \
--header "If-Match: "a200832df1b3c5ebe8f30809177630abbdcf8f7cbd9d0f69bd9f229b359f4d00"" \
--header "Content-Type: application/json" \
--data '{
	"new_name": "mylinuxserver01"
	}' \
"$API_URL/objects/host_config/mylinuxserver/actions/rename/invoke"
On this page