1 # <a id="icinga2-api"></a> Icinga 2 API
3 ## <a id="icinga2-api-setup"></a> Setting up the API
5 You can run the CLI command `icinga2 api setup` to enable the
6 `api` [feature](11-cli-commands.md#enable-features) and set up
7 certificates as well as a new API user `root` with an auto-generated password in the
8 `/etc/icinga2/conf.d/api-users.conf` configuration file:
12 Make sure to restart Icinga 2 to enable the changes you just made:
14 # service icinga2 restart
16 If you prefer to set up the API manually, you will have to perform the following steps:
18 * Set up X.509 certificates for Icinga 2
19 * Enable the `api` feature (`icinga2 feature enable api`)
20 * Create an `ApiUser` object for authentication
22 The next chapter provides a quick overview of how you can use the API.
24 ## <a id="icinga2-api-introduction"></a> Introduction
26 The Icinga 2 API allows you to manage configuration objects
27 and resources in a simple, programmatic way using HTTP requests.
29 The URL endpoints are logically separated allowing you to easily
32 * query, create, modify and delete [config objects](12-icinga2-api.md#icinga2-api-config-objects)
33 * perform [actions](12-icinga2-api.md#icinga2-api-actions) (reschedule checks, etc.)
34 * subscribe to [event streams](12-icinga2-api.md#icinga2-api-event-streams)
35 * [manage configuration packages](12-icinga2-api.md#icinga2-api-config-management)
36 * evaluate [script expressions](12-icinga2-api.md#icinga2-api-console)
38 ### <a id="icinga2-api-requests"></a> Requests
40 Any tool capable of making HTTP requests can communicate with
41 the API, for example [curl](http://curl.haxx.se).
43 Requests are only allowed to use the HTTPS protocol so that
44 traffic remains encrypted.
46 By default the Icinga 2 API listens on port `5665` which is shared with
47 the cluster stack. The port can be changed by setting the `bind_port` attribute
48 for the [ApiListener](9-object-types.md#objecttype-apilistener)
49 object in the `/etc/icinga2/features-available/api.conf`
52 Supported request methods:
56 GET | Retrieve information about configuration objects. Any request using the GET method is read-only and does not affect any objects.
57 POST | Update attributes of a specified configuration object.
58 PUT | Create a new object. The PUT request must include all attributes required to create a new object.
59 DELETE | Remove an object created by the API. The DELETE method is idempotent and does not require any check if the object actually exists.
61 All requests apart from `GET` require that the following `Accept` header is set:
63 Accept: application/json
65 Each URL is prefixed with the API version (currently "/v1").
67 ### <a id="icinga2-api-responses"></a> Responses
69 Successful requests will send back a response body containing a `results`
70 list. Depending on the number of affected objects in your request, the
71 `results` list may contain more than one entry.
73 The output will be sent back as a JSON object:
80 "status": "Object was created."
87 > Future versions of Icinga 2 might set additional fields. Your application
88 > should gracefully handle fields it is not familiar with, for example by
91 ### <a id="icinga2-api-http-statuses"></a> HTTP Statuses
93 The API will return standard [HTTP statuses](https://www.ietf.org/rfc/rfc2616.txt)
94 including error codes.
96 When an error occurs, the response body will contain additional information
97 about the problem and its source.
99 A status code between 200 and 299 generally means that the request was
102 Return codes within the 400 range indicate that there was a problem with the
103 request. Either you did not authenticate correctly, you are missing the authorization
104 for your requested action, the requested object does not exist or the request
107 A status in the range of 500 generally means that there was a server-side problem
108 and Icinga 2 is unable to process your request.
110 ### <a id="icinga2-api-authentication"></a> Authentication
112 There are two different ways for authenticating against the Icinga 2 API:
114 * username and password using HTTP basic auth
117 In order to configure a new API user you'll need to add a new [ApiUser](9-object-types.md#objecttype-apiuser)
118 configuration object. In this example `root` will be the basic auth username
119 and the `password` attribute contains the basic auth password.
121 # vim /etc/icinga2/conf.d/api-users.conf
123 object ApiUser "root" {
127 Alternatively you can use X.509 client certificates by specifying the `client_cn`
128 the API should trust. The X.509 certificate has to be signed by the CA certificate
129 that is configured in the [ApiListener](9-object-types.md#objecttype-apilistener) object.
131 # vim /etc/icinga2/conf.d/api-users.conf
133 object ApiUser "root" {
134 client_cn = "CertificateCommonName"
137 An `ApiUser` object can have both authentication methods configured.
139 You can test authentication by sending a GET request to the API:
141 $ curl -k -s -u root:icinga 'https://localhost:5665/v1'
143 In case you get an error message make sure to check the API user credentials.
145 When using client certificates for authentication you'll need to pass your client certificate
146 and private key to the curl call:
148 $ curl -k --cert example.localdomain.crt --key example.localdomain.key 'https://example.localdomain:5665/v1/status'
150 In case of an error make sure to verify the client certificate and CA.
152 The curl parameter `-k` disables certificate verification and should therefore
153 only be used for testing. In order to securely check each connection you'll need to
154 specify the trusted CA certificate using the curl parameter`--cacert`:
156 $ curl -u root:icinga --cacert ca.crt 'icinga2.node1.localdomain:5665/v1'
158 Read the next chapter on [API permissions](12-icinga2-api.md#icinga2-api-permissions)
159 in order to configure authorization settings for your newly created API user.
161 ### <a id="icinga2-api-permissions"></a> Permissions
163 By default an API user does not have any permissions to perform
164 actions on the URL endpoints.
166 Permissions for API users must be specified in the `permissions` attribute
167 as array. The array items can be a list of permission strings with wildcard
170 Example for an API user with all permissions:
172 permissions = [ "*" ]
174 Note that you can use wildcards. Here's another example that only allows the user
175 to perform read-only object queries for hosts and services:
177 permissions = [ "objects/query/Host", "objects/query/Service" ]
179 You can also further restrict permissions by specifying a filter expression. The
180 filter expression has to be a [lambda function](17-language-reference.md#nullary-lambdas)
181 which must return a boolean value.
183 The following example allows the API user to query all hosts and services which have a
184 custom attribute `os` that matches the regular expression `^Linux`.
188 permission = "objects/query/Host"
189 filter = {{ regex("^Linux", host.vars.os) }}
192 permission = "objects/query/Service"
193 filter = {{ regex("^Linux", service.vars.os) }}
197 More information about filters can be found in the [filters](12-icinga2-api.md#icinga2-api-filters) chapter.
199 Available permissions for specific URL endpoints:
201 Permissions | URL Endpoint | Supports Filters
202 ------------------------------|---------------|-----------------
203 actions/<action> | /v1/actions | Yes
204 config/query | /v1/config | No
205 config/modify | /v1/config | No
206 objects/query/<type> | /v1/objects | Yes
207 objects/create/<type> | /v1/objects | No
208 objects/modify/<type> | /v1/objects | Yes
209 objects/delete/<type> | /v1/objects | Yes
210 status/query | /v1/status | Yes
211 events/<type> | /v1/events | No
212 console | /v1/console | No
214 The required actions or types can be replaced by using a wildcard match ("\*").
216 ### <a id="icinga2-api-parameters"></a> Parameters
218 Depending on the request method there are two ways of
219 passing parameters to the request:
221 * JSON object as request body (all request methods other than `GET`)
222 * Query string as URL parameter (all request methods)
224 Reserved characters by the HTTP protocol must be [URL-encoded](https://en.wikipedia.org/wiki/Percent-encoding)
225 as query string, e.g. a space character becomes `%20`.
227 Example for a URL-encoded query string:
229 /v1/objects/hosts?filter=match(%22example.localdomain*%22,host.name)&attrs=host.name&attrs=host.state
231 Here are the exact same query parameters as a JSON object:
233 { "filter": "match(\"example.localdomain*\",host.name)", "attrs": [ "host.name", "host.state" ] }
235 ### <a id="icinga2-api-requests-method-override"></a> Request Method Override
237 `GET` requests do not allow you to send a request body. In case you cannot pass everything as URL parameters (e.g. complex filters or JSON-encoded dictionaries) you can use the `X-HTTP-Method-Override` header. This comes in handy when you are using HTTP proxies disallowing `PUT` or `DELETE` requests too.
239 Query an existing object by sending a `POST` request with `X-HTTP-Method-Override: GET` as request header:
241 $ curl -k -s -u 'root:icinga' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts'
243 Delete an existing object by sending a `POST` request with `X-HTTP-Method-Override: DELETE` as request header:
245 $ curl -k -s -u 'root:icinga' -H 'X-HTTP-Method-Override: DELETE' -X POST 'https://localhost:5665/v1/objects/hosts/example.localdomain'
247 ### <a id="icinga2-api-filters"></a> Filters
249 #### <a id="icinga2-api-simple-filters"></a> Simple Filters
251 By default actions and queries operate on all objects unless further restricted by the user. For
252 example, the following query returns all `Host` objects:
254 https://localhost:5665/v1/objects/hosts
256 If you're only interested in a single object, you can limit the output to that object by specifying its name:
258 https://localhost:5665/v1/objects/hosts?host=localhost
260 **The name of the URL parameter is the lower-case version of the type the query applies to.** For
261 example, for `Host` objects the URL parameter therefore is `host`, for `Service` objects it is
264 You can also specify multiple objects:
266 https://localhost:5665/v1/objects/hosts?hosts=first-host&hosts=second-host
268 Again -- like in the previous example -- the name of the URL parameter is the lower-case version of the type. However, because we're specifying multiple objects here the **plural form** of the type is used.
270 When specifying names for objects which have composite names like for example services the
271 full name has to be used:
273 https://localhost:5665/v1/objects/services?service=localhost!ping6
275 The full name of an object can be obtained by looking at the `__name` attribute.
277 #### <a id="icinga2-api-advanced-filters"></a> Advanced Filters
279 Most of the information provided in this chapter applies to both permission filters (as used when
280 configuring `ApiUser` objects) and filters specified in queries.
282 Advanced filters allow users to filter objects using lambda expressions. The syntax for these filters is the same like for [apply rule expressions](3-monitoring-basics.md#using-apply-expressions).
286 > Filters used as URL parameter must be URL-encoded. The following examples
287 > are **not URL-encoded** for better readability.
289 Example matching all services in NOT-OK state:
291 https://localhost:5665/v1/objects/services?filter=service.state!=ServiceOK
293 Example matching all hosts by name:
295 https://localhost:5665/v1/objects/hosts?filter=match("example.localdomain*",host.name)
297 Example for all hosts which are in the host group `linux-servers`:
299 https://localhost:5665/v1/objects/hosts?filter="linux-servers" in host.groups
301 User-specified filters are run in a sandbox environment which ensures that filters cannot
302 modify Icinga's state, for example object attributes or global variables.
304 When querying objects of a specific type the filter expression is evaluated for each object
305 of that type. The object is made available to the filter expression as a variable whose name
306 is the lower-case version of the object's type name.
308 For example when querying objects of type `Host` the variable in the filter expression is named
309 `host`. Additionally related objects such as the host's check command are also made available
310 (e.g., via the `check_command` variable). The variable names are the exact same as for the `joins`
311 query parameter; see [object query joins](12-icinga2-api.md#icinga2-api-config-objects-query-joins)
314 The object is also made available via the `obj` variable. This makes it easier to build
315 filters which can be used for more than one object type (e.g., for permissions).
317 Some queries can be performed for more than just one object type. One example is the 'reschedule-check'
318 action which can be used for both hosts and services. When using advanced filters you will also have to specify the
319 type using the `type` parameter:
321 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \
322 -d '{ "type": "Service", "filter": "service.name==\"ping6\"" }' | python -m json.tool
324 When building filters you have to ensure that values such as
325 `"linux-servers"` are escaped properly according to the rules of the Icinga 2 configuration
328 To make using the API in scripts easier you can use the `filter_vars` attribute to specify
329 variables which should be made available to your filter expression. This way you don't have
330 to worry about escaping values:
332 $ curl -k -s -u 'root:icinga' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts' \
333 -d '{ "filter": "host.vars.os == os", "filter_vars": { "os": "Linux" } }'
335 We're using X-HTTP-Method-Override here because the HTTP specification does
336 not allow message bodies for GET requests.
338 The `filters_vars` attribute can only be used inside the request body, but not as
339 a URL parameter because there is no way to specify a dictionary in a URL.
341 ## <a id="icinga2-api-config-objects"></a> Config Objects
343 Provides methods to manage configuration objects:
345 * [creating objects](12-icinga2-api.md#icinga2-api-config-objects-create)
346 * [querying objects](12-icinga2-api.md#icinga2-api-config-objects-query)
347 * [modifying objects](12-icinga2-api.md#icinga2-api-config-objects-modify)
348 * [deleting objects](12-icinga2-api.md#icinga2-api-config-objects-delete)
350 ### <a id="icinga2-api-config-objects-cluster-sync"></a> API Objects and Cluster Config Sync
352 Newly created or updated objects can be synced throughout your
353 Icinga 2 cluster. Set the `zone` attribute to the zone this object
354 belongs to and let the API and cluster handle the rest.
356 Objects without a zone attribute are only synced in the same zone the Icinga instance belongs to.
360 > Cluster nodes must accept configuration for creating, modifying
361 > and deleting objects. Ensure that `accept_config` is set to `true`
362 > in the [ApiListener](9-object-types.md#objecttype-apilistener) object
365 If you add a new cluster instance, or reconnect an instance which has been offline
366 for a while, Icinga 2 takes care of the initial object sync for all objects
369 ### <a id="icinga2-api-config-objects-query"></a> Querying Objects
371 You can request information about configuration objects by sending
372 a `GET` query to the `/v1/objects/<type>` URL endpoint. `<type` has
373 to be replaced with the plural name of the object type you are interested
376 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts'
378 A list of all available configuration types is available in the
379 [object types](9-object-types.md#object-types) chapter.
381 The following URL parameters are available:
383 Parameters | Type | Description
384 -----------|--------------|----------------------------
385 attrs | string array | **Optional.** Limits attributes in the output.
386 joins | string array | **Optional.** Join related object types and their attributes (`?joins=host` for the entire set, or selectively by `?joins=host.name`).
387 meta | string array | **Optional.** Enable meta information using `?meta=used_by`. Defaults to disabled.
389 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) may be provided.
391 Instead of using a filter you can optionally specify the object name in the
392 URL path when querying a single object. For objects with composite names
393 (e.g. services) the full name (e.g. `localhost!http`) must be specified:
395 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/services/localhost!http'
397 You can limit the output to specific attributes using the `attrs` URL parameter:
399 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts/example.localdomain?attrs=name&attrs=address' | python -m json.tool
404 "name": "example.localdomain"
405 "address": "192.168.1.1"
409 "name": "example.localdomain",
415 #### <a id="icinga2-api-config-objects-query-result"></a> Object Queries Result
417 Each response entry in the results array contains the following attributes:
419 Attribute | Type | Description
420 -----------|------------|--------------
421 name | string | Full object name.
422 type | string | Object type.
423 attrs | dictionary | Object attributes (can be filtered using the URL parameter `attrs`).
424 joins | dictionary | [Joined object types](12-icinga2-api.md#icinga2-api-config-objects-query-joins) as key, attributes as nested dictionary. Disabled by default.
425 meta | dictionary | Contains `used_by` object references. Disabled by default, enable it using `?meta=used_by` as URL parameter.
427 #### <a id="icinga2-api-config-objects-query-joins"></a> Object Query Joins
429 Icinga 2 knows about object relations. For example it can optionally return
430 information about the host when querying service objects.
432 The following query retrieves all host attributes:
434 https://localhost:5665/v1/objects/services?joins=host
436 Instead of requesting all host attributes you can also limit the output to specific
439 https://localhost:5665/v1/objects/services?joins=host.name&joins=host.address
441 You can request that all available joins are returned in the result set by using
442 the `all_joins` query parameter.
444 https://localhost:5665/v1/objects/services?all_joins=1
448 > For performance reasons you should only request attributes which your application
451 The following joins are available:
453 Object Type | Object Relations (`joins` prefix name)
454 -------------|------------------------------------------
455 Service | host, check\_command, check\_period, event\_command, command\_endpoint
456 Host | check\_command, check\_period, event\_command, command\_endpoint
457 Notification | host, service, command, period
458 Dependency | child\_host, child\_service, parent\_host, parent\_service, period
462 Here's an example that retrieves all service objects for hosts which have had their `os`
463 custom attribute set to `Linux`. The result set contains the `display_name` and `check_command`
464 attributes for the service. The query also returns the host's `name` and `address` attribute
467 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/services?attrs=display_name&attrs=check_command&joins=host.name&joins=host.address&filter=host.vars.os==%22Linux%22' | python -m json.tool
473 "check_command": "ping4",
474 "display_name": "ping4"
478 "address": "192.168.1.1",
479 "name": "example.localdomain"
483 "name": "example.localdomain!ping4",
488 "check_command": "ssh",
489 "display_name": "ssh"
493 "address": "192.168.1.1",
494 "name": "example.localdomain"
498 "name": "example.localdomain!ssh",
504 In case you want to fetch all [comments](9-object-types.md#objecttype-comment)
505 for hosts and services, you can use the following query URL (similar example
508 https://localhost:5665/v1/objects/comments?joins=host&joins=service
510 ### <a id="icinga2-api-config-objects-create"></a> Creating Config Objects
512 New objects must be created by sending a PUT request. The following
513 parameters need to be passed inside the JSON body:
515 Parameters | Type | Description
516 -----------|--------------|--------------------------
517 templates | string array | **Optional.** Import existing configuration templates for this object type.
518 attrs | dictionary | **Required.** Set specific object attributes for this [object type](9-object-types.md#object-types).
520 The object name must be specified as part of the URL path. For objects with composite names (e.g. services)
521 the full name (e.g. `localhost!http`) must be specified.
523 If attributes are of the Dictionary type, you can also use the indexer format. This might be necessary to only override specific custom variables and keep all other existing custom variables (e.g. from templates):
525 "attrs": { "vars.os": "Linux" }
527 Example for creating the new host object `example.localdomain`:
529 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
530 -d '{ "templates": [ "generic-host" ], "attrs": { "address": "192.168.1.1", "check_command": "hostalive", "vars.os" : "Linux" } }' \
531 | python -m json.tool
536 "status": "Object was created."
541 If the configuration validation fails, the new object will not be created and the response body
542 contains a detailed error message. The following example is missing the `check_command` attribute
543 which is required for host objects:
545 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
546 -d '{ "attrs": { "address": "192.168.1.1", "vars.os" : "Linux" } }' \
547 | python -m json.tool
553 "Error: Validation failed for object 'example.localdomain' of type 'Host'; Attribute 'check_command': Attribute must not be empty."
555 "status": "Object could not be created."
560 Service objects must be created using their full name ("hostname!servicename") referencing an existing host object:
562 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/services/localhost!realtime-load' \
563 -d '{ "templates": [ "generic-service" ], "attrs": { "check_command": "load", "check_interval": 1,"retry_interval": 1 } }'
566 Example for a new CheckCommand object:
568 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/checkcommands/mytest' \
569 -d '{ "templates": [ "plugin-check-command" ], "attrs": { "command": [ "/usr/local/sbin/check_http" ], "arguments": { "-I": "$mytest_iparam$" } } }'
572 ### <a id="icinga2-api-config-objects-modify"></a> Modifying Objects
574 Existing objects must be modified by sending a `POST` request. The following
575 parameters need to be passed inside the JSON body:
577 Parameters | Type | Description
578 -----------|------------|---------------------------
579 attrs | dictionary | **Required.** Set specific object attributes for this [object type](9-object-types.md#object-types).
581 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) should be provided.
583 **Note**: Modified attributes do not trigger a re-evaluation of existing
584 static [apply rules](3-monitoring-basics.md#using-apply) and [group assignments](3-monitoring-basics.md#group-assign-intro).
585 Delete and re-create the objects if you require such changes.
588 If attributes are of the Dictionary type, you can also use the indexer format:
590 "attrs": { "vars.os": "Linux" }
592 The following example updates the `address` attribute and the custom attribute `os` for the `example.localdomain` host:
594 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
595 -d '{ "attrs": { "address": "192.168.1.2", "vars.os" : "Windows" } }' \
596 | python -m json.tool
601 "name": "example.localdomain",
602 "status": "Attributes updated.",
609 ### <a id="icinga2-api-config-objects-delete"></a> Deleting Objects
611 You can delete objects created using the API by sending a `DELETE`
614 Parameters | Type | Description
615 -----------|---------|---------------
616 cascade | boolean | **Optional.** Delete objects depending on the deleted objects (e.g. services on a host).
618 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) should be provided.
620 Example for deleting the host object `example.localdomain`:
622 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE 'https://localhost:5665/v1/objects/hosts/example.localdomain?cascade=1' | python -m json.tool
627 "name": "example.localdomain",
628 "status": "Object was deleted.",
634 ## <a id="icinga2-api-config-templates"></a> Config Templates
636 Provides methods to manage configuration templates:
638 * [querying templates](12-icinga2-api.md#icinga2-api-config-templates-query)
640 ### <a id="icinga2-api-config-templates-query"></a> Querying Templates
642 You can request information about configuration templates by sending
643 a `GET` query to the `/v1/templates/<type>` URL endpoint. `<type` has
644 to be replaced with the plural name of the object type you are interested
647 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts'
649 A list of all available configuration types is available in the
650 [object types](9-object-types.md#object-types) chapter.
652 A [filter](12-icinga2-api.md#icinga2-api-filters) may be provided for this query type. The
653 template object can be accessed in the filter using the `tmpl` variable:
655 $ curl -u root:root -k 'https://localhost:5661/v1/templates/hosts' -H "Accept: application/json" -X PUT -H "X-HTTP-Method-Override: GET" \
656 -d '{ "filter": "match(\"g*\", tmpl.name)" }'
658 Instead of using a filter you can optionally specify the template name in the
659 URL path when querying a single object:
661 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts/generic-host'
663 The result set contains the type and name of the template.
665 ## <a id="icinga2-api-variables"></a> Variables
667 Provides methods to manage global variables:
669 * [querying variables](12-icinga2-api.md#icinga2-api-variables-query)
671 ### <a id="icinga2-api-variables-query"></a> Querying Variables
673 You can request information about global variables by sending
674 a `GET` query to the `/v1/variables/` URL endpoint:
676 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables'
678 A [filter](12-icinga2-api.md#icinga2-api-filters) may be provided for this query type. The
679 variable information object can be accessed in the filter using the `variable` variable:
681 $ curl -u root:root -k 'https://localhost:5661/v1/variables' -H "Accept: application/json" -X PUT -H "X-HTTP-Method-Override: GET" \
682 -d '{ "filter": "variable.type in [ \"String\", \"Number\" ]" }'
684 Instead of using a filter you can optionally specify the variable name in the
685 URL path when querying a single variable:
687 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables/PrefixDir'
689 The result set contains the type, name and value of the global variable.
691 ## <a id="icinga2-api-actions"></a> Actions
693 There are several actions available for Icinga 2 provided by the `/v1/actions`
694 URL endpoint. You can run actions by sending a `POST` request.
696 In case you have been using the [external commands](14-features.md#external-commands)
697 in the past, the API actions provide a similar interface with filter
698 capabilities for some of the more common targets which do not directly change
701 All actions return a 200 `OK` or an appropriate error code for each
702 action performed on each object matching the supplied filter.
704 Actions which affect the Icinga Application itself such as disabling
705 notification on a program-wide basis must be applied by updating the
706 [IcingaApplication object](12-icinga2-api.md#icinga2-api-config-objects)
709 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/icingaapplications/app' -d '{ "attrs": { "enable_notifications": false } }'
711 ### <a id="icinga2-api-actions-process-check-result"></a> process-check-result
713 Process a check result for a host or a service.
715 Send a `POST` request to the URL endpoint `/v1/actions/process-check-result`.
717 Parameter | Type | Description
718 ------------------|--------------|--------------
719 exit\_status | integer | **Required.** For services: 0=OK, 1=WARNING, 2=CRITICAL, 3=UNKNOWN, for hosts: 0=OK, 1=CRITICAL.
720 plugin\_output | string | **Required.** The plugins main output. Does **not** contain the performance data.
721 performance\_data | string array | **Optional.** The performance data.
722 check\_command | string array | **Optional.** The first entry should be the check commands path, then one entry for each command line option followed by an entry for each of its argument.
723 check\_source | string | **Optional.** Usually the name of the `command_endpoint`
725 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
729 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/process-check-result?service=example.localdomain!passive-ping6' \
730 -d '{ "exit_status": 2, "plugin_output": "PING CRITICAL - Packet loss = 100%", "performance_data": [ "rta=5000.000000ms;3000.000000;5000.000000;0.000000", "pl=100%;80;100;0" ], "check_source": "example.localdomain" }' | python -m json.tool
736 "status": "Successfully processed check result for object 'localdomain!passive-ping6'."
741 ### <a id="icinga2-api-actions-reschedule-check"></a> reschedule-check
743 Reschedule a check for hosts and services. The check can be forced if required.
745 Send a `POST` request to the URL endpoint `/v1/actions/reschedule-check`.
747 Parameter | Type | Description
748 -------------|-----------|--------------
749 next\_check | timestamp | **Optional.** The next check will be run at this time. If omitted, the current time is used.
750 force\_check | boolean | **Optional.** Defaults to `false`. If enabled, the checks are executed regardless of time period restrictions and checks being disabled per object or on a global basis.
752 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
754 The example reschedules all services with the name "ping6" to immediately perform a check
755 (`next_check` default), ignoring any time periods or whether active checks are
756 allowed for the service (`force_check=true`).
758 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \
759 -d '{ "type": "Service", "filter": "service.name==\"ping6\"", "force_check": true }' | python -m json.tool
765 "status": "Successfully rescheduled check for object 'localhost!ping6'."
771 ### <a id="icinga2-api-actions-send-custom-notification"></a> send-custom-notification
773 Send a custom notification for hosts and services. This notification
774 type can be forced being sent to all users.
776 Send a `POST` request to the URL endpoint `/v1/actions/send-custom-notification`.
778 Parameter | Type | Description
779 ----------|---------|--------------
780 author | string | **Required.** Name of the author, may be empty.
781 comment | string | **Required.** Comment text, may be empty.
782 force | boolean | **Optional.** Default: false. If true, the notification is sent regardless of downtimes or whether notifications are enabled or not.
784 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
786 Example for a custom host notification announcing a global maintenance to
789 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/send-custom-notification' \
790 -d '{ "type": "Host", "author": "icingaadmin", "comment": "System is going down for maintenance", "force": true }' | python -m json.tool
796 "status": "Successfully sent custom notification for object 'host0'."
800 "status": "Successfully sent custom notification for object 'host1'."
804 ### <a id="icinga2-api-actions-delay-notification"></a> delay-notification
806 Delay notifications for a host or a service.
807 Note that this will only have an effect if the service stays in the same problem
808 state that it is currently in. If the service changes to another state, a new
809 notification may go out before the time you specify in the `timestamp` argument.
811 Send a `POST` request to the URL endpoint `/v1/actions/delay-notification`.
813 Parameter | Type | Description
814 ----------|-----------|--------------
815 timestamp | timestamp | **Required.** Delay notifications until this timestamp.
817 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
821 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/delay-notification' \
822 -d '{ "type": "Service", "timestamp": 1446389894 }' | python -m json.tool
828 "status": "Successfully delayed notifications for object 'host0!service0'."
832 "status": "Successfully delayed notifications for object 'host1!service1'."
836 ### <a id="icinga2-api-actions-acknowledge-problem"></a> acknowledge-problem
838 Allows you to acknowledge the current problem for hosts or services. By
839 acknowledging the current problem, future notifications (for the same state if `sticky` is set to `false`)
842 Send a `POST` request to the URL endpoint `/v1/actions/acknowledge-problem`.
844 Parameter | Type | Description
845 ----------|-----------|--------------
846 author | string | **Required.** Name of the author, may be empty.
847 comment | string | **Required.** Comment text, may be empty.
848 expiry | timestamp | **Optional.** If set, the acknowledgement will vanish after this timestamp.
849 sticky | boolean | **Optional.** If `true`, the default, the acknowledgement will remain until the service or host fully recovers.
850 notify | boolean | **Optional.** If `true`, a notification will be sent out to contacts to indicate this problem has been acknowledged. The default is false.
852 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
854 The following example acknowledges all services which are in a hard critical state and sends out
855 a notification for them:
857 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/acknowledge-problem?type=Service&filter=service.state==2&service.state_type=1' \
858 -d '{ "author": "icingaadmin", "comment": "Global outage. Working on it.", "notify": true }' | python -m json.tool
864 "status": "Successfully acknowledged problem for object 'example2.localdomain!ping4'."
868 "status": "Successfully acknowledged problem for object 'example.localdomain!ping4'."
873 ### <a id="icinga2-api-actions-remove-acknowledgement"></a> remove-acknowledgement
875 Removes the acknowledgements for services or hosts. Once the acknowledgement has
876 been removed notifications will be sent out again.
878 Send a `POST` request to the URL endpoint `/v1/actions/remove-acknowledgement`.
880 A [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
882 The example removes all service acknowledgements:
884 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-acknowledgement?type=Service' | python -m json.tool
890 "status": "Successfully removed acknowledgement for object 'host0!service0'."
894 "status": "Successfully removed acknowledgement for object 'example2.localdomain!aws-health'."
898 ### <a id="icinga2-api-actions-add-comment"></a> add-comment
900 Adds a `comment` from an `author` to services or hosts.
902 Send a `POST` request to the URL endpoint `/v1/actions/add-comment`.
904 Parameter | Type | Description
905 ----------|--------|--------------
906 author | string | **Required.** Name of the author, may be empty.
907 comment | string | **Required.** Comment text, may be empty.
909 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
911 The following example adds a comment for all `ping4` services:
913 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/add-comment?type=Service&filter=service.name==%22ping4%22' -d '{ "author": "icingaadmin", "comment": "Troubleticket #123456789 opened." }' | python -m json.tool
919 "name": "example.localdomain!ping4!example.localdomain-1446824161-0",
920 "status": "Successfully added comment 'example.localdomain!ping4!example.localdomain-1446824161-0' for object 'example.localdomain!ping4'."
925 "name": "example2.localdomain!ping4!example.localdomain-1446824161-1",
926 "status": "Successfully added comment 'example2.localdomain!ping4!example.localdomain-1446824161-1' for object 'example2.localdomain!ping4'."
931 ### <a id="icinga2-api-actions-remove-comment"></a> remove-comment
933 Remove the comment using its `name` attribute , returns `OK` if the
934 comment did not exist.
935 **Note**: This is **not** the legacy ID but the comment name returned by
936 Icinga 2 when [adding a comment](12-icinga2-api.md#icinga2-api-actions-add-comment).
938 Send a `POST` request to the URL endpoint `/v1/actions/remove-comment`.
940 A [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host`, `Service` and `Comment`.
942 Example for a simple filter using the `comment` URL parameter:
944 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-comment?comment=example2.localdomain!ping4!mbmif.local-1446986367-0' | python -m json.tool
949 "status": "Successfully removed comment 'example2.localdomain!ping4!mbmif.local-1446986367-0'."
954 Example for removing all service comments using a service name filter for `ping4`:
956 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-comment?filter=service.name==%22ping4%22&type=Service' | python -m json.tool
961 "status": "Successfully removed all comments for object 'example2.localdomain!ping4'."
965 "status": "Successfully removed all comments for object 'example.localdomain!ping4'."
971 ### <a id="icinga2-api-actions-schedule-downtime"></a> schedule-downtime
973 Schedule a downtime for hosts and services.
975 Send a `POST` request to the URL endpoint `/v1/actions/schedule-downtime`.
977 Parameter | Type | Description
978 --------------|-----------|--------------
979 author | string | **Required.** Name of the author.
980 comment | string | **Required.** Comment text.
981 start\_time | timestamp | **Required.** Timestamp marking the beginning of the downtime.
982 end\_time | timestamp | **Required.** Timestamp marking the end of the downtime.
983 duration | integer | **Required.** Duration of the downtime in seconds if `fixed` is set to false.
984 fixed | boolean | **Optional.** Defaults to `true`. If true, the downtime is `fixed` otherwise `flexible`. See [downtimes](8-advanced-topics.md#downtimes) for more information.
985 trigger\_name | string | **Optional.** Sets the trigger for a triggered downtime. See [downtimes](8-advanced-topics.md#downtimes) for more information on triggered downtimes.
987 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
991 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/schedule-downtime?type=Service&filter=service.name==%22ping4%22' -d '{ "start_time": 1446388806, "end_time": 1446389806, "duration": 1000, "author": "icingaadmin", "comment": "IPv4 network maintenance" }' | python -m json.tool
997 "name": "example2.localdomain!ping4!example.localdomain-1446822004-0",
998 "status": "Successfully scheduled downtime 'example2.localdomain!ping4!example.localdomain-1446822004-0' for object 'example2.localdomain!ping4'."
1003 "name": "example.localdomain!ping4!example.localdomain-1446822004-1",
1004 "status": "Successfully scheduled downtime 'example.localdomain!ping4!example.localdomain-1446822004-1' for object 'example.localdomain!ping4'."
1009 ### <a id="icinga2-api-actions-remove-downtime"></a> remove-downtime
1011 Remove the downtime using its `name` attribute , returns `OK` if the
1012 downtime did not exist.
1013 **Note**: This is **not** the legacy ID but the downtime name returned by
1014 Icinga 2 when [scheduling a downtime](12-icinga2-api.md#icinga2-api-actions-schedule-downtime).
1016 Send a `POST` request to the URL endpoint `/v1/actions/remove-downtime`.
1018 A [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host`, `Service` and `Downtime`.
1020 Example for a simple filter using the `downtime` URL parameter:
1022 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime?downtime=example.localdomain!ping4!mbmif.local-1446979168-6' | python -m json.tool
1027 "status": "Successfully removed downtime 'example.localdomain!ping4!mbmif.local-1446979168-6'."
1032 Example for removing all host downtimes using a host name filter for `example.localdomain`:
1034 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime?filter=host.name==%22example.localdomain%22&type=Host' | python -m json.tool
1039 "status": "Successfully removed all downtimes for object 'example.localdomain'."
1044 Example for removing a downtime from a host but not the services filtered by the author name. This example uses
1045 filter variables explained in the [advanced filters](12-icinga2-api.md#icinga2-api-advanced-filters) chapter.
1047 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime' \
1050 "filter": "host.name == filterHost && !service && downtime.author == filterAuthor",
1052 "filterHost": "example.localdomain",
1053 "filterAuthor": "icingaadmin"
1055 }' | python -m json.tool
1061 "status": "Successfully removed downtime 'example.localdomain!mbmif.local-1463043129-3'."
1066 ### <a id="icinga2-api-actions-shutdown-process"></a> shutdown-process
1068 Shuts down Icinga2. May or may not return.
1070 Send a `POST` request to the URL endpoint `/v1/actions/shutdown-process`.
1072 This action does not support a target type or filter.
1076 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/shutdown-process' | python -m json.tool
1082 "status": "Shutting down Icinga 2."
1087 ### <a id="icinga2-api-actions-restart-process"></a> restart-process
1089 Restarts Icinga2. May or may not return.
1091 Send a `POST` request to the URL endpoint `/v1/actions/restart-process`.
1093 This action does not support a target type or filter.
1097 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/restart-process' | python -m json.tool
1103 "status": "Restarting Icinga 2."
1109 ## <a id="icinga2-api-event-streams"></a> Event Streams
1111 You can subscribe to event streams by sending a `POST` request to the URL endpoint `/v1/events`.
1112 The following parameters need to be specified (either as URL parameters or in a JSON-encoded message body):
1114 Parameter | Type | Description
1115 -----------|--------------|-------------
1116 types | string array | **Required.** Event type(s). Multiple types as URL parameters are supported.
1117 queue | string | **Required.** Unique queue name. Multiple HTTP clients can use the same queue as long as they use the same event types and filter.
1118 filter | string | **Optional.** Filter for specific event attributes using [filter expressions](12-icinga2-api.md#icinga2-api-filters).
1120 ### <a id="icinga2-api-event-streams-types"></a> Event Stream Types
1122 The following event stream types are available:
1125 -----------------------|--------------
1126 CheckResult | Check results for hosts and services.
1127 StateChange | Host/service state changes.
1128 Notification | Notification events including notified users for hosts and services.
1129 AcknowledgementSet | Acknowledgement set on hosts and services.
1130 AcknowledgementCleared | Acknowledgement cleared on hosts and services.
1131 CommentAdded | Comment added for hosts and services.
1132 CommentRemoved | Comment removed for hosts and services.
1133 DowntimeAdded | Downtime added for hosts and services.
1134 DowntimeRemoved | Downtime removed for hosts and services.
1135 DowntimeTriggered | Downtime triggered for hosts and services.
1137 Note: Each type requires [API permissions](12-icinga2-api.md#icinga2-api-permissions)
1140 Example for all downtime events:
1142 &types=DowntimeAdded&types=DowntimeRemoved&types=DowntimeTriggered
1145 ### <a id="icinga2-api-event-streams-filter"></a> Event Stream Filter
1147 Event streams can be filtered by attributes using the prefix `event.`.
1149 Example for the `CheckResult` type with the `exit_code` set to `2`:
1151 &types=CheckResult&filter=event.check_result.exit_status==2
1153 Example for the `CheckResult` type with the service matching the string "random":
1155 &types=CheckResult&filter=match%28%22random*%22,event.service%29
1158 ### <a id="icinga2-api-event-streams-response"></a> Event Stream Response
1160 The event stream response is separated with new lines. The HTTP client
1161 must support long-polling and HTTP/1.1. HTTP/1.0 is not supported.
1165 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/events?queue=michi&types=CheckResult&filter=event.check_result.exit_status==2'
1167 {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421319.7226390839,"type":"CheckResult"}
1168 {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421324.7226390839,"type":"CheckResult"}
1169 {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421329.7226390839,"type":"CheckResult"}
1172 ## <a id="icinga2-api-status"></a> Status and Statistics
1174 Send a `GET` request to the URL endpoint `/v1/status` to retrieve status information and statistics for Icinga 2.
1178 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/status' | python -m json.tool
1182 "name": "ApiListener",
1183 "perfdata": [ ... ],
1188 "name": "IcingaAplication",
1189 "perfdata": [ ... ],
1196 You can limit the output by specifying a status type in the URL, e.g. `IcingaApplication`:
1198 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/status/IcingaApplication' | python -m json.tool
1204 "icingaapplication": {
1206 "enable_event_handlers": true,
1207 "enable_flapping": true,
1208 "enable_host_checks": true,
1209 "enable_notifications": true,
1210 "enable_perfdata": true,
1211 "enable_service_checks": true,
1212 "node_name": "example.localdomain",
1214 "program_start": 1443019345.093372,
1215 "version": "v2.3.0-573-g380a131"
1224 ## <a id="icinga2-api-config-management"></a> Configuration Management
1226 The main idea behind configuration management is to allow external applications
1227 creating configuration packages and stages based on configuration files and
1228 directory trees. This replaces any additional SSH connection and whatnot to
1229 dump configuration files to Icinga 2 directly.
1230 In case you are pushing a new configuration stage to a package, Icinga 2 will
1231 validate the configuration asynchronously and populate a status log which
1232 can be fetched in a separated request.
1235 ### <a id="icinga2-api-config-management-create-package"></a> Creating a Config Package
1237 Send a `POST` request to a new config package called `example-cmdb` in this example. This
1238 will create a new empty configuration package.
1240 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \
1241 'https://localhost:5665/v1/config/packages/example-cmdb' | python -m json.tool
1246 "package": "example-cmdb",
1247 "status": "Created package."
1252 Package names starting with an underscore are reserved for internal packages and must not be used.
1254 ### <a id="icinga2-api-config-management-create-config-stage"></a> Uploading configuration for a Config Package
1256 Configuration files in packages are managed in stages.
1257 Stages provide a way to maintain multiple configuration versions for a package.
1259 Send a `POST` request to the URL endpoint `/v1/config/stages` and add the name of an existing
1260 configuration package to the URL path (e.g. `example-cmdb`).
1261 The request body must contain the `files` attribute with the value being
1262 a dictionary of file targets and their content.
1264 The file path requires one of these two directories inside its path:
1266 Directory | Description
1267 ------------|------------------------------------
1268 conf.d | Local configuration directory.
1269 zones.d | Configuration directory for cluster zones, each zone must be put into its own zone directory underneath. Supports the [cluster config sync](6-distributed-monitoring.md#distributed-monitoring-top-down-config-sync).
1271 Example for a local configuration in the `conf.d` directory:
1273 "files": { "conf.d/host1.conf": "object Host \"local-host\" { address = \"127.0.0.1\", check_command = \"hostalive\" }" }
1275 Example for a host configuration inside the `satellite` zone in the `zones.d` directory:
1277 "files": { "zones.d/satellite/host2.conf": "object Host \"satellite-host\" { address = \"192.168.1.100\", check_command = \"hostalive\" }" }
1280 The example below will create a new file called `test.conf` in the `conf.d`
1281 directory. Note: This example contains an error (`chec_command`). This is
1284 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \
1285 -d '{ "files": { "conf.d/test.conf": "object Host \"cmdb-host\" { chec_command = \"dummy\" }" } }' \
1286 'https://localhost:5665/v1/config/stages/example-cmdb' | python -m json.tool
1291 "package": "example-cmdb",
1292 "stage": "example.localdomain-1441625839-0",
1293 "status": "Created stage."
1298 The Icinga 2 API returns the `package` name this stage was created for, and also
1299 generates a unique name for the `stage` attribute you'll need for later requests.
1301 Icinga 2 automatically restarts the daemon in order to activate the new config stage.
1302 If the validation for the new config stage failed, the old stage and its configuration objects
1307 > Old stages are not purged automatically. You can [remove stages](12-icinga2-api.md#icinga2-api-config-management-delete-config-stage) that are no longer in use.
1309 Icinga 2 will create the following files in the configuration package
1310 stage after configuration validation:
1313 ------------|--------------
1314 status | Contains the [configuration validation](11-cli-commands.md#config-validation) exit code (everything else than 0 indicates an error).
1315 startup.log | Contains the [configuration validation](11-cli-commands.md#config-validation) output.
1317 You can [fetch these files](12-icinga2-api.md#icinga2-api-config-management-fetch-config-package-stage-files)
1318 in order to verify that the new configuration was deployed successfully.
1321 ### <a id="icinga2-api-config-management-list-config-packages"></a> List Configuration Packages and their Stages
1323 A list of packages and their stages can be retrieved by sending a `GET` request to the URL endpoint `/v1/config/packages`.
1325 The following example contains one configuration package `example-cmdb`. The package does not currently
1326 have an active stage.
1328 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/packages' | python -m json.tool
1333 "name": "example-cmdb",
1335 "example.localdomain-1441625839-0"
1342 ### <a id="icinga2-api-config-management-list-config-package-stage-files"></a> List Configuration Packages and their Stages
1344 In order to retrieve a list of files for a stage you can send a `GET` request to
1345 the URL endpoint `/v1/config/stages`. You need to include
1346 the package name (`example-cmdb`) and stage name (`example.localdomain-1441625839-0`) in the URL:
1348 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441625839-0' | python -m json.tool
1353 "name": "startup.log",
1369 "name": "conf.d/test.conf",
1375 ### <a id="icinga2-api-config-management-fetch-config-package-stage-files"></a> Fetch Configuration Package Stage Files
1377 Send a `GET` request to the URL endpoint `/v1/config/files` and add
1378 the package name, the stage name and the relative path to the file to the URL path.
1382 > The returned files are plain-text instead of JSON-encoded.
1384 The following example fetches the configuration file `conf.d/test.conf`:
1386 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441625839-0/conf.d/test.conf'
1388 object Host "cmdb-host" { chec_command = "dummy" }
1390 You can fetch a [list of existing files](12-icinga2-api.md#icinga2-api-config-management-list-config-package-stage-files)
1391 in a configuration stage and then specifically request their content.
1393 ### <a id="icinga2-api-config-management-config-package-stage-errors"></a> Configuration Package Stage Errors
1395 Now that we don't have an active stage for `example-cmdb` yet seen [here](12-icinga2-api.md#icinga2-api-config-management-list-config-packages),
1396 there must have been an error.
1398 In order to check for validation errors you can fetch the `startup.log` file
1399 by sending a `GET` request to the URL endpoint `/v1/config/files`. You must include
1400 the package name, stage name and the `startup.log` in the URL path.
1402 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441133065-1/startup.log'
1405 critical/config: Error: Attribute 'chec_command' does not exist.
1407 /var/lib/icinga2/api/packages/example-cmdb/example.localdomain-1441133065-1/conf.d/test.conf(1): object Host "cmdb-host" { chec_command = "dummy" }
1408 ^^^^^^^^^^^^^^^^^^^^^^
1410 critical/config: 1 error
1412 The output is similar to the manual [configuration validation](11-cli-commands.md#config-validation).
1416 > The returned output is plain-text instead of JSON-encoded.
1419 ### <a id="icinga2-api-config-management-delete-config-stage"></a> Deleting Configuration Package Stage
1421 You can send a `DELETE` request to the URL endpoint `/v1/config/stages`
1422 in order to purge a configuration stage. You must include the package and
1423 stage name inside the URL path.
1425 The following example removes the failed configuration stage `example.localdomain-1441133065-1`
1426 in the `example-cmdb` configuration package:
1428 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \
1429 'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441133065-1' | python -m json.tool
1434 "status": "Stage deleted."
1440 ### <a id="icinga2-api-config-management-delete-config-package"></a> Deleting Configuration Package
1442 In order to completely purge a configuration package and its stages
1443 you can send a `DELETE` request to the URL endpoint `/v1/config/packages`
1444 with the package name in the URL path.
1446 This example entirely deletes the configuration package `example-cmdb`:
1448 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \
1449 'https://localhost:5665/v1/config/packages/example-cmdb' | python -m json.tool
1454 "package": "example-cmdb",
1455 "status": "Deleted package."
1461 ## <a id="icinga2-api-types"></a> Types
1463 You can retrieve the configuration object types by sending a `GET` request to URL
1464 endpoint `/v1/types`.
1466 Each response entry in the results array contains the following attributes:
1468 Attribute | Type | Description
1469 ---------------|--------------|---------------------
1470 name | string | The type name.
1471 plural_name | string | The plural type name.
1472 fields | dictionary | Available fields including details on e.g. the type and attribute accessibility.
1473 abstract | boolean | Whether objects can be instantiated for this type.
1474 base | boolean | The base type (e.g. `Service` inherits fields and prototype methods from `Checkable`).
1475 prototype_keys | string array | Available prototype methods.
1477 In order to view a specific configuration object type specify its name inside the URL path:
1479 $ curl -k -s -u root:icinga 'https://localhost:5665/v1/types/Object' | python -m json.tool
1489 "navigation": false,
1490 "no_user_modify": false,
1491 "no_user_view": false,
1500 "plural_name": "Objects",
1511 ## <a id="icinga2-api-console"></a> Console
1513 You can inspect variables and execute other expressions by sending a `POST` request to the URL endpoint `/v1/console/execute-script`.
1514 In order to receive auto-completion suggestions, send a `POST` request to the URL endpoint `/v1/console/auto-complete-script`.
1516 The following parameters need to be specified (either as URL parameters or in a JSON-encoded message body):
1518 Parameter | Type | Description
1519 -----------|--------------|-------------
1520 session | string | **Optional.** The session ID. Ideally this should be a GUID or some other unique identifier.
1521 command | string | **Required.** Command expression for execution or auto-completion.
1522 sandboxed | number | **Optional.** Whether runtime changes are allowed or forbidden. Defaults to disabled.
1524 The [API permission](12-icinga2-api.md#icinga2-api-permissions) `console` is required for executing
1527 If you specify a session identifier, the same script context can be reused for multiple requests. This allows you to, for example, set a local variable in a request and use that local variable in another request. Sessions automatically expire after a set period of inactivity (currently 30 minutes).
1529 Example for fetching the command line from the local host's last check result:
1531 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/console/execute-script?command=get_host(NodeName).last_check_result.command&sandboxed=0&session=bb75fd7c-c686-407d-9688-582c04227756' | python -m json.tool
1537 "/usr/local/sbin/check_ping",
1545 "status": "Executed successfully."
1550 Example for fetching auto-completion suggestions for the `Host.` type. This works in a
1551 similar fashion when pressing TAB inside the [console CLI command](11-cli-commands.md#cli-command-console):
1553 $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/console/auto-complete-script?command=Host.&sandboxed=0&session=bb75fd7c-c686-407d-9688-582c04227756' | python -m json.tool
1558 "status": "Auto-completed successfully.",
1564 "Host.register_attribute_handler",
1566 "Host.notify_attribute",
1574 ## <a id="icinga2-api-clients"></a> API Clients
1576 There are a couple of existing clients which can be used with the Icinga 2 API:
1578 * [curl](http://curl.haxx.se) or any other HTTP client really
1579 * [Icinga 2 console (CLI command)](12-icinga2-api.md#icinga2-api-clients-cli-console)
1580 * [Icinga Studio](12-icinga2-api.md#icinga2-api-clients-icinga-studio)
1581 * [Icinga Web 2 Director](https://dev.icinga.org/projects/icingaweb2-modules)
1585 * [Dashing](https://github.com/Icinga/dashing-icinga2)
1586 * [API examples](https://github.com/Icinga/icinga2-api-examples)
1588 Additional [programmatic examples](12-icinga2-api.md#icinga2-api-clients-programmatic-examples)
1589 will help you getting started using the Icinga 2 API in your environment.
1591 ### <a id="icinga2-api-clients-icinga-studio"></a> Icinga Studio
1593 Icinga Studio is a graphical application to query configuration objects provided by the API.
1595 ![Icinga Studio Connection](images/icinga2-api/icinga2_api_icinga_studio_connect.png)
1597 ![Icinga Studio Overview](images/icinga2-api/icinga2_api_icinga_studio_overview.png)
1599 Please check the package repository of your distribution for available
1603 > Icinga Studio does not currently support SSL certificate verification.
1605 The Windows installer already includes Icinga Studio. On Debian and Ubuntu the package
1606 `icinga2-studio` can be used to install Icinga Studio.
1608 ### <a id="icinga2-api-clients-cli-console"></a> Icinga 2 Console
1610 By default the [console CLI command](11-cli-commands.md#cli-command-console) evaluates expressions in a local interpreter, i.e. independently from your Icinga 2 daemon. Using the `--connect` parameter you can use the Icinga 2 console to evaluate expressions via the API.
1612 ### <a id="icinga2-api-clients-programmatic-examples"></a> API Clients Programmatic Examples
1614 The programmatic examples use HTTP basic authentication and SSL certificate
1615 verification. The CA file is expected in `pki/icinga2-ca.crt`
1616 but you may adjust the examples for your likings.
1618 The request method is `POST` using `X-HTTP-Method-Override: GET`
1619 which allows you to send a JSON request body. The examples request
1620 specific service attributes joined with host attributes. `attrs`
1621 and `joins` are therefore specified as array.
1622 The `filter` attribute matches on all services with `ping` in their name.
1624 #### <a id="icinga2-api-clients-programmatic-examples-python"></a> Example API Client in Python
1626 The following example uses **Python** and the `requests` and `json` module:
1628 # pip install requests
1631 $ vim icinga2-api-example.py
1633 #!/usr/bin/env python
1635 import requests, json
1637 # Replace 'localhost' with your FQDN and certificate CN
1638 # for SSL verification
1639 request_url = "https://localhost:5665/v1/objects/services"
1641 'Accept': 'application/json',
1642 'X-HTTP-Method-Override': 'GET'
1645 "attrs": [ "name", "state", "last_check_result" ],
1646 "joins": [ "host.name", "host.state", "host.last_check_result" ],
1647 "filter": "match(\"ping*\", service.name)",
1650 r = requests.post(request_url,
1652 auth=('root', 'icinga'),
1653 data=json.dumps(data),
1654 verify="pki/icinga2-ca.crt")
1656 print "Request URL: " + str(r.url)
1657 print "Status code: " + str(r.status_code)
1659 if (r.status_code == 200):
1660 print "Result: " + json.dumps(r.json())
1663 r.raise_for_status()
1665 $ python icinga2-api-example.py
1668 #### <a id="icinga2-api-clients-programmatic-examples-ruby"></a> Example API Client in Ruby
1670 The following example uses **Ruby** and the `rest_client` gem:
1672 # gem install rest_client
1674 $ vim icinga2-api-example.rb
1678 require 'rest_client'
1680 # Replace 'localhost' with your FQDN and certificate CN
1681 # for SSL verification
1682 request_url = "https://localhost:5665/v1/objects/services"
1684 "Accept" => "application/json",
1685 "X-HTTP-Method-Override" => "GET"
1688 "attrs" => [ "name", "state", "last_check_result" ],
1689 "joins" => [ "host.name", "host.state", "host.last_check_result" ],
1690 "filter" => "match(\"ping*\", service.name)",
1693 r = RestClient::Resource.new(
1694 URI.encode(request_url),
1695 :headers => headers,
1697 :password => "icinga",
1698 :ssl_ca_file => "pki/icinga2-ca.crt")
1701 response = r.post(data.to_json)
1703 response = e.response
1706 puts "Status: " + response.code.to_s
1707 if response.code == 200
1708 puts "Result: " + (JSON.pretty_generate JSON.parse(response.body))
1710 puts "Error: " + response
1713 $ ruby icinga2-api-example.rb
1715 A more detailed example can be found in the [Dashing demo](https://github.com/Icinga/dashing-icinga2).
1717 #### <a id="icinga2-api-clients-programmatic-examples-php"></a> Example API Client in PHP
1719 The following example uses **PHP** and its `curl` library:
1721 $ vim icinga2-api-example.php
1725 # Replace 'localhost' with your FQDN and certificate CN
1726 # for SSL verification
1727 $request_url = "https://localhost:5665/v1/objects/services";
1729 $password = "icinga";
1731 'Accept: application/json',
1732 'X-HTTP-Method-Override: GET'
1735 attrs => array('name', 'state', 'last_check_result'),
1736 joins => array('host.name', 'host.state', 'host.last_check_result'),
1737 filter => 'match("ping*", service.name)',
1741 curl_setopt_array($ch, array(
1742 CURLOPT_URL => $request_url,
1743 CURLOPT_HTTPHEADER => $headers,
1744 CURLOPT_USERPWD => $username . ":" . $password,
1745 CURLOPT_RETURNTRANSFER => true,
1746 CURLOPT_CAINFO => "pki/icinga2-ca.crt",
1747 CURLOPT_POST => count($data),
1748 CURLOPT_POSTFIELDS => json_encode($data)
1751 $response = curl_exec($ch);
1752 if ($response === false) {
1753 print "Error: " . curl_error($ch) . "(" . $response . ")\n";
1756 $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1758 print "Status: " . $code . "\n";
1761 $response = json_decode($response, true);
1766 $ php icinga2-api-example.php
1768 #### <a id="icinga2-api-clients-programmatic-examples-perl"></a> Example API Client in Perl
1770 The following example uses **Perl** and the `Rest::Client` module:
1772 # perl -MCPAN -e 'install REST::Client'
1773 # perl -MCPAN -e 'install JSON'
1774 # perl -MCPAN -e 'install MIME::Base64'
1775 # perl -MCPAN -e 'install Data::Dumper'
1777 $ vim icinga2-api-example.pl
1788 # Replace 'localhost' with your FQDN and certificate CN
1789 # for SSL verification
1790 my $request_host = "https://localhost:5665";
1791 my $userpass = "root:icinga";
1793 my $client = REST::Client->new();
1794 $client->setHost($request_host);
1795 $client->setCa("pki/icinga2-ca.crt");
1796 $client->addHeader("Accept", "application/json");
1797 $client->addHeader("X-HTTP-Method-Override", "GET");
1798 $client->addHeader("Authorization", "Basic " . encode_base64($userpass));
1800 attrs => ['name', 'state', 'last_check_result'],
1801 joins => ['host.name', 'host.state', 'host.last_check_result'],
1802 filter => 'match("ping*", service.name)',
1804 my $data = encode_json(\%json_data);
1805 $client->POST("/v1/objects/services", $data);
1807 my $status = $client->responseCode();
1808 print "Status: " . $status . "\n";
1809 my $response = $client->responseContent();
1810 if ($status == 200) {
1811 print "Result: " . Dumper(decode_json($response)) . "\n";
1813 print "Error: " . $response . "\n";
1816 $ perl icinga2-api-example.pl