Create a new configuration directory, e.g. `objects.d` and include it
in your icinga2.conf file.
- [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/objects.d
+```
+[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/objects.d
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/icinga2.conf
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/icinga2.conf
- /* Local object configuration on our master instance. */
- include_recursive "objects.d"
+/* Local object configuration on our master instance. */
+include_recursive "objects.d"
+```
This approach is used by the [Icinga 2 Puppet module](https://github.com/Icinga/puppet-icinga2).
Here's a brief description of the example configuration:
- /**
- * Icinga 2 configuration file
- * -- this is where you define settings for the Icinga application including
- * which hosts/services to check.
- *
- * For an overview of all available configuration options please refer
- * to the documentation that is distributed as part of Icinga 2.
- */
+```
+/**
+* Icinga 2 configuration file
+* -- this is where you define settings for the Icinga application including
+* which hosts/services to check.
+*
+* For an overview of all available configuration options please refer
+* to the documentation that is distributed as part of Icinga 2.
+*/
+```
Icinga 2 supports [C/C++-style comments](17-language-reference.md#comments).
- /**
- * The constants.conf defines global constants.
- */
- include "constants.conf"
+/**
+* The constants.conf defines global constants.
+*/
+include "constants.conf"
The `include` directive can be used to include other files.
- /**
- * The zones.conf defines zones for a cluster setup.
- * Not required for single instance setups.
- */
- include "zones.conf"
+```
+/**
+* The zones.conf defines zones for a cluster setup.
+* Not required for single instance setups.
+*/
+include "zones.conf"
+```
The [Icinga Template Library](10-icinga-template-library.md#icinga-template-library) provides a set of common templates
and [CheckCommand](03-monitoring-basics.md#check-commands) definitions.
- /**
- * The Icinga Template Library (ITL) provides a number of useful templates
- * and command definitions.
- * Common monitoring plugin command definitions are included separately.
- */
- include <itl>
- include <plugins>
- include <plugins-contrib>
- include <manubulon>
-
- /**
- * This includes the Icinga 2 Windows plugins. These command definitions
- * are required on a master node when a client is used as command endpoint.
- */
- include <windows-plugins>
-
- /**
- * This includes the NSClient++ check commands. These command definitions
- * are required on a master node when a client is used as command endpoint.
- */
- include <nscp>
-
- /**
- * The features-available directory contains a number of configuration
- * files for features which can be enabled and disabled using the
- * icinga2 feature enable / icinga2 feature disable CLI commands.
- * These commands work by creating and removing symbolic links in
- * the features-enabled directory.
- */
- include "features-enabled/*.conf"
+```
+/**
+* The Icinga Template Library (ITL) provides a number of useful templates
+* and command definitions.
+* Common monitoring plugin command definitions are included separately.
+*/
+include <itl>
+include <plugins>
+include <plugins-contrib>
+include <manubulon>
+
+/**
+* This includes the Icinga 2 Windows plugins. These command definitions
+* are required on a master node when a client is used as command endpoint.
+*/
+include <windows-plugins>
+
+/**
+* This includes the NSClient++ check commands. These command definitions
+* are required on a master node when a client is used as command endpoint.
+*/
+include <nscp>
+
+/**
+* The features-available directory contains a number of configuration
+* files for features which can be enabled and disabled using the
+* icinga2 feature enable / icinga2 feature disable CLI commands.
+* These commands work by creating and removing symbolic links in
+* the features-enabled directory.
+*/
+include "features-enabled/*.conf"
+```
This `include` directive takes care of including the configuration files for all
the features which have been enabled with `icinga2 feature enable`. See
[Enabling/Disabling Features](11-cli-commands.md#enable-features) for more details.
- /**
- * Although in theory you could define all your objects in this file
- * the preferred way is to create separate directories and files in the conf.d
- * directory. Each of these files must have the file extension ".conf".
- */
- include_recursive "conf.d"
+```
+/**
+* Although in theory you could define all your objects in this file
+* the preferred way is to create separate directories and files in the conf.d
+* directory. Each of these files must have the file extension ".conf".
+*/
+include_recursive "conf.d"
+```
You can put your own configuration files in the [conf.d](04-configuring-icinga-2.md#conf-d) directory. This
directive makes sure that all of your own configuration files are included.
Example:
- /* The directory which contains the plugins from the Monitoring Plugins project. */
- const PluginDir = "/usr/lib64/nagios/plugins"
+```
+/* The directory which contains the plugins from the Monitoring Plugins project. */
+const PluginDir = "/usr/lib64/nagios/plugins"
- /* The directory which contains the Manubulon plugins.
- * Check the documentation, chapter "SNMP Manubulon Plugin Check Commands", for details.
- */
- const ManubulonPluginDir = "/usr/lib64/nagios/plugins"
+/* The directory which contains the Manubulon plugins.
+* Check the documentation, chapter "SNMP Manubulon Plugin Check Commands", for details.
+*/
+const ManubulonPluginDir = "/usr/lib64/nagios/plugins"
- /* Our local instance name. By default this is the server's hostname as returned by `hostname --fqdn`.
- * This should be the common name from the API certificate.
- */
- //const NodeName = "localhost"
+/* Our local instance name. By default this is the server's hostname as returned by `hostname --fqdn`.
+* This should be the common name from the API certificate.
+*/
+//const NodeName = "localhost"
- /* Our local zone name. */
- const ZoneName = NodeName
+/* Our local zone name. */
+const ZoneName = NodeName
- /* Secret key for remote node tickets */
- const TicketSalt = ""
+/* Secret key for remote node tickets */
+const TicketSalt = ""
+```
The `ZoneName` and `TicketSalt` constants are required for remote client
and distributed setups only.
generate a new service checking the `/icingaweb2` URI using the `http`
check.
- /*
- * Host definitions with object attributes
- * used for apply rules for Service, Notification,
- * Dependency and ScheduledDowntime objects.
- *
- * Tip: Use `icinga2 object list --type Host` to
- * list all host objects after running
- * configuration validation (`icinga2 daemon -C`).
- */
-
- /*
- * This is an example host based on your
- * local host's FQDN. Specify the NodeName
- * constant in `constants.conf` or use your
- * own description, e.g. "db-host-1".
- */
-
- object Host NodeName {
- /* Import the default host template defined in `templates.conf`. */
- import "generic-host"
-
- /* Specify the address attributes for checks e.g. `ssh` or `http`. */
- address = "127.0.0.1"
- address6 = "::1"
-
- /* Set custom attribute `os` for hostgroup assignment in `groups.conf`. */
- vars.os = "Linux"
-
- /* Define http vhost attributes for service apply rules in `services.conf`. */
- vars.http_vhosts["http"] = {
- http_uri = "/"
- }
- /* Uncomment if you've sucessfully installed Icinga Web 2. */
- //vars.http_vhosts["Icinga Web 2"] = {
- // http_uri = "/icingaweb2"
- //}
-
- /* Define disks and attributes for service apply rules in `services.conf`. */
- vars.disks["disk"] = {
- /* No parameters. */
- }
- vars.disks["disk /"] = {
- disk_partitions = "/"
- }
-
- /* Define notification mail attributes for notification apply rules in `notifications.conf`. */
- vars.notification["mail"] = {
- /* The UserGroup `icingaadmins` is defined in `users.conf`. */
- groups = [ "icingaadmins" ]
- }
- }
+```
+/*
+* Host definitions with object attributes
+* used for apply rules for Service, Notification,
+* Dependency and ScheduledDowntime objects.
+*
+* Tip: Use `icinga2 object list --type Host` to
+* list all host objects after running
+* configuration validation (`icinga2 daemon -C`).
+*/
+
+/*
+ * This is an example host based on your
+ * local host's FQDN. Specify the NodeName
+ * constant in `constants.conf` or use your
+ * own description, e.g. "db-host-1".
+ */
+
+object Host NodeName {
+ /* Import the default host template defined in `templates.conf`. */
+ import "generic-host"
+
+ /* Specify the address attributes for checks e.g. `ssh` or `http`. */
+ address = "127.0.0.1"
+ address6 = "::1"
+
+ /* Set custom attribute `os` for hostgroup assignment in `groups.conf`. */
+ vars.os = "Linux"
+
+ /* Define http vhost attributes for service apply rules in `services.conf`. */
+ vars.http_vhosts["http"] = {
+ http_uri = "/"
+ }
+ /* Uncomment if you've sucessfully installed Icinga Web 2. */
+ //vars.http_vhosts["Icinga Web 2"] = {
+ // http_uri = "/icingaweb2"
+ //}
+
+ /* Define disks and attributes for service apply rules in `services.conf`. */
+ vars.disks["disk"] = {
+ /* No parameters. */
+ }
+ vars.disks["disk /"] = {
+ disk_partitions = "/"
+ }
+
+ /* Define notification mail attributes for notification apply rules in `notifications.conf`. */
+ vars.notification["mail"] = {
+ /* The UserGroup `icingaadmins` is defined in `users.conf`. */
+ groups = [ "icingaadmins" ]
+ }
+}
+```
This is only the host object definition. Now we'll need to make sure that this
host and your additional hosts are getting [services](04-configuring-icinga-2.md#services-conf) applied.
Example `load` service apply rule:
- apply Service "load" {
- import "generic-service"
+```
+apply Service "load" {
+import "generic-service"
- check_command = "load"
+check_command = "load"
- /* Used by the ScheduledDowntime apply rule in `downtimes.conf`. */
- vars.backup_downtime = "02:00-03:00"
+/* Used by the ScheduledDowntime apply rule in `downtimes.conf`. */
+vars.backup_downtime = "02:00-03:00"
- assign where host.name == NodeName
- }
+assign where host.name == NodeName
+}
+```
The `apply` keyword can be used to create new objects which are associated with
another group of objects. You can `import` existing templates, define (custom)
Multiple `assign where` condition can be combined with `AND` using the `&&` operator
as shown in the `ssh` example:
- apply Service "ssh" {
- import "generic-service"
+```
+apply Service "ssh" {
+ import "generic-service"
- check_command = "ssh"
+ check_command = "ssh"
- assign where host.address && host.vars.os == "Linux"
- }
+ assign where host.address && host.vars.os == "Linux"
+}
+```
In this example, the service `ssh` is applied to all hosts having the `address`
attribute defined `AND` having the custom attribute `os` set to the string
Remember the example from [hosts.conf](04-configuring-icinga-2.md#hosts-conf):
- ...
- /* Define disks and attributes for service apply rules in `services.conf`. */
- vars.disks["disk"] = {
- /* No parameters. */
- }
- vars.disks["disk /"] = {
- disk_partition = "/"
- }
- ...
-
+```
+...
+ /* Define disks and attributes for service apply rules in `services.conf`. */
+ vars.disks["disk"] = {
+ /* No parameters. */
+ }
+ vars.disks["disk /"] = {
+ disk_partition = "/"
+ }
+...
+```
This dictionary contains multiple service names we want to monitor. `disk`
should just check all available disks, while `disk /` will pass an additional
Configuration example:
- apply Service for (disk => config in host.vars.disks) {
- import "generic-service"
+```
+apply Service for (disk => config in host.vars.disks) {
+ import "generic-service"
- check_command = "disk"
+ check_command = "disk"
- vars += config
- }
+ vars += config
+}
+```
A similar example is used for the `http` services. That way you can make your
host the information provider for all apply rules. Define them once, and only
[hosts.conf](04-configuring-icinga-2.md#hosts-conf) for defining a custom host attribute later used in
[notifications.conf](04-configuring-icinga-2.md#notifications-conf) for notification apply rules.
- object User "icingaadmin" {
- import "generic-user"
-
- display_name = "Icinga 2 Admin"
- groups = [ "icingaadmins" ]
+```
+object User "icingaadmin" {
+ import "generic-user"
- email = "icinga@localhost"
- }
+ display_name = "Icinga 2 Admin"
+ groups = [ "icingaadmins" ]
- object UserGroup "icingaadmins" {
- display_name = "Icinga 2 Admin Group"
- }
+ email = "icinga@localhost"
+}
+object UserGroup "icingaadmins" {
+ display_name = "Icinga 2 Admin Group"
+}
+```
#### notifications.conf <a id="notifications-conf"></a>
respective [host.vars.notification.mail](04-configuring-icinga-2.md#hosts-conf) attribute we'll
implicitely use the `icingaadmins` UserGroup defined in [users.conf](04-configuring-icinga-2.md#users-conf).
- apply Notification "mail-icingaadmin" to Host {
- import "mail-host-notification"
+```
+apply Notification "mail-icingaadmin" to Host {
+ import "mail-host-notification"
- user_groups = host.vars.notification.mail.groups
- users = host.vars.notification.mail.users
+ user_groups = host.vars.notification.mail.groups
+ users = host.vars.notification.mail.users
- assign where host.vars.notification.mail
- }
+ assign where host.vars.notification.mail
+}
- apply Notification "mail-icingaadmin" to Service {
- import "mail-service-notification"
+apply Notification "mail-icingaadmin" to Service {
+ import "mail-service-notification"
- user_groups = host.vars.notification.mail.groups
- users = host.vars.notification.mail.users
+ user_groups = host.vars.notification.mail.groups
+ users = host.vars.notification.mail.users
- assign where host.vars.notification.mail
- }
+ assign where host.vars.notification.mail
+}
+```
More details on defining notifications and their additional attributes such as
filters can be read in [this chapter](03-monitoring-basics.md#alert-notifications).
This is done by using the [group assign](17-language-reference.md#group-assign) expressions similar
to previously seen [apply rules](03-monitoring-basics.md#using-apply).
- object HostGroup "linux-servers" {
- display_name = "Linux Servers"
+```
+object HostGroup "linux-servers" {
+ display_name = "Linux Servers"
- assign where host.vars.os == "Linux"
- }
+ assign where host.vars.os == "Linux"
+}
- object HostGroup "windows-servers" {
- display_name = "Windows Servers"
+object HostGroup "windows-servers" {
+ display_name = "Windows Servers"
- assign where host.vars.os == "Windows"
- }
+ assign where host.vars.os == "Windows"
+}
+```
Service groups can be grouped together by similar pattern matches.
The [match function](18-library-reference.md#global-functions-match) expects a wildcard match string
and the attribute string to match with.
- object ServiceGroup "ping" {
- display_name = "Ping Checks"
+```
+object ServiceGroup "ping" {
+ display_name = "Ping Checks"
- assign where match("ping*", service.name)
- }
+ assign where match("ping*", service.name)
+}
- object ServiceGroup "http" {
- display_name = "HTTP Checks"
+object ServiceGroup "http" {
+ display_name = "HTTP Checks"
- assign where match("http*", service.check_command)
- }
+ assign where match("http*", service.check_command)
+}
- object ServiceGroup "disk" {
- display_name = "Disk Checks"
-
- assign where match("disk*", service.check_command)
- }
+object ServiceGroup "disk" {
+ display_name = "Disk Checks"
+ assign where match("disk*", service.check_command)
+}
+```
#### templates.conf <a id="templates-conf"></a>
Most of the example configuration objects use generic global templates by
default:
- template Host "generic-host" {
- max_check_attempts = 5
- check_interval = 1m
- retry_interval = 30s
+```
+template Host "generic-host" {
+ max_check_attempts = 5
+ check_interval = 1m
+ retry_interval = 30s
- check_command = "hostalive"
- }
+ check_command = "hostalive"
+}
- template Service "generic-service" {
- max_check_attempts = 3
- check_interval = 1m
- retry_interval = 30s
- }
+template Service "generic-service" {
+ max_check_attempts = 3
+ check_interval = 1m
+ retry_interval = 30s
+}
+```
The `hostalive` check command is part of the
[Plugin Check Commands](10-icinga-template-library.md#icinga-template-library).
+```
+template Notification "mail-host-notification" {
+ command = "mail-host-notification"
- template Notification "mail-host-notification" {
- command = "mail-host-notification"
-
- states = [ Up, Down ]
- types = [ Problem, Acknowledgement, Recovery, Custom,
- FlappingStart, FlappingEnd,
- DowntimeStart, DowntimeEnd, DowntimeRemoved ]
+ states = [ Up, Down ]
+ types = [ Problem, Acknowledgement, Recovery, Custom,
+ FlappingStart, FlappingEnd,
+ DowntimeStart, DowntimeEnd, DowntimeRemoved ]
- period = "24x7"
- }
+ period = "24x7"
+}
- template Notification "mail-service-notification" {
- command = "mail-service-notification"
+template Notification "mail-service-notification" {
+ command = "mail-service-notification"
- states = [ OK, Warning, Critical, Unknown ]
- types = [ Problem, Acknowledgement, Recovery, Custom,
- FlappingStart, FlappingEnd,
- DowntimeStart, DowntimeEnd, DowntimeRemoved ]
+ states = [ OK, Warning, Critical, Unknown ]
+ types = [ Problem, Acknowledgement, Recovery, Custom,
+ FlappingStart, FlappingEnd,
+ DowntimeStart, DowntimeEnd, DowntimeRemoved ]
- period = "24x7"
- }
+ period = "24x7"
+}
+```
More details on `Notification` object attributes can be found [here](09-object-types.md#objecttype-notification).
Learn more about downtimes in [this chapter](08-advanced-topics.md#downtimes).
- apply ScheduledDowntime "backup-downtime" to Service {
- author = "icingaadmin"
- comment = "Scheduled downtime for backup"
-
- ranges = {
- monday = service.vars.backup_downtime
- tuesday = service.vars.backup_downtime
- wednesday = service.vars.backup_downtime
- thursday = service.vars.backup_downtime
- friday = service.vars.backup_downtime
- saturday = service.vars.backup_downtime
- sunday = service.vars.backup_downtime
- }
-
- assign where service.vars.backup_downtime != ""
- }
-
+```
+apply ScheduledDowntime "backup-downtime" to Service {
+ author = "icingaadmin"
+ comment = "Scheduled downtime for backup"
+
+ ranges = {
+ monday = service.vars.backup_downtime
+ tuesday = service.vars.backup_downtime
+ wednesday = service.vars.backup_downtime
+ thursday = service.vars.backup_downtime
+ friday = service.vars.backup_downtime
+ saturday = service.vars.backup_downtime
+ sunday = service.vars.backup_downtime
+ }
+
+ assign where service.vars.backup_downtime != ""
+}
+```
#### timeperiods.conf <a id="timeperiods-conf"></a>
and create a new global constant, e.g. `CustomPluginDir` in your [constants.conf](04-configuring-icinga-2.md#constants-conf)
configuration file:
- # cp check_snmp_int.pl /opt/monitoring/plugins
- # chmod +x /opt/monitoring/plugins/check_snmp_int.pl
+```
+# cp check_snmp_int.pl /opt/monitoring/plugins
+# chmod +x /opt/monitoring/plugins/check_snmp_int.pl
- # cat /etc/icinga2/constants.conf
- /**
- * This file defines global constants which can be used in
- * the other configuration files. At a minimum the
- * PluginDir constant should be defined.
- */
+# cat /etc/icinga2/constants.conf
+/**
+ * This file defines global constants which can be used in
+ * the other configuration files. At a minimum the
+ * PluginDir constant should be defined.
+ */
- const PluginDir = "/usr/lib/nagios/plugins"
- const CustomPluginDir = "/opt/monitoring/plugins"
+const PluginDir = "/usr/lib/nagios/plugins"
+const CustomPluginDir = "/opt/monitoring/plugins"
+```
Prior to using the check plugin with Icinga 2 you should ensure that it is working properly
by trying to run it on the console using whichever user Icinga 2 is running as:
- # su - icinga -s /bin/bash
- $ /opt/monitoring/plugins/check_snmp_int.pl --help
+```
+# su - icinga -s /bin/bash
+$ /opt/monitoring/plugins/check_snmp_int.pl --help
+```
Additional libraries may be required for some plugins. Please consult the plugin
documentation and/or the included README file for installation instructions.
This is an example for a custom `my-snmp-int` check command:
- object CheckCommand "my-snmp-int" {
- command = [ CustomPluginDir + "/check_snmp_int.pl" ]
-
- arguments = {
- "-H" = "$snmp_address$"
- "-C" = "$snmp_community$"
- "-p" = "$snmp_port$"
- "-2" = {
- set_if = "$snmp_v2$"
- }
- "-n" = "$snmp_interface$"
- "-f" = {
- set_if = "$snmp_perf$"
- }
- "-w" = "$snmp_warn$"
- "-c" = "$snmp_crit$"
- }
-
- vars.snmp_v2 = true
- vars.snmp_perf = true
- vars.snmp_warn = "300,400"
- vars.snmp_crit = "0,600"
+```
+object CheckCommand "my-snmp-int" {
+ command = [ CustomPluginDir + "/check_snmp_int.pl" ]
+
+ arguments = {
+ "-H" = "$snmp_address$"
+ "-C" = "$snmp_community$"
+ "-p" = "$snmp_port$"
+ "-2" = {
+ set_if = "$snmp_v2$"
+ }
+ "-n" = "$snmp_interface$"
+ "-f" = {
+ set_if = "$snmp_perf$"
}
+ "-w" = "$snmp_warn$"
+ "-c" = "$snmp_crit$"
+ }
+ vars.snmp_v2 = true
+ vars.snmp_perf = true
+ vars.snmp_warn = "300,400"
+ vars.snmp_crit = "0,600"
+}
+```
For further information on your monitoring configuration read the
[Monitoring Basics](03-monitoring-basics.md#monitoring-basics) chapter.
Example skeleton:
- # 1. include optional libraries
- # 2. global variables
- # 3. helper functions and/or classes
- # 4. define timeout condition
-
- if (<timeout_reached>) then
- print "UNKNOWN - Timeout (...) reached | 'time'=30.0
- endif
-
- # 5. main method
-
- <execute and fetch data>
-
- if (<threshold_critical_condition>) then
- print "CRITICAL - ... | 'time'=0.1 'myperfdatavalue'=5.0
- exit(2)
- else if (<threshold_warning_condition>) then
- print "WARNING - ... | 'time'=0.1 'myperfdatavalue'=3.0
- exit(1)
- else
- print "OK - ... | 'time'=0.2 'myperfdatavalue'=1.0
- endif
+```
+# 1. include optional libraries
+# 2. global variables
+# 3. helper functions and/or classes
+# 4. define timeout condition
+
+if (<timeout_reached>) then
+ print "UNKNOWN - Timeout (...) reached | 'time'=30.0
+endif
+
+# 5. main method
+
+<execute and fetch data>
+
+if (<threshold_critical_condition>) then
+ print "CRITICAL - ... | 'time'=0.1 'myperfdatavalue'=5.0
+ exit(2)
+else if (<threshold_warning_condition>) then
+ print "WARNING - ... | 'time'=0.1 'myperfdatavalue'=3.0
+ exit(1)
+else
+ print "OK - ... | 'time'=0.2 'myperfdatavalue'=1.0
+endif
+```
There are various plugin libraries available which will help
with plugin execution and output formatting too, for example
Have a look at this example for the `satellite` zones which have the `master` zone as a parent zone:
- object Zone "master" {
- //...
- }
+```
+object Zone "master" {
+ //...
+}
- object Zone "satellite region 1" {
- parent = "master"
- //...
- }
+object Zone "satellite region 1" {
+ parent = "master"
+ //...
+}
- object Zone "satellite region 2" {
- parent = "master"
- //...
- }
+object Zone "satellite region 2" {
+ parent = "master"
+ //...
+}
+```
There are certain limitations for child zones, e.g. their members are not allowed
to send configuration commands to the parent zone members. Vice versa, the
Here is an example configuration for two endpoints in different zones:
- object Endpoint "icinga2-master1.localdomain" {
- host = "192.168.56.101"
- }
+```
+object Endpoint "icinga2-master1.localdomain" {
+ host = "192.168.56.101"
+}
- object Endpoint "icinga2-satellite1.localdomain" {
- host = "192.168.56.105"
- }
+object Endpoint "icinga2-satellite1.localdomain" {
+ host = "192.168.56.105"
+}
- object Zone "master" {
- endpoints = [ "icinga2-master1.localdomain" ]
- }
+object Zone "master" {
+ endpoints = [ "icinga2-master1.localdomain" ]
+}
- object Zone "satellite" {
- endpoints = [ "icinga2-satellite1.localdomain" ]
- parent = "master"
- }
+object Zone "satellite" {
+ endpoints = [ "icinga2-satellite1.localdomain" ]
+ parent = "master"
+}
+```
All endpoints in the same zone work as high-availability setup. For
example, if you have two nodes in the `master` zone, they will load-balance the check execution.
In order to use the `api` feature you need to enable it and restart Icinga 2.
- icinga2 feature enable api
+```
+icinga2 feature enable api
+```
## Conventions <a id="distributed-monitoring-conventions"></a>
The following example shows how to generate a ticket on the master node `icinga2-master1.localdomain` for the client `icinga2-client1.localdomain`:
- [root@icinga2-master1.localdomain /]# icinga2 pki ticket --cn icinga2-client1.localdomain
+```
+[root@icinga2-master1.localdomain /]# icinga2 pki ticket --cn icinga2-client1.localdomain
+```
Querying the [Icinga 2 API](12-icinga2-api.md#icinga2-api) on the master requires an [ApiUser](12-icinga2-api.md#icinga2-api-authentication)
object with at least the `actions/generate-ticket` permission.
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/conf.d/api-users.conf
+```
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/conf.d/api-users.conf
- object ApiUser "client-pki-ticket" {
- password = "bea11beb7b810ea9ce6ea" //change this
- permissions = [ "actions/generate-ticket" ]
- }
+object ApiUser "client-pki-ticket" {
+ password = "bea11beb7b810ea9ce6ea" //change this
+ permissions = [ "actions/generate-ticket" ]
+}
- [root@icinga2-master1.localdomain /]# systemctl restart icinga2
+[root@icinga2-master1.localdomain /]# systemctl restart icinga2
Retrieve the ticket on the master node `icinga2-master1.localdomain` with `curl`, for example:
- [root@icinga2-master1.localdomain /]# curl -k -s -u client-pki-ticket:bea11beb7b810ea9ce6ea -H 'Accept: application/json' \
- -X POST 'https://localhost:5665/v1/actions/generate-ticket' -d '{ "cn": "icinga2-client1.localdomain" }'
+ [root@icinga2-master1.localdomain /]# curl -k -s -u client-pki-ticket:bea11beb7b810ea9ce6ea -H 'Accept: application/json' \
+ -X POST 'https://localhost:5665/v1/actions/generate-ticket' -d '{ "cn": "icinga2-client1.localdomain" }'
+```
Store that ticket number for the satellite/client setup below.
In this example we're generating a ticket on the master node `icinga2-master1.localdomain` for the client `icinga2-client1.localdomain`:
- [root@icinga2-master1.localdomain /]# icinga2 pki ticket --cn icinga2-client1.localdomain
- 4f75d2ecd253575fe9180938ebff7cbca262f96e
+```
+[root@icinga2-master1.localdomain /]# icinga2 pki ticket --cn icinga2-client1.localdomain
+4f75d2ecd253575fe9180938ebff7cbca262f96e
+```
Note: You don't need this step if you have chosen to use [On-Demand CSR Signing](06-distributed-monitoring.md#distributed-monitoring-setup-on-demand-csr-signing).
The endpoint configuration could look like this, for example:
- [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
- object Endpoint "icinga2-master1.localdomain" {
- host = "192.168.56.101"
- }
+object Endpoint "icinga2-master1.localdomain" {
+ host = "192.168.56.101"
+}
- object Endpoint "icinga2-client1.localdomain" {
- host = "192.168.56.111"
- }
+object Endpoint "icinga2-client1.localdomain" {
+ host = "192.168.56.111"
+}
+```
Next, you need to define two zones. There is no naming convention, best practice is to either use `master`, `satellite`/`client-fqdn` or to choose region names for example `Europe`, `USA` and `Asia`, though.
The `master` zone is a parent of the `icinga2-client1.localdomain` zone:
- [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
- object Zone "master" {
- endpoints = [ "icinga2-master1.localdomain" ] //array with endpoint names
- }
+object Zone "master" {
+ endpoints = [ "icinga2-master1.localdomain" ] //array with endpoint names
+}
- object Zone "icinga2-client1.localdomain" {
- endpoints = [ "icinga2-client1.localdomain" ]
+object Zone "icinga2-client1.localdomain" {
+ endpoints = [ "icinga2-client1.localdomain" ]
- parent = "master" //establish zone hierarchy
- }
+ parent = "master" //establish zone hierarchy
+}
+ ```
You don't need any local configuration on the client except for
CheckCommand definitions which can be synced using the global zone
Example on CentOS 7:
- [root@icinga2-client1.localdomain /]# icinga2 daemon -C
- [root@icinga2-client1.localdomain /]# systemctl restart icinga2
+```
+[root@icinga2-client1.localdomain /]# icinga2 daemon -C
+[root@icinga2-client1.localdomain /]# systemctl restart icinga2
- [root@icinga2-master1.localdomain /]# icinga2 daemon -C
- [root@icinga2-master1.localdomain /]# systemctl restart icinga2
+[root@icinga2-master1.localdomain /]# icinga2 daemon -C
+[root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
Once the clients have successfully connected, you are ready for the next step: **execute
a remote check on the client using the command endpoint**.
Include the host and service object configuration in the `master` zone
-- this will help adding a secondary master for high-availability later.
- [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master
+```
+[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master
+```
Add the host and service objects you want to monitor. There is
no limitation for files and directories -- best practice is to
By convention a master/satellite/client host object should use the same name as the endpoint object.
You can also add multiple hosts which execute checks against remote services/clients.
- [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
+```
+[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
- object Host "icinga2-client1.localdomain" {
- check_command = "hostalive" //check is executed on the master
- address = "192.168.56.111"
+object Host "icinga2-client1.localdomain" {
+ check_command = "hostalive" //check is executed on the master
+ address = "192.168.56.111"
- vars.client_endpoint = name //follows the convention that host name == endpoint name
- }
+ vars.client_endpoint = name //follows the convention that host name == endpoint name
+}
+```
Given that you are monitoring a Linux client, we'll add a remote [disk](10-icinga-template-library.md#plugin-check-command-disk)
check.
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
+```
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
- apply Service "disk" {
- check_command = "disk"
+apply Service "disk" {
+ check_command = "disk"
- //specify where the check is executed
- command_endpoint = host.vars.client_endpoint
+ //specify where the check is executed
+ command_endpoint = host.vars.client_endpoint
- assign where host.vars.client_endpoint
- }
+ assign where host.vars.client_endpoint
+}
+```
If you have your own custom `CheckCommand` definition, add it to the global zone:
- [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/global-templates
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/global-templates/commands.conf
+```
+[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/global-templates
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/global-templates/commands.conf
- object CheckCommand "my-cmd" {
- //...
- }
+object CheckCommand "my-cmd" {
+ //...
+}
+```
Save the changes and validate the configuration on the master node:
- [root@icinga2-master1.localdomain /]# icinga2 daemon -C
-
+```
+[root@icinga2-master1.localdomain /]# icinga2 daemon -C
+```
Restart the Icinga 2 daemon (example for CentOS 7):
- [root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
+[root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
The following steps will happen:
The endpoint configuration could look like this:
- [root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf
- object Endpoint "icinga2-master1.localdomain" {
- host = "192.168.56.101"
- }
+object Endpoint "icinga2-master1.localdomain" {
+ host = "192.168.56.101"
+}
- object Endpoint "icinga2-client2.localdomain" {
- host = "192.168.56.112"
- }
+object Endpoint "icinga2-client2.localdomain" {
+ host = "192.168.56.112"
+}
+```
Next, you need to define two zones. There is no naming convention, best practice is to either use `master`, `satellite`/`client-fqdn` or to choose region names for example `Europe`, `USA` and `Asia`, though.
The `master` zone is a parent of the `icinga2-client2.localdomain` zone:
- [root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf
- object Zone "master" {
- endpoints = [ "icinga2-master1.localdomain" ] //array with endpoint names
- }
+object Zone "master" {
+ endpoints = [ "icinga2-master1.localdomain" ] //array with endpoint names
+}
- object Zone "icinga2-client2.localdomain" {
- endpoints = [ "icinga2-client2.localdomain" ]
+object Zone "icinga2-client2.localdomain" {
+ endpoints = [ "icinga2-client2.localdomain" ]
- parent = "master" //establish zone hierarchy
- }
+ parent = "master" //establish zone hierarchy
+}
+```
Edit the `api` feature on the client `icinga2-client2.localdomain` in
the `/etc/icinga2/features-enabled/api.conf` file and set
`accept_config` to `true`.
- [root@icinga2-client2.localdomain /]# vim /etc/icinga2/features-enabled/api.conf
+```
+[root@icinga2-client2.localdomain /]# vim /etc/icinga2/features-enabled/api.conf
- object ApiListener "api" {
- //...
- accept_config = true
- }
+object ApiListener "api" {
+ //...
+ accept_config = true
+}
+```
Now it is time to validate the configuration and to restart the Icinga 2 daemon
on both nodes.
Example on CentOS 7:
- [root@icinga2-client2.localdomain /]# icinga2 daemon -C
- [root@icinga2-client2.localdomain /]# systemctl restart icinga2
-
- [root@icinga2-master1.localdomain /]# icinga2 daemon -C
- [root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
+[root@icinga2-client2.localdomain /]# icinga2 daemon -C
+[root@icinga2-client2.localdomain /]# systemctl restart icinga2
+[root@icinga2-master1.localdomain /]# icinga2 daemon -C
+[root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
**Tip**: Best practice is to use a [global zone](06-distributed-monitoring.md#distributed-monitoring-global-zone-config-sync)
for common configuration items (check commands, templates, groups, etc.).
`icinga2-master1.localdomain` and create a new directory with the same
name as your satellite/client zone name:
- [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/icinga2-client2.localdomain
+```
+[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/icinga2-client2.localdomain
+```
Add the host and service objects you want to monitor. There is
no limitation for files and directories -- best practice is to
By convention a master/satellite/client host object should use the same name as the endpoint object.
You can also add multiple hosts which execute checks against remote services/clients.
- [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/icinga2-client2.localdomain
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/icinga2-client2.localdomain]# vim hosts.conf
+```
+[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/icinga2-client2.localdomain
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/icinga2-client2.localdomain]# vim hosts.conf
- object Host "icinga2-client2.localdomain" {
- check_command = "hostalive"
- address = "192.168.56.112"
- zone = "master" //optional trick: sync the required host object to the client, but enforce the "master" zone to execute the check
- }
+object Host "icinga2-client2.localdomain" {
+ check_command = "hostalive"
+ address = "192.168.56.112"
+ zone = "master" //optional trick: sync the required host object to the client, but enforce the "master" zone to execute the check
+}
+```
Given that you are monitoring a Linux client we'll just add a local [disk](10-icinga-template-library.md#plugin-check-command-disk)
check.
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/icinga2-client2.localdomain]# vim services.conf
+```
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/icinga2-client2.localdomain]# vim services.conf
- object Service "disk" {
- host_name = "icinga2-client2.localdomain"
+object Service "disk" {
+ host_name = "icinga2-client2.localdomain"
- check_command = "disk"
- }
+ check_command = "disk"
+}
+```
Save the changes and validate the configuration on the master node:
- [root@icinga2-master1.localdomain /]# icinga2 daemon -C
+```
+[root@icinga2-master1.localdomain /]# icinga2 daemon -C
+```
Restart the Icinga 2 daemon (example for CentOS 7):
- [root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
+[root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
The following steps will happen:
Edit the `zones.conf` configuration file on the master:
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf
- object Endpoint "icinga2-master1.localdomain" {
- }
+object Endpoint "icinga2-master1.localdomain" {
+}
- object Endpoint "icinga2-client1.localdomain" {
- host = "192.168.56.111" //the master actively tries to connect to the client
- }
+object Endpoint "icinga2-client1.localdomain" {
+ host = "192.168.56.111" //the master actively tries to connect to the client
+}
- object Endpoint "icinga2-client2.localdomain" {
- host = "192.168.56.112" //the master actively tries to connect to the client
- }
+object Endpoint "icinga2-client2.localdomain" {
+ host = "192.168.56.112" //the master actively tries to connect to the client
+}
- object Zone "master" {
- endpoints = [ "icinga2-master1.localdomain" ]
- }
+object Zone "master" {
+ endpoints = [ "icinga2-master1.localdomain" ]
+}
- object Zone "icinga2-client1.localdomain" {
- endpoints = [ "icinga2-client1.localdomain" ]
+object Zone "icinga2-client1.localdomain" {
+ endpoints = [ "icinga2-client1.localdomain" ]
- parent = "master"
- }
+ parent = "master"
+}
- object Zone "icinga2-client2.localdomain" {
- endpoints = [ "icinga2-client2.localdomain" ]
+object Zone "icinga2-client2.localdomain" {
+ endpoints = [ "icinga2-client2.localdomain" ]
- parent = "master"
- }
+ parent = "master"
+}
- /* sync global commands */
- object Zone "global-templates" {
- global = true
- }
+/* sync global commands */
+object Zone "global-templates" {
+ global = true
+}
+```
The two client nodes do not necessarily need to know about each other. The only important thing
is that they know about the parent zone and their endpoint members (and optionally the global zone).
endpoint's attribute on the master node already, we don't want the clients to connect to the
master. **Choose one [connection direction](06-distributed-monitoring.md#distributed-monitoring-advanced-hints-connection-direction).**
- [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
- object Endpoint "icinga2-master1.localdomain" {
- //do not actively connect to the master by leaving out the 'host' attribute
- }
+object Endpoint "icinga2-master1.localdomain" {
+ //do not actively connect to the master by leaving out the 'host' attribute
+}
- object Endpoint "icinga2-client1.localdomain" {
- }
+object Endpoint "icinga2-client1.localdomain" {
+}
- object Zone "master" {
- endpoints = [ "icinga2-master1.localdomain" ]
- }
+object Zone "master" {
+ endpoints = [ "icinga2-master1.localdomain" ]
+}
- object Zone "icinga2-client1.localdomain" {
- endpoints = [ "icinga2-client1.localdomain" ]
+object Zone "icinga2-client1.localdomain" {
+ endpoints = [ "icinga2-client1.localdomain" ]
- parent = "master"
- }
+ parent = "master"
+}
- /* sync global commands */
- object Zone "global-templates" {
- global = true
- }
+/* sync global commands */
+object Zone "global-templates" {
+ global = true
+}
- [root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf
+[root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf
- object Endpoint "icinga2-master1.localdomain" {
- //do not actively connect to the master by leaving out the 'host' attribute
- }
+object Endpoint "icinga2-master1.localdomain" {
+ //do not actively connect to the master by leaving out the 'host' attribute
+}
- object Endpoint "icinga2-client2.localdomain" {
- }
+object Endpoint "icinga2-client2.localdomain" {
+}
- object Zone "master" {
- endpoints = [ "icinga2-master1.localdomain" ]
- }
+object Zone "master" {
+ endpoints = [ "icinga2-master1.localdomain" ]
+}
- object Zone "icinga2-client2.localdomain" {
- endpoints = [ "icinga2-client2.localdomain" ]
+object Zone "icinga2-client2.localdomain" {
+ endpoints = [ "icinga2-client2.localdomain" ]
- parent = "master"
- }
+ parent = "master"
+}
- /* sync global commands */
- object Zone "global-templates" {
- global = true
- }
+/* sync global commands */
+object Zone "global-templates" {
+ global = true
+}
+```
Now it is time to define the two client hosts and apply service checks using
the command endpoint execution method on them. Note: You can also use the
Create a new configuration directory on the master node:
- [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master
+```
+[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master
+```
Add the two client nodes as host objects:
- [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
+```
+[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
- object Host "icinga2-client1.localdomain" {
- check_command = "hostalive"
- address = "192.168.56.111"
- vars.client_endpoint = name //follows the convention that host name == endpoint name
- }
+object Host "icinga2-client1.localdomain" {
+ check_command = "hostalive"
+ address = "192.168.56.111"
+ vars.client_endpoint = name //follows the convention that host name == endpoint name
+}
- object Host "icinga2-client2.localdomain" {
- check_command = "hostalive"
- address = "192.168.56.112"
- vars.client_endpoint = name //follows the convention that host name == endpoint name
- }
+object Host "icinga2-client2.localdomain" {
+ check_command = "hostalive"
+ address = "192.168.56.112"
+ vars.client_endpoint = name //follows the convention that host name == endpoint name
+}
+```
Add services using command endpoint checks:
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
+```
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
- apply Service "ping4" {
- check_command = "ping4"
- //check is executed on the master node
- assign where host.address
- }
+apply Service "ping4" {
+ check_command = "ping4"
+ //check is executed on the master node
+ assign where host.address
+}
- apply Service "disk" {
- check_command = "disk"
+apply Service "disk" {
+ check_command = "disk"
- //specify where the check is executed
- command_endpoint = host.vars.client_endpoint
+ //specify where the check is executed
+ command_endpoint = host.vars.client_endpoint
- assign where host.vars.client_endpoint
- }
+ assign where host.vars.client_endpoint
+}
+```
Validate the configuration and restart Icinga 2 on the master node `icinga2-master1.localdomain`.
- [root@icinga2-master1.localdomain /]# icinga2 daemon -C
- [root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
+[root@icinga2-master1.localdomain /]# icinga2 daemon -C
+[root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
Open Icinga Web 2 and check the two newly created client hosts with two new services
-- one executed locally (`ping4`) and one using command endpoint (`disk`).
The zone hierarchy could look like this. It involves putting the two master nodes
`icinga2-master1.localdomain` and `icinga2-master2.localdomain` into the `master` zone.
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf
- object Endpoint "icinga2-master1.localdomain" {
- host = "192.168.56.101"
- }
+object Endpoint "icinga2-master1.localdomain" {
+ host = "192.168.56.101"
+}
- object Endpoint "icinga2-master2.localdomain" {
- host = "192.168.56.102"
- }
+object Endpoint "icinga2-master2.localdomain" {
+ host = "192.168.56.102"
+}
- object Endpoint "icinga2-client1.localdomain" {
- host = "192.168.56.111" //the master actively tries to connect to the client
- }
+object Endpoint "icinga2-client1.localdomain" {
+ host = "192.168.56.111" //the master actively tries to connect to the client
+}
- object Endpoint "icinga2-client2.localdomain" {
- host = "192.168.56.112" //the master actively tries to connect to the client
- }
+object Endpoint "icinga2-client2.localdomain" {
+ host = "192.168.56.112" //the master actively tries to connect to the client
+}
- object Zone "master" {
- endpoints = [ "icinga2-master1.localdomain", "icinga2-master2.localdomain" ]
- }
+object Zone "master" {
+ endpoints = [ "icinga2-master1.localdomain", "icinga2-master2.localdomain" ]
+}
- object Zone "icinga2-client1.localdomain" {
- endpoints = [ "icinga2-client1.localdomain" ]
+object Zone "icinga2-client1.localdomain" {
+ endpoints = [ "icinga2-client1.localdomain" ]
- parent = "master"
- }
+ parent = "master"
+}
- object Zone "icinga2-client2.localdomain" {
- endpoints = [ "icinga2-client2.localdomain" ]
+object Zone "icinga2-client2.localdomain" {
+ endpoints = [ "icinga2-client2.localdomain" ]
- parent = "master"
- }
+ parent = "master"
+}
- /* sync global commands */
- object Zone "global-templates" {
- global = true
- }
+/* sync global commands */
+object Zone "global-templates" {
+ global = true
+}
+```
The two client nodes do not necessarily need to know about each other. The only important thing
is that they know about the parent zone and their endpoint members (and optionally about the global zone).
endpoint's attribute on the master node already, we don't want the clients to connect to the
master nodes. **Choose one [connection direction](06-distributed-monitoring.md#distributed-monitoring-advanced-hints-connection-direction).**
- [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
- object Endpoint "icinga2-master1.localdomain" {
- //do not actively connect to the master by leaving out the 'host' attribute
- }
+object Endpoint "icinga2-master1.localdomain" {
+ //do not actively connect to the master by leaving out the 'host' attribute
+}
- object Endpoint "icinga2-master2.localdomain" {
- //do not actively connect to the master by leaving out the 'host' attribute
- }
+object Endpoint "icinga2-master2.localdomain" {
+ //do not actively connect to the master by leaving out the 'host' attribute
+}
- object Endpoint "icinga2-client1.localdomain" {
- }
+object Endpoint "icinga2-client1.localdomain" {
+}
- object Zone "master" {
- endpoints = [ "icinga2-master1.localdomain", "icinga2-master2.localdomain" ]
- }
+object Zone "master" {
+ endpoints = [ "icinga2-master1.localdomain", "icinga2-master2.localdomain" ]
+}
- object Zone "icinga2-client1.localdomain" {
- endpoints = [ "icinga2-client1.localdomain" ]
+object Zone "icinga2-client1.localdomain" {
+ endpoints = [ "icinga2-client1.localdomain" ]
- parent = "master"
- }
+ parent = "master"
+}
- /* sync global commands */
- object Zone "global-templates" {
- global = true
- }
+/* sync global commands */
+object Zone "global-templates" {
+ global = true
+}
- [root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf
+[root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf
- object Endpoint "icinga2-master1.localdomain" {
- //do not actively connect to the master by leaving out the 'host' attribute
- }
+object Endpoint "icinga2-master1.localdomain" {
+ //do not actively connect to the master by leaving out the 'host' attribute
+}
- object Endpoint "icinga2-master2.localdomain" {
- //do not actively connect to the master by leaving out the 'host' attribute
- }
+object Endpoint "icinga2-master2.localdomain" {
+ //do not actively connect to the master by leaving out the 'host' attribute
+}
- object Endpoint "icinga2-client2.localdomain" {
- }
+object Endpoint "icinga2-client2.localdomain" {
+}
- object Zone "master" {
- endpoints = [ "icinga2-master1.localdomain", "icinga2-master2.localdomain" ]
- }
+object Zone "master" {
+ endpoints = [ "icinga2-master1.localdomain", "icinga2-master2.localdomain" ]
+}
- object Zone "icinga2-client2.localdomain" {
- endpoints = [ "icinga2-client2.localdomain" ]
+object Zone "icinga2-client2.localdomain" {
+ endpoints = [ "icinga2-client2.localdomain" ]
- parent = "master"
- }
+ parent = "master"
+}
- /* sync global commands */
- object Zone "global-templates" {
- global = true
- }
+/* sync global commands */
+object Zone "global-templates" {
+ global = true
+}
+```
Now it is time to define the two client hosts and apply service checks using
the command endpoint execution method. Note: You can also use the
**Note**: The secondary master node `icinga2-master2.localdomain` receives the
configuration using the [config sync mode](06-distributed-monitoring.md#distributed-monitoring-top-down-config-sync).
- [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master
+```
+[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master
+```
Add the two client nodes as host objects:
- [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
+```
+[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
- object Host "icinga2-client1.localdomain" {
- check_command = "hostalive"
- address = "192.168.56.111"
- vars.client_endpoint = name //follows the convention that host name == endpoint name
- }
+object Host "icinga2-client1.localdomain" {
+ check_command = "hostalive"
+ address = "192.168.56.111"
+ vars.client_endpoint = name //follows the convention that host name == endpoint name
+}
- object Host "icinga2-client2.localdomain" {
- check_command = "hostalive"
- address = "192.168.56.112"
- vars.client_endpoint = name //follows the convention that host name == endpoint name
- }
+object Host "icinga2-client2.localdomain" {
+ check_command = "hostalive"
+ address = "192.168.56.112"
+ vars.client_endpoint = name //follows the convention that host name == endpoint name
+}
+```
Add services using command endpoint checks:
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
+```
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
- apply Service "ping4" {
- check_command = "ping4"
- //check is executed on the master node
- assign where host.address
- }
+apply Service "ping4" {
+ check_command = "ping4"
+ //check is executed on the master node
+ assign where host.address
+}
- apply Service "disk" {
- check_command = "disk"
+apply Service "disk" {
+ check_command = "disk"
- //specify where the check is executed
- command_endpoint = host.vars.client_endpoint
+ //specify where the check is executed
+ command_endpoint = host.vars.client_endpoint
- assign where host.vars.client_endpoint
- }
+ assign where host.vars.client_endpoint
+}
+```
Validate the configuration and restart Icinga 2 on the master node `icinga2-master1.localdomain`.
- [root@icinga2-master1.localdomain /]# icinga2 daemon -C
- [root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
+[root@icinga2-master1.localdomain /]# icinga2 daemon -C
+[root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
Open Icinga Web 2 and check the two newly created client hosts with two new services
-- one executed locally (`ping4`) and one using command endpoint (`disk`).
In order to minimize the effort, we'll sync the client zone and endpoint configuration to the
satellites where the connection information is needed as well.
- [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/{master,satellite,global-templates}
- [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/satellite
+```
+[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/{master,satellite,global-templates}
+[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/satellite
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client1.localdomain.conf
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client1.localdomain.conf
- object Endpoint "icinga2-client1.localdomain" {
- host = "192.168.56.111" //the satellite actively tries to connect to the client
- }
+object Endpoint "icinga2-client1.localdomain" {
+ host = "192.168.56.111" //the satellite actively tries to connect to the client
+}
- object Zone "icinga2-client1.localdomain" {
- endpoints = [ "icinga2-client1.localdomain" ]
+object Zone "icinga2-client1.localdomain" {
+ endpoints = [ "icinga2-client1.localdomain" ]
- parent = "satellite"
- }
+ parent = "satellite"
+}
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client2.localdomain.conf
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client2.localdomain.conf
- object Endpoint "icinga2-client2.localdomain" {
- host = "192.168.56.112" //the satellite actively tries to connect to the client
- }
+object Endpoint "icinga2-client2.localdomain" {
+ host = "192.168.56.112" //the satellite actively tries to connect to the client
+}
- object Zone "icinga2-client2.localdomain" {
- endpoints = [ "icinga2-client2.localdomain" ]
+object Zone "icinga2-client2.localdomain" {
+ endpoints = [ "icinga2-client2.localdomain" ]
- parent = "satellite"
- }
+ parent = "satellite"
+}
+```
The two client nodes do not necessarily need to know about each other, either. The only important thing
is that they know about the parent zone (the satellite) and their endpoint members (and optionally the global zone).
Example for `icinga2-client1.localdomain`:
- [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
- object Endpoint "icinga2-satellite1.localdomain" {
- //do not actively connect to the satellite by leaving out the 'host' attribute
- }
+object Endpoint "icinga2-satellite1.localdomain" {
+ //do not actively connect to the satellite by leaving out the 'host' attribute
+}
- object Endpoint "icinga2-satellite2.localdomain" {
- //do not actively connect to the satellite by leaving out the 'host' attribute
- }
+object Endpoint "icinga2-satellite2.localdomain" {
+ //do not actively connect to the satellite by leaving out the 'host' attribute
+}
- object Endpoint "icinga2-client1.localdomain" {
- //that's us
- }
+object Endpoint "icinga2-client1.localdomain" {
+ //that's us
+}
- object Zone "satellite" {
- endpoints = [ "icinga2-satellite1.localdomain", "icinga2-satellite2.localdomain" ]
- }
+object Zone "satellite" {
+ endpoints = [ "icinga2-satellite1.localdomain", "icinga2-satellite2.localdomain" ]
+}
- object Zone "icinga2-client1.localdomain" {
- endpoints = [ "icinga2-client1.localdomain" ]
+object Zone "icinga2-client1.localdomain" {
+ endpoints = [ "icinga2-client1.localdomain" ]
- parent = "satellite"
- }
+ parent = "satellite"
+}
- /* sync global commands */
- object Zone "global-templates" {
- global = true
- }
+/* sync global commands */
+object Zone "global-templates" {
+ global = true
+}
- object Zone "director-global" {
- global = true
- }
+object Zone "director-global" {
+ global = true
+}
+```
Example for `icinga2-client2.localdomain`:
- [root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-client2.localdomain /]# vim /etc/icinga2/zones.conf
- object Endpoint "icinga2-satellite1.localdomain" {
- //do not actively connect to the satellite by leaving out the 'host' attribute
- }
+object Endpoint "icinga2-satellite1.localdomain" {
+ //do not actively connect to the satellite by leaving out the 'host' attribute
+}
- object Endpoint "icinga2-satellite2.localdomain" {
- //do not actively connect to the satellite by leaving out the 'host' attribute
- }
+object Endpoint "icinga2-satellite2.localdomain" {
+ //do not actively connect to the satellite by leaving out the 'host' attribute
+}
- object Endpoint "icinga2-client2.localdomain" {
- //that's us
- }
+object Endpoint "icinga2-client2.localdomain" {
+ //that's us
+}
- object Zone "satellite" {
- endpoints = [ "icinga2-satellite1.localdomain", "icinga2-satellite2.localdomain" ]
- }
+object Zone "satellite" {
+ endpoints = [ "icinga2-satellite1.localdomain", "icinga2-satellite2.localdomain" ]
+}
- object Zone "icinga2-client2.localdomain" {
- endpoints = [ "icinga2-client2.localdomain" ]
+object Zone "icinga2-client2.localdomain" {
+ endpoints = [ "icinga2-client2.localdomain" ]
- parent = "satellite"
- }
+ parent = "satellite"
+}
- /* sync global commands */
- object Zone "global-templates" {
- global = true
- }
+/* sync global commands */
+object Zone "global-templates" {
+ global = true
+}
- object Zone "director-global" {
- global = true
- }
+object Zone "director-global" {
+ global = true
+}
+```
Now it is time to define the two client hosts on the master, sync them to the satellites
and apply service checks using the command endpoint execution method to them.
We've already created the directories in `/etc/icinga2/zones.d` including the files for the
zone and endpoint configuration for the clients.
- [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/satellite
+```
+[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/satellite
+```
Add the host object configuration for the `icinga2-client1.localdomain` client. You should
have created the configuration file in the previous steps and it should contain the endpoint
and zone object configuration already.
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client1.localdomain.conf
+```
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client1.localdomain.conf
- object Host "icinga2-client1.localdomain" {
- check_command = "hostalive"
- address = "192.168.56.111"
- vars.client_endpoint = name //follows the convention that host name == endpoint name
- }
+object Host "icinga2-client1.localdomain" {
+ check_command = "hostalive"
+ address = "192.168.56.111"
+ vars.client_endpoint = name //follows the convention that host name == endpoint name
+}
+```
Add the host object configuration for the `icinga2-client2.localdomain` client configuration file:
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client2.localdomain.conf
+```
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim icinga2-client2.localdomain.conf
- object Host "icinga2-client2.localdomain" {
- check_command = "hostalive"
- address = "192.168.56.112"
- vars.client_endpoint = name //follows the convention that host name == endpoint name
- }
+object Host "icinga2-client2.localdomain" {
+ check_command = "hostalive"
+ address = "192.168.56.112"
+ vars.client_endpoint = name //follows the convention that host name == endpoint name
+}
+```
Add a service object which is executed on the satellite nodes (e.g. `ping4`). Pin the apply rule to the `satellite` zone only.
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim services.conf
+```
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim services.conf
- apply Service "ping4" {
- check_command = "ping4"
- //check is executed on the satellite node
- assign where host.zone == "satellite" && host.address
- }
+apply Service "ping4" {
+ check_command = "ping4"
+ //check is executed on the satellite node
+ assign where host.zone == "satellite" && host.address
+}
+```
Add services using command endpoint checks. Pin the apply rules to the `satellite` zone only.
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim services.conf
+```
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/satellite]# vim services.conf
- apply Service "disk" {
- check_command = "disk"
+apply Service "disk" {
+ check_command = "disk"
- //specify where the check is executed
- command_endpoint = host.vars.client_endpoint
+ //specify where the check is executed
+ command_endpoint = host.vars.client_endpoint
- assign where host.zone == "satellite" && host.vars.client_endpoint
- }
+ assign where host.zone == "satellite" && host.vars.client_endpoint
+}
+```
Validate the configuration and restart Icinga 2 on the master node `icinga2-master1.localdomain`.
- [root@icinga2-master1.localdomain /]# icinga2 daemon -C
- [root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
+[root@icinga2-master1.localdomain /]# icinga2 daemon -C
+[root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
Open Icinga Web 2 and check the two newly created client hosts with two new services
-- one executed locally (`ping4`) and one using command endpoint (`disk`).
The zone object configuration must be deployed on all nodes which should receive
the global configuration files:
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf
- object Zone "global-commands" {
- global = true
- }
+object Zone "global-commands" {
+ global = true
+}
+```
The default global zones generated by the setup wizards are called `global-templates` and `director-global`.
Similar to the zone configuration sync you'll need to create a new directory in
`/etc/icinga2/zones.d`:
- [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/global-commands
+```
+[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/global-commands
+```
Next, add a new check command, for example:
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/global-commands/web.conf
+```
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/global-commands/web.conf
- object CheckCommand "webinject" {
- //...
- }
+object CheckCommand "webinject" {
+ //...
+}
+```
Restart the client(s) which should receive the global zone before
before restarting the parent master/satellite nodes.
Example:
- [root@icinga2-master1.localdomain /]# cd /etc/icinga2/conf.d
- [root@icinga2-master1.localdomain /etc/icinga2/conf.d]# cp {commands,groups,notifications,services,templates,timeperiods,users}.conf /etc/icinga2/zones.d/global-templates
+```
+[root@icinga2-master1.localdomain /]# cd /etc/icinga2/conf.d
+[root@icinga2-master1.localdomain /etc/icinga2/conf.d]# cp {commands,groups,notifications,services,templates,timeperiods,users}.conf /etc/icinga2/zones.d/global-templates
+```
### Health Checks <a id="distributed-monitoring-health-checks"></a>
The `cluster` check, for example, will check if all endpoints in the current zone and the directly
connected zones are working properly:
- [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/icinga2-master1.localdomain.conf
+```
+[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/icinga2-master1.localdomain.conf
- object Host "icinga2-master1.localdomain" {
- check_command = "hostalive"
- address = "192.168.56.101"
- }
+object Host "icinga2-master1.localdomain" {
+ check_command = "hostalive"
+ address = "192.168.56.101"
+}
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/cluster.conf
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/cluster.conf
- object Service "cluster" {
- check_command = "cluster"
- check_interval = 5s
- retry_interval = 1s
+object Service "cluster" {
+ check_command = "cluster"
+ check_interval = 5s
+ retry_interval = 1s
- host_name = "icinga2-master1.localdomain"
- }
+ host_name = "icinga2-master1.localdomain"
+}
+```
The `cluster-zone` check will test whether the configured target zone is currently
connected or not. This example adds a health check for the [ha master with clients scenario](06-distributed-monitoring.md#distributed-monitoring-scenarios-ha-master-clients).
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/services.conf
+```
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/services.conf
- apply Service "cluster-health" {
- check_command = "cluster-zone"
+apply Service "cluster-health" {
+ check_command = "cluster-zone"
- display_name = "cluster-health-" + host.name
+ display_name = "cluster-health-" + host.name
- /* This follows the convention that the client zone name is the FQDN which is the same as the host object name. */
- vars.cluster_zone = host.name
+ /* This follows the convention that the client zone name is the FQDN which is the same as the host object name. */
+ vars.cluster_zone = host.name
- assign where host.vars.client_endpoint
- }
+ assign where host.vars.client_endpoint
+}
+```
In case you cannot assign the `cluster_zone` attribute, add specific
checks to your cluster:
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/cluster.conf
-
- object Service "cluster-zone-satellite" {
- check_command = "cluster-zone"
- check_interval = 5s
- retry_interval = 1s
- vars.cluster_zone = "satellite"
+```
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/cluster.conf
- host_name = "icinga2-master1.localdomain"
- }
+object Service "cluster-zone-satellite" {
+ check_command = "cluster-zone"
+ check_interval = 5s
+ retry_interval = 1s
+ vars.cluster_zone = "satellite"
+ host_name = "icinga2-master1.localdomain"
+}
+```
If you are using top down checks with command endpoint configuration, you can
add a dependency which prevents notifications for all other failing services:
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/dependencies.conf
+```
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/dependencies.conf
- apply Dependency "health-check" to Service {
- parent_service_name = "child-health"
+apply Dependency "health-check" to Service {
+ parent_service_name = "child-health"
- states = [ OK ]
- disable_notifications = true
+ states = [ OK ]
+ disable_notifications = true
- assign where host.vars.client_endpoint
- ignore where service.name == "child-health"
- }
+ assign where host.vars.client_endpoint
+ ignore where service.name == "child-health"
+}
+```
### Pin Checks in a Zone <a id="distributed-monitoring-pin-checks-zone"></a>
the `command_endpoint` attribute. This is reasonable if you want to
execute a local disk check in the `master` Zone on a specific endpoint then.
- [root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/icinga2-master1.localdomain.conf
+```
+[root@icinga2-master1.localdomain /]# mkdir -p /etc/icinga2/zones.d/master
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/icinga2-master1.localdomain.conf
- object Host "icinga2-master1.localdomain" {
- check_command = "hostalive"
- address = "192.168.56.101"
- }
+object Host "icinga2-master1.localdomain" {
+ check_command = "hostalive"
+ address = "192.168.56.101"
+}
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/services.conf
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.d/master/services.conf
- apply Service "disk" {
- check_command = "disk"
+apply Service "disk" {
+ check_command = "disk"
- command_endpoint = host.name //requires a host object matching the endpoint object name e.g. icinga2-master1.localdomain
+ command_endpoint = host.name //requires a host object matching the endpoint object name e.g. icinga2-master1.localdomain
- assign where host.zone == "master" && match("icinga2-master*", host.name)
- }
+ assign where host.zone == "master" && match("icinga2-master*", host.name)
+}
+```
The `host.zone` attribute check inside the expression ensures that
the service object is only created for host objects inside the `master`
By default ICMP requests are disabled in the Windows firewall. You can
change that by [adding a new rule](https://support.microsoft.com/en-us/kb/947709).
- C:\WINDOWS\system32>netsh advfirewall firewall add rule name="ICMP Allow incoming V4 echo request" protocol=icmpv4:8,any dir=in action=allow
+```
+C:\WINDOWS\system32>netsh advfirewall firewall add rule name="ICMP Allow incoming V4 echo request" protocol=icmpv4:8,any dir=in action=allow
+```
#### Icinga 2 <a id="distributed-monitoring-windows-firewall-icinga2"></a>
If your master/satellite nodes should actively connect to the Windows client
you'll also need to ensure that port `5665` is enabled.
- C:\WINDOWS\system32>netsh advfirewall firewall add rule name="Open port 5665 (Icinga 2)" dir=in action=allow protocol=TCP localport=5665
+```
+C:\WINDOWS\system32>netsh advfirewall firewall add rule name="Open port 5665 (Icinga 2)" dir=in action=allow protocol=TCP localport=5665
+```
#### NSClient++ API <a id="distributed-monitoring-windows-firewall-nsclient-api"></a>
If the [check_nscp_api](06-distributed-monitoring.md#distributed-monitoring-windows-nscp-check-api)
plugin is used to query NSClient++, you need to ensure that its port is enabled.
- C:\WINDOWS\system32>netsh advfirewall firewall add rule name="Open port 8443 (NSClient++ API)" dir=in action=allow protocol=TCP localport=8443
+```
+C:\WINDOWS\system32>netsh advfirewall firewall add rule name="Open port 8443 (NSClient++ API)" dir=in action=allow protocol=TCP localport=8443
+```
For security reasons, it is advised to enable the NSClient++ HTTP API for local
connection from the Icinga 2 client only. Remote connections to the HTTP API
Add the following `include` statement on all your nodes (master, satellite, client):
- vim /etc/icinga2/icinga2.conf
+```
+vim /etc/icinga2/icinga2.conf
- include <windows-plugins>
+include <windows-plugins>
+```
Based on the [master with clients](06-distributed-monitoring.md#distributed-monitoring-master-clients)
scenario we'll now add a local disk check.
First, add the client node as host object:
- [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
+```
+[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
- object Host "icinga2-client2.localdomain" {
- check_command = "hostalive"
- address = "192.168.56.112"
- vars.client_endpoint = name //follows the convention that host name == endpoint name
- vars.os_type = "windows"
- }
+object Host "icinga2-client2.localdomain" {
+ check_command = "hostalive"
+ address = "192.168.56.112"
+ vars.client_endpoint = name //follows the convention that host name == endpoint name
+ vars.os_type = "windows"
+}
+```
Next, add the disk check using command endpoint checks (details in the
[disk-windows](10-icinga-template-library.md#windows-plugins-disk-windows) documentation):
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
+```
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
- apply Service "disk C:" {
- check_command = "disk-windows"
+apply Service "disk C:" {
+ check_command = "disk-windows"
- vars.disk_win_path = "C:"
+ vars.disk_win_path = "C:"
- //specify where the check is executed
- command_endpoint = host.vars.client_endpoint
+ //specify where the check is executed
+ command_endpoint = host.vars.client_endpoint
- assign where host.vars.os_type == "windows" && host.vars.client_endpoint
- }
+ assign where host.vars.os_type == "windows" && host.vars.client_endpoint
+}
+```
Validate the configuration and restart Icinga 2.
- [root@icinga2-master1.localdomain /]# icinga2 daemon -C
- [root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
+[root@icinga2-master1.localdomain /]# icinga2 daemon -C
+[root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
Open Icinga Web 2 and check your newly added Windows disk check :)
Define a host object called `icinga2-client2.localdomain` on the master. Add the `nscp_api_password`
custom attribute and specify the drives to check.
- [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
+```
+[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
- object Host "icinga2-client1.localdomain" {
- check_command = "hostalive"
- address = "192.168.56.111"
- vars.client_endpoint = name //follows the convention that host name == endpoint name
- vars.os_type = "Windows"
- vars.nscp_api_password = "icinga"
- vars.drives = [ "C:", "D:" ]
- }
+object Host "icinga2-client1.localdomain" {
+check_command = "hostalive"
+address = "192.168.56.111"
+vars.client_endpoint = name //follows the convention that host name == endpoint name
+vars.os_type = "Windows"
+vars.nscp_api_password = "icinga"
+vars.drives = [ "C:", "D:" ]
+}
+```
The service checks are generated using an [apply for](03-monitoring-basics.md#using-apply-for)
rule based on `host.vars.drives`:
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
+```
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
- apply Service "nscp-api-" for (drive in host.vars.drives) {
- import "generic-service"
+apply Service "nscp-api-" for (drive in host.vars.drives) {
+ import "generic-service"
- check_command = "nscp_api"
- command_endpoint = host.vars.client_endpoint
+ check_command = "nscp_api"
+ command_endpoint = host.vars.client_endpoint
- //display_name = "nscp-drive-" + drive
+ //display_name = "nscp-drive-" + drive
- vars.nscp_api_host = "localhost"
- vars.nscp_api_query = "check_drivesize"
- vars.nscp_api_password = host.vars.nscp_api_password
- vars.nscp_api_arguments = [ "drive=" + drive ]
+ vars.nscp_api_host = "localhost"
+ vars.nscp_api_query = "check_drivesize"
+ vars.nscp_api_password = host.vars.nscp_api_password
+ vars.nscp_api_arguments = [ "drive=" + drive ]
- ignore where host.vars.os_type != "Windows"
- }
+ ignore where host.vars.os_type != "Windows"
+}
+```
Validate the configuration and restart Icinga 2.
- [root@icinga2-master1.localdomain /]# icinga2 daemon -C
- [root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
+[root@icinga2-master1.localdomain /]# icinga2 daemon -C
+[root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
Two new services ("nscp-drive-D:" and "nscp-drive-C:") will be visible in Icinga Web 2.
the command on the master. This also requires a different value for `nscp_api_host`
which defaults to `host.address`.
- //command_endpoint = host.vars.client_endpoint
+```
+ //command_endpoint = host.vars.client_endpoint
- //vars.nscp_api_host = "localhost"
+ //vars.nscp_api_host = "localhost"
+```
You can verify the check execution by looking at the `Check Source` attribute
in Icinga Web 2 or the REST API.
If you want to monitor specific Windows services, you could use the following example:
- [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
+```
+[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
- object Host "icinga2-client1.localdomain" {
- check_command = "hostalive"
- address = "192.168.56.111"
- vars.client_endpoint = name //follows the convention that host name == endpoint name
- vars.os_type = "Windows"
- vars.nscp_api_password = "icinga"
- vars.services = [ "Windows Update", "wscsvc" ]
- }
+object Host "icinga2-client1.localdomain" {
+check_command = "hostalive"
+address = "192.168.56.111"
+vars.client_endpoint = name //follows the convention that host name == endpoint name
+vars.os_type = "Windows"
+vars.nscp_api_password = "icinga"
+vars.services = [ "Windows Update", "wscsvc" ]
+}
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
- apply Service "nscp-api-" for (svc in host.vars.services) {
- import "generic-service"
+apply Service "nscp-api-" for (svc in host.vars.services) {
+ import "generic-service"
- check_command = "nscp_api"
- command_endpoint = host.vars.client_endpoint
+ check_command = "nscp_api"
+ command_endpoint = host.vars.client_endpoint
- //display_name = "nscp-service-" + svc
+ //display_name = "nscp-service-" + svc
- vars.nscp_api_host = "localhost"
- vars.nscp_api_query = "check_service"
- vars.nscp_api_password = host.vars.nscp_api_password
- vars.nscp_api_arguments = [ "service=" + svc ]
+ vars.nscp_api_host = "localhost"
+ vars.nscp_api_query = "check_service"
+ vars.nscp_api_password = host.vars.nscp_api_password
+ vars.nscp_api_arguments = [ "service=" + svc ]
- ignore where host.vars.os_type != "Windows"
- }
+ ignore where host.vars.os_type != "Windows"
+}
+```
#### NSCLient++ with nscp-local <a id="distributed-monitoring-windows-nscp-check-local"></a>
Add the following `include` statement on all your nodes (master, satellite, client):
- vim /etc/icinga2/icinga2.conf
+```
+vim /etc/icinga2/icinga2.conf
- include <nscp>
+include <nscp>
+```
The CheckCommand definitions will automatically determine the installed path
to the `nscp.exe` binary.
First, add the client node as host object:
- [root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
+```
+[root@icinga2-master1.localdomain /]# cd /etc/icinga2/zones.d/master
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim hosts.conf
- object Host "icinga2-client1.localdomain" {
- check_command = "hostalive"
- address = "192.168.56.111"
- vars.client_endpoint = name //follows the convention that host name == endpoint name
- vars.os_type = "windows"
- }
+object Host "icinga2-client1.localdomain" {
+ check_command = "hostalive"
+ address = "192.168.56.111"
+ vars.client_endpoint = name //follows the convention that host name == endpoint name
+ vars.os_type = "windows"
+}
+```
Next, add a performance counter check using command endpoint checks (details in the
[nscp-local-counter](10-icinga-template-library.md#nscp-check-local-counter) documentation):
- [root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
+```
+[root@icinga2-master1.localdomain /etc/icinga2/zones.d/master]# vim services.conf
- apply Service "nscp-local-counter-cpu" {
- check_command = "nscp-local-counter"
- command_endpoint = host.vars.client_endpoint
+apply Service "nscp-local-counter-cpu" {
+ check_command = "nscp-local-counter"
+ command_endpoint = host.vars.client_endpoint
- vars.nscp_counter_name = "\\Processor(_total)\\% Processor Time"
- vars.nscp_counter_perfsyntax = "Total Processor Time"
- vars.nscp_counter_warning = 1
- vars.nscp_counter_critical = 5
+ vars.nscp_counter_name = "\\Processor(_total)\\% Processor Time"
+ vars.nscp_counter_perfsyntax = "Total Processor Time"
+ vars.nscp_counter_warning = 1
+ vars.nscp_counter_critical = 5
- vars.nscp_counter_showall = true
+ vars.nscp_counter_showall = true
- assign where host.vars.os_type == "windows" && host.vars.client_endpoint
- }
+ assign where host.vars.os_type == "windows" && host.vars.client_endpoint
+}
+```
Validate the configuration and restart Icinga 2.
- [root@icinga2-master1.localdomain /]# icinga2 daemon -C
- [root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
+[root@icinga2-master1.localdomain /]# icinga2 daemon -C
+[root@icinga2-master1.localdomain /]# systemctl restart icinga2
+```
Open Icinga Web 2 and check your newly added Windows NSClient++ check :)
Example:
- # icinga2 feature enable checker
+```
+# icinga2 feature enable checker
+```
All nodes in the same zone load-balance the check execution. If one instance shuts down,
the other nodes will automatically take over the remaining checks.
Example:
- # icinga2 feature enable notification
+```
+# icinga2 feature enable notification
+```
Notifications are load-balanced amongst all nodes in a zone. By default this functionality
is enabled.
Example DB IDO MySQL:
- # icinga2 feature enable ido-mysql
+```
+# icinga2 feature enable ido-mysql
+```
By default the DB IDO feature only runs on one node. All other nodes in the same zone disable
the active IDO database connection at runtime. The node with the active DB IDO connection is
to the database and bail out if another endpoint is active. You can manually verify that
by running the following query command:
- icinga=> SELECT status_update_time, endpoint_name FROM icinga_programstatus;
- status_update_time | endpoint_name
- ------------------------+---------------
- 2016-08-15 15:52:26+02 | icinga2-master1.localdomain
- (1 Zeile)
+```
+icinga=> SELECT status_update_time, endpoint_name FROM icinga_programstatus;
+ status_update_time | endpoint_name
+------------------------+---------------
+ 2016-08-15 15:52:26+02 | icinga2-master1.localdomain
+(1 Zeile)
+```
This is useful when the cluster connection between endpoints breaks, and prevents
data duplication in split-brain-scenarios. The failover timeout can be set for the
Example for the master node `icinga2-master1.localdomain` actively connecting
to the client node `icinga2-client1.localdomain`:
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf
- //...
+//...
- object Endpoint "icinga2-client1.localdomain" {
- host = "192.168.56.111" //the master actively tries to connect to the client
- log_duration = 0
- }
+object Endpoint "icinga2-client1.localdomain" {
+ host = "192.168.56.111" //the master actively tries to connect to the client
+ log_duration = 0
+}
+```
Example for the client node `icinga2-client1.localdomain` not actively
connecting to the master node `icinga2-master1.localdomain`:
- [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
- //...
+//...
- object Endpoint "icinga2-master1.localdomain" {
- //do not actively connect to the master by leaving out the 'host' attribute
- log_duration = 0
- }
+object Endpoint "icinga2-master1.localdomain" {
+ //do not actively connect to the master by leaving out the 'host' attribute
+ log_duration = 0
+}
+```
It is not necessary that both the master and the client node establish
two connections to each other. Icinga 2 will only use one connection
Configuration on the master node `icinga2-master1.localdomain`:
- [root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-master1.localdomain /]# vim /etc/icinga2/zones.conf
- //...
+//...
- object Endpoint "icinga2-client1.localdomain" {
- host = "192.168.56.111" //the master actively tries to connect to the client
- log_duration = 0
- }
+object Endpoint "icinga2-client1.localdomain" {
+ host = "192.168.56.111" //the master actively tries to connect to the client
+ log_duration = 0
+}
- object Endpoint "icinga2-client2.localdomain" {
- host = "192.168.56.112" //the master actively tries to connect to the client
- log_duration = 0
- }
+object Endpoint "icinga2-client2.localdomain" {
+ host = "192.168.56.112" //the master actively tries to connect to the client
+ log_duration = 0
+}
+```
Configuration on the client `icinga2-client1.localdomain`:
- [root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
+```
+[root@icinga2-client1.localdomain /]# vim /etc/icinga2/zones.conf
- //...
+//...
- object Endpoint "icinga2-master1.localdomain" {
- //do not actively connect to the master by leaving out the 'host' attribute
- log_duration = 0
- }
+object Endpoint "icinga2-master1.localdomain" {
+ //do not actively connect to the master by leaving out the 'host' attribute
+ log_duration = 0
+}
- object Endpoint "icinga2-master2.localdomain" {
- //do not actively connect to the master by leaving out the 'host' attribute
- log_duration = 0
- }
+object Endpoint "icinga2-master2.localdomain" {
+ //do not actively connect to the master by leaving out the 'host' attribute
+ log_duration = 0
+}
+```
### Manual Certificate Creation <a id="distributed-monitoring-advanced-hints-certificates-manual"></a>
The first step is the creation of the certificate authority (CA) by running the following command
as root user:
- [root@icinga2-master1.localdomain /root]# icinga2 pki new-ca
+```
+[root@icinga2-master1.localdomain /root]# icinga2 pki new-ca
+```
#### Create CSR and Certificate <a id="distributed-monitoring-advanced-hints-certificates-manual-create"></a>
If you want to install the client silently/unattended, use the `/qn` modifier. The
installation should not trigger a restart, but if you want to be completely sure, you can use the `/norestart` modifier.
- C:> msiexec /i C:\Icinga2-v2.5.0-x86.msi /qn /norestart
+```
+C:> msiexec /i C:\Icinga2-v2.5.0-x86.msi /qn /norestart
+```
Once the setup is completed you can use the `node setup` cli command too.
In case you want to bind the `ApiListener` object to a specific
host/port you can specify it like this:
- --listen 192.68.56.101,5665
+```
+--listen 192.68.56.101,5665
+```
In case you don't need anything in `conf.d`, use the following command line:
Make sure that the `/var/lib/icinga2/certs` directory exists and is owned by the `icinga`
user (or the user Icinga 2 is running as).
- [root@icinga2-client1.localdomain /]# mkdir -p /var/lib/icinga2/certs
- [root@icinga2-client1.localdomain /]# chown -R icinga:icinga /var/lib/icinga2/certs
+```
+[root@icinga2-client1.localdomain /]# mkdir -p /var/lib/icinga2/certs
+[root@icinga2-client1.localdomain /]# chown -R icinga:icinga /var/lib/icinga2/certs
+```
First you'll need to generate a new local self-signed certificate.
Pass the following details to the `pki new-cert` CLI command:
Example:
- [root@icinga2-client1.localdomain /]# icinga2 pki new-cert --cn icinga2-client1.localdomain \
- --key /var/lib/icinga2/certs/icinga2-client1.localdomain.key \
- --cert /var/lib/icinga2/certs/icinga2-client1.localdomain.crt
+```
+[root@icinga2-client1.localdomain /]# icinga2 pki new-cert --cn icinga2-client1.localdomain \
+--key /var/lib/icinga2/certs/icinga2-client1.localdomain.key \
+--cert /var/lib/icinga2/certs/icinga2-client1.localdomain.crt
+```
Request the master certificate from the master host (`icinga2-master1.localdomain`)
and store it as `trusted-master.crt`. Review it and continue.
Example:
- [root@icinga2-client1.localdomain /]# icinga2 pki save-cert --key /var/lib/icinga2/certs/icinga2-client1.localdomain.key \
- --cert /var/lib/icinga2/certs/icinga2-client1.localdomain.crt \
- --trustedcert /var/lib/icinga2/certs/trusted-parent.crt \
- --host icinga2-master1.localdomain
+```
+[root@icinga2-client1.localdomain /]# icinga2 pki save-cert --key /var/lib/icinga2/certs/icinga2-client1.localdomain.key \
+--cert /var/lib/icinga2/certs/icinga2-client1.localdomain.crt \
+--trustedcert /var/lib/icinga2/certs/trusted-parent.crt \
+--host icinga2-master1.localdomain
+```
Continue with the additional node setup step. Specify a local endpoint and zone name (`icinga2-client1.localdomain`)
and set the master host (`icinga2-master1.localdomain`) as parent zone configuration. Specify the path to
In case the client should connect to the master node, you'll
need to modify the `--endpoint` parameter using the format `cn,host,port`:
- --endpoint icinga2-master1.localdomain,192.168.56.101,5665
+```
+--endpoint icinga2-master1.localdomain,192.168.56.101,5665
+```
Specify the parent zone using the `--parent_zone` parameter. This is useful
if the client connects to a satellite, not the master instance.
- --parent_zone satellite
+```
+--parent_zone satellite
+```
In case the client should know the additional global zone `linux-templates`, you'll
need to set the `--global-zones` parameter.
- --global_zones linux-templates
+```
+--global_zones linux-templates
+```
The `--parent-host` parameter is optional since v2.9 and allows you to perform a connection-less setup.
You cannot restart Icinga 2 yet, the CLI command asked to to manually copy the parent's public CA
If this client node is configured as [remote command endpoint execution](06-distributed-monitoring.md#distributed-monitoring-top-down-command-endpoint)
you can safely disable the `checker` feature. The `node setup` CLI command already disabled the `notification` feature.
- [root@icinga2-client1.localdomain /]# icinga2 feature disable checker
+```
+[root@icinga2-client1.localdomain /]# icinga2 feature disable checker
+```
Disable "conf.d" inclusion if this is a [top down](06-distributed-monitoring.md#distributed-monitoring-top-down)
configured client.
- [root@icinga2-client1.localdomain /]# sed -i 's/include_recursive "conf.d"/\/\/include_recursive "conf.d"/g' /etc/icinga2/icinga2.conf
+```
+[root@icinga2-client1.localdomain /]# sed -i 's/include_recursive "conf.d"/\/\/include_recursive "conf.d"/g' /etc/icinga2/icinga2.conf
+```
**Note**: This is the default since v2.9.
**Optional**: Add an ApiUser object configuration for remote troubleshooting.
- [root@icinga2-client1.localdomain /]# cat <<EOF >/etc/icinga2/conf.d/api-users.conf
- object ApiUser "root" {
- password = "clientsupersecretpassword"
- permissions = ["*"]
- }
- EOF
+```
+[root@icinga2-client1.localdomain /]# cat <<EOF >/etc/icinga2/conf.d/api-users.conf
+object ApiUser "root" {
+ password = "clientsupersecretpassword"
+ permissions = ["*"]
+}
+EOF
+```
In case you've previously disabled the "conf.d" directory only
add the file file `conf.d/api-users.conf`:
- [root@icinga2-client1.localdomain /]# echo 'include "conf.d/api-users.conf"' >> /etc/icinga2/icinga2.conf
+```
+[root@icinga2-client1.localdomain /]# echo 'include "conf.d/api-users.conf"' >> /etc/icinga2/icinga2.conf
+```
Finally restart Icinga 2.
- [root@icinga2-client1.localdomain /]# systemctl restart icinga2
+```
+[root@icinga2-client1.localdomain /]# systemctl restart icinga2
+```
Your automation tool must then configure master node in the meantime.
- # cat <<EOF >>/etc/icinga2/zones.conf
- object Endpoint "icinga2-client1.localdomain" {
- //client connects itself
- }
+```
+# cat <<EOF >>/etc/icinga2/zones.conf
+object Endpoint "icinga2-client1.localdomain" {
+ //client connects itself
+}
- object Zone "icinga2-client1.localdomain" {
- endpoints = [ "icinga2-client1.localdomain" ]
- parent = "master"
- }
+object Zone "icinga2-client1.localdomain" {
+ endpoints = [ "icinga2-client1.localdomain" ]
+ parent = "master"
+}
- EOF
+EOF
+```
## Using Multiple Environments <a id="distributed-monitoring-environments"></a>
overrides the `snmp_oid` custom attribute. A service is created for all hosts which
have the `snmp-community` custom attribute.
- apply Service "uptime" {
- import "generic-service"
+```
+apply Service "uptime" {
+ import "generic-service"
- check_command = "snmp"
- vars.snmp_oid = "1.3.6.1.2.1.1.3.0"
- vars.snmp_miblist = "DISMAN-EVENT-MIB"
+ check_command = "snmp"
+ vars.snmp_oid = "1.3.6.1.2.1.1.3.0"
+ vars.snmp_miblist = "DISMAN-EVENT-MIB"
- assign where host.vars.snmp_community != ""
- }
+ assign where host.vars.snmp_community != ""
+}
+```
Additional SNMP plugins are available using the [Manubulon SNMP Plugins](10-icinga-template-library.md#snmp-manubulon-plugin-check-commands).
its return code and output. The `by_ssh` command object is part of the built-in templates and
requires the `check_by_ssh` check plugin which is available in the [Monitoring Plugins package](02-getting-started.md#setting-up-check-plugins).
- object CheckCommand "by_ssh_swap" {
- import "by_ssh"
+```
+object CheckCommand "by_ssh_swap" {
+ import "by_ssh"
- vars.by_ssh_command = "/usr/lib/nagios/plugins/check_swap -w $by_ssh_swap_warn$ -c $by_ssh_swap_crit$"
- vars.by_ssh_swap_warn = "75%"
- vars.by_ssh_swap_crit = "50%"
- }
+ vars.by_ssh_command = "/usr/lib/nagios/plugins/check_swap -w $by_ssh_swap_warn$ -c $by_ssh_swap_crit$"
+ vars.by_ssh_swap_warn = "75%"
+ vars.by_ssh_swap_crit = "50%"
+}
- object Service "swap" {
- import "generic-service"
+object Service "swap" {
+ import "generic-service"
- host_name = "remote-ssh-host"
+ host_name = "remote-ssh-host"
- check_command = "by_ssh_swap"
+ check_command = "by_ssh_swap"
- vars.by_ssh_logname = "icinga"
- }
+ vars.by_ssh_logname = "icinga"
+}
+```
## NSClient++ <a id="agent-based-checks-nsclient"></a>
Example:
- object Service "disk" {
- import "generic-service"
+```
+object Service "disk" {
+ import "generic-service"
- host_name = "remote-windows-host"
+ host_name = "remote-windows-host"
- check_command = "nscp"
+ check_command = "nscp"
- vars.nscp_variable = "USEDDISKSPACE"
- vars.nscp_params = "c"
- vars.nscp_warn = 70
- vars.nscp_crit = 80
- }
+ vars.nscp_variable = "USEDDISKSPACE"
+ vars.nscp_params = "c"
+ vars.nscp_warn = 70
+ vars.nscp_crit = 80
+}
+```
For details on the `NSClient++` configuration please refer to the [official documentation](https://docs.nsclient.org/).
Example:
- object Service "users" {
- import "generic-service"
+```
+object Service "users" {
+ import "generic-service"
- host_name = "remote-nrpe-host"
+ host_name = "remote-nrpe-host"
- check_command = "nrpe"
- vars.nrpe_command = "check_users"
- }
+ check_command = "nrpe"
+ vars.nrpe_command = "check_users"
+}
+```
nrpe.cfg:
- command[check_users]=/usr/local/icinga/libexec/check_users -w 5 -c 10
+```
+command[check_users]=/usr/local/icinga/libexec/check_users -w 5 -c 10
+```
If you are planning to pass arguments to NRPE using the `-a`
command line parameter, make sure that your NRPE daemon has them
Example:
- object Service "nrpe-disk-/" {
- import "generic-service"
+```
+object Service "nrpe-disk-/" {
+ import "generic-service"
- host_name = "remote-nrpe-host"
+ host_name = "remote-nrpe-host"
- check_command = "nrpe"
- vars.nrpe_command = "check_disk"
- vars.nrpe_arguments = [ "20%", "10%", "/" ]
- }
+ check_command = "nrpe"
+ vars.nrpe_command = "check_disk"
+ vars.nrpe_arguments = [ "20%", "10%", "/" ]
+}
+```
Icinga 2 will execute the nrpe plugin like this:
- /usr/lib/nagios/plugins/check_nrpe -H <remote-nrpe-host> -c 'check_disk' -a '20%' '10%' '/'
+```
+/usr/lib/nagios/plugins/check_nrpe -H <remote-nrpe-host> -c 'check_disk' -a '20%' '10%' '/'
+```
NRPE expects all additional arguments in an ordered fashion
and interprets the first value as `$ARG1$` macro, the second
nrpe.cfg:
- command[check_disk]=/usr/local/icinga/libexec/check_disk -w $ARG1$ -c $ARG2$ -p $ARG3$
+```
+command[check_disk]=/usr/local/icinga/libexec/check_disk -w $ARG1$ -c $ARG2$ -p $ARG3$
+```
Using the above example with `nrpe_arguments` the command
executed by the NRPE daemon looks similar to that:
- /usr/local/icinga/libexec/check_disk -w 20% -c 10% -p /
+```
+/usr/local/icinga/libexec/check_disk -w 20% -c 10% -p /
+```
You can pass arguments in a similar manner to [NSClient++](07-agent-based-monitoring.md#agent-based-checks-nsclient)
when using its NRPE supported check method.
Add a directive in `snmptt.conf`
- EVENT coldStart .1.3.6.1.6.3.1.1.5.1 "Status Events" Normal
- FORMAT Device reinitialized (coldStart)
- EXEC echo "[$@] PROCESS_SERVICE_CHECK_RESULT;$A;Coldstart;2;The snmp agent has reinitialized." >> /var/run/icinga2/cmd/icinga2.cmd
- SDESC
- A coldStart trap signifies that the SNMPv2 entity, acting
- in an agent role, is reinitializing itself and that its
- configuration may have been altered.
- EDESC
+```
+EVENT coldStart .1.3.6.1.6.3.1.1.5.1 "Status Events" Normal
+FORMAT Device reinitialized (coldStart)
+EXEC echo "[$@] PROCESS_SERVICE_CHECK_RESULT;$A;Coldstart;2;The snmp agent has reinitialized." >> /var/run/icinga2/cmd/icinga2.cmd
+SDESC
+A coldStart trap signifies that the SNMPv2 entity, acting
+in an agent role, is reinitializing itself and that its
+configuration may have been altered.
+EDESC
+```
1. Define the `EVENT` as per your need.
2. Construct the `EXEC` statement with the service name matching your template
Add an `EventCommand` configuration object for the passive service auto reset event.
- object EventCommand "coldstart-reset-event" {
- command = [ ConfigDir + "/conf.d/custom/scripts/coldstart_reset_event.sh" ]
+```
+object EventCommand "coldstart-reset-event" {
+ command = [ ConfigDir + "/conf.d/custom/scripts/coldstart_reset_event.sh" ]
- arguments = {
- "-i" = "$service.state_id$"
- "-n" = "$host.name$"
- "-s" = "$service.name$"
- }
- }
+ arguments = {
+ "-i" = "$service.state_id$"
+ "-n" = "$host.name$"
+ "-s" = "$service.name$"
+ }
+}
+```
Create the `coldstart_reset_event.sh` shell script to pass the expanded variable
data in. The `$service.state_id$` is important in order to prevent an endless loop
of event firing after the service has been reset.
- #!/bin/bash
-
- SERVICE_STATE_ID=""
- HOST_NAME=""
- SERVICE_NAME=""
-
- show_help()
- {
- cat <<-EOF
- Usage: ${0##*/} [-h] -n HOST_NAME -s SERVICE_NAME
- Writes a coldstart reset event to the Icinga command pipe.
-
- -h Display this help and exit.
- -i SERVICE_STATE_ID The associated service state id.
- -n HOST_NAME The associated host name.
- -s SERVICE_NAME The associated service name.
- EOF
- }
-
- while getopts "hi:n:s:" opt; do
- case "$opt" in
- h)
- show_help
- exit 0
- ;;
- i)
- SERVICE_STATE_ID=$OPTARG
- ;;
- n)
- HOST_NAME=$OPTARG
- ;;
- s)
- SERVICE_NAME=$OPTARG
- ;;
- '?')
- show_help
- exit 0
- ;;
- esac
- done
-
- if [ -z "$SERVICE_STATE_ID" ]; then
- show_help
- printf "\n Error: -i required.\n"
- exit 1
- fi
-
- if [ -z "$HOST_NAME" ]; then
- show_help
- printf "\n Error: -n required.\n"
- exit 1
- fi
-
- if [ -z "$SERVICE_NAME" ]; then
- show_help
- printf "\n Error: -s required.\n"
- exit 1
- fi
-
- if [ "$SERVICE_STATE_ID" -gt 0 ]; then
- echo "[`date +%s`] PROCESS_SERVICE_CHECK_RESULT;$HOST_NAME;$SERVICE_NAME;0;Auto-reset (`date +"%m-%d-%Y %T"`)." >> /var/run/icinga2/cmd/icinga2.cmd
- fi
+```
+#!/bin/bash
+
+SERVICE_STATE_ID=""
+HOST_NAME=""
+SERVICE_NAME=""
+
+show_help()
+{
+cat <<-EOF
+ Usage: ${0##*/} [-h] -n HOST_NAME -s SERVICE_NAME
+ Writes a coldstart reset event to the Icinga command pipe.
+
+ -h Display this help and exit.
+ -i SERVICE_STATE_ID The associated service state id.
+ -n HOST_NAME The associated host name.
+ -s SERVICE_NAME The associated service name.
+EOF
+}
+
+while getopts "hi:n:s:" opt; do
+ case "$opt" in
+ h)
+ show_help
+ exit 0
+ ;;
+ i)
+ SERVICE_STATE_ID=$OPTARG
+ ;;
+ n)
+ HOST_NAME=$OPTARG
+ ;;
+ s)
+ SERVICE_NAME=$OPTARG
+ ;;
+ '?')
+ show_help
+ exit 0
+ ;;
+ esac
+done
+
+if [ -z "$SERVICE_STATE_ID" ]; then
+ show_help
+ printf "\n Error: -i required.\n"
+ exit 1
+fi
+
+if [ -z "$HOST_NAME" ]; then
+ show_help
+ printf "\n Error: -n required.\n"
+ exit 1
+fi
+
+if [ -z "$SERVICE_NAME" ]; then
+ show_help
+ printf "\n Error: -s required.\n"
+ exit 1
+fi
+
+if [ "$SERVICE_STATE_ID" -gt 0 ]; then
+ echo "[`date +%s`] PROCESS_SERVICE_CHECK_RESULT;$HOST_NAME;$SERVICE_NAME;0;Auto-reset (`date +"%m-%d-%Y %T"`)." >> /var/run/icinga2/cmd/icinga2.cmd
+fi
+```
Finally create the `Service` and assign it:
- apply Service "Coldstart" {
- import "generic-service-custom"
+```
+apply Service "Coldstart" {
+ import "generic-service-custom"
- check_command = "dummy"
- event_command = "coldstart-reset-event"
+ check_command = "dummy"
+ event_command = "coldstart-reset-event"
- enable_notifications = 1
- enable_active_checks = 0
- enable_passive_checks = 1
- enable_flapping = 0
- volatile = 1
- enable_perfdata = 0
+ enable_notifications = 1
+ enable_active_checks = 0
+ enable_passive_checks = 1
+ enable_flapping = 0
+ volatile = 1
+ enable_perfdata = 0
- vars.dummy_state = 0
- vars.dummy_text = "Manual reset."
+ vars.dummy_state = 0
+ vars.dummy_text = "Manual reset."
- vars.sla = "24x7"
+ vars.sla = "24x7"
- assign where (host.vars.os == "Linux" || host.vars.os == "Windows")
- }
+ assign where (host.vars.os == "Linux" || host.vars.os == "Windows")
+}
+```
### Complex SNMP Traps <a id="complex-traps"></a>
Add a directive in `snmptt.conf`
- EVENT enterpriseSpecific <YOUR OID> "Status Events" Normal
- FORMAT Enterprise specific trap
- EXEC echo "[$@] PROCESS_SERVICE_CHECK_RESULT;$A;$1;$2;$3" >> /var/run/icinga2/cmd/icinga2.cmd
- SDESC
- An enterprise specific trap.
- The varbinds in order denote the Icinga service name, state and text.
- EDESC
+```
+EVENT enterpriseSpecific <YOUR OID> "Status Events" Normal
+FORMAT Enterprise specific trap
+EXEC echo "[$@] PROCESS_SERVICE_CHECK_RESULT;$A;$1;$2;$3" >> /var/run/icinga2/cmd/icinga2.cmd
+SDESC
+An enterprise specific trap.
+The varbinds in order denote the Icinga service name, state and text.
+EDESC
+```
1. Define the `EVENT` as per your need using your actual oid.
2. The service name, state and text are extracted from the first three varbinds.
matches and the first varbind value is `Backup`, SNMPTT will submit the corresponding
passive update with the state and text from the second and third varbind:
- object Service "Backup" {
- import "generic-service-custom"
-
- host_name = "host.domain.com"
- check_command = "dummy"
-
- enable_notifications = 1
- enable_active_checks = 1
- enable_passive_checks = 1
- enable_flapping = 0
- volatile = 1
- max_check_attempts = 1
- check_interval = 87000
- enable_perfdata = 0
-
- vars.sla = "24x7"
- vars.dummy_state = 2
- vars.dummy_text = "No passive check result received."
- }
+```
+object Service "Backup" {
+ import "generic-service-custom"
+
+ host_name = "host.domain.com"
+ check_command = "dummy"
+
+ enable_notifications = 1
+ enable_active_checks = 1
+ enable_passive_checks = 1
+ enable_flapping = 0
+ volatile = 1
+ max_check_attempts = 1
+ check_interval = 87000
+ enable_perfdata = 0
+
+ vars.sla = "24x7"
+ vars.dummy_state = 2
+ vars.dummy_text = "No passive check result received."
+}
+```
\ No newline at end of file
The threshold is calculated based on the last check execution time for actively executed checks:
- (last check execution time + check interval) > current time
+```
+(last check execution time + check interval) > current time
+```
If this host/service receives check results from an [external source](08-advanced-topics.md#external-check-results),
the threshold is based on the last time a check result was received:
- (last check result time + check interval) > current time
+```
+(last check result time + check interval) > current time
+```
> **Tip**
>
Host definition:
- object Host "webserver01" {
- import "generic-host"
- address = "192.168.56.200"
- vars.os = "Linux"
-
- vars.webserver = {
- instance["status"] = {
- address = "192.168.56.201"
- port = "80"
- url = "/status"
- }
- instance["tomcat"] = {
- address = "192.168.56.202"
- port = "8080"
- }
- instance["icingaweb2"] = {
- address = "192.168.56.210"
- port = "443"
- url = "/icingaweb2"
- ssl = true
- }
- }
+```
+object Host "webserver01" {
+ import "generic-host"
+ address = "192.168.56.200"
+ vars.os = "Linux"
+
+ vars.webserver = {
+ instance["status"] = {
+ address = "192.168.56.201"
+ port = "80"
+ url = "/status"
}
+ instance["tomcat"] = {
+ address = "192.168.56.202"
+ port = "8080"
+ }
+ instance["icingaweb2"] = {
+ address = "192.168.56.210"
+ port = "443"
+ url = "/icingaweb2"
+ ssl = true
+ }
+ }
+}
+```
Service apply for definitions:
- apply Service "webserver_ping" for (instance => config in host.vars.webserver.instance) {
- display_name = "webserver_" + instance
- check_command = "ping4"
+```
+apply Service "webserver_ping" for (instance => config in host.vars.webserver.instance) {
+ display_name = "webserver_" + instance
+ check_command = "ping4"
- vars.ping_address = config.address
+ vars.ping_address = config.address
- assign where host.vars.webserver.instance
- }
+ assign where host.vars.webserver.instance
+}
- apply Service "webserver_port" for (instance => config in host.vars.webserver.instance) {
- display_name = "webserver_" + instance + "_" + config.port
- check_command = "tcp"
+apply Service "webserver_port" for (instance => config in host.vars.webserver.instance) {
+ display_name = "webserver_" + instance + "_" + config.port
+ check_command = "tcp"
- vars.tcp_address = config.address
- vars.tcp_port = config.port
+ vars.tcp_address = config.address
+ vars.tcp_port = config.port
- assign where host.vars.webserver.instance
- }
+ assign where host.vars.webserver.instance
+}
- apply Service "webserver_url" for (instance => config in host.vars.webserver.instance) {
- display_name = "webserver_" + instance + "_" + config.url
- check_command = "http"
+apply Service "webserver_url" for (instance => config in host.vars.webserver.instance) {
+ display_name = "webserver_" + instance + "_" + config.url
+ check_command = "http"
- vars.http_address = config.address
- vars.http_port = config.port
- vars.http_uri = config.url
+ vars.http_address = config.address
+ vars.http_port = config.port
+ vars.http_uri = config.url
- if (config.ssl) {
- vars.http_ssl = config.ssl
- }
+ if (config.ssl) {
+ vars.http_ssl = config.ssl
+ }
- assign where config.url != ""
- }
+ assign where config.url != ""
+}
+```
The variables defined in the host dictionary are not using the typical custom attribute
prefix recommended for CheckCommand parameters. Instead they are re-used for multiple
depending on group membership. All hosts in the `slow-lan` host group use 300
as value for `ping_wrta`, all other hosts use 100.
- globals.group_specific_value = function(group, group_value, non_group_value) {
- return function() use (group, group_value, non_group_value) {
- if (group in host.groups) {
- return group_value
- } else {
- return non_group_value
- }
+```
+globals.group_specific_value = function(group, group_value, non_group_value) {
+ return function() use (group, group_value, non_group_value) {
+ if (group in host.groups) {
+ return group_value
+ } else {
+ return non_group_value
}
}
+}
- apply Service "ping4" {
- import "generic-service"
- check_command = "ping4"
+apply Service "ping4" {
+ import "generic-service"
+ check_command = "ping4"
- vars.ping_wrta = group_specific_value("slow-lan", 300, 100)
- vars.ping_crta = group_specific_value("slow-lan", 500, 200)
+ vars.ping_wrta = group_specific_value("slow-lan", 300, 100)
+ vars.ping_crta = group_specific_value("slow-lan", 500, 200)
- assign where true
- }
+ assign where true
+}
+```
#### Use Functions in Assign Where Expressions <a id="use-functions-assign-where"></a>
to the host group `printers-lexmark` but only if the host uses
a template matching the name `lexmark*`.
- template Host "lexmark-printer-host" {
- vars.printer_type = "Lexmark"
- }
-
- object Host "myprinter" {
- import "generic-host"
- import "lexmark-printer-host"
+```
+template Host "lexmark-printer-host" {
+ vars.printer_type = "Lexmark"
+}
- address = "192.168.1.1"
- }
+object Host "myprinter" {
+ import "generic-host"
+ import "lexmark-printer-host"
- /* register a global function for the assign where call */
- globals.check_host_templates = function(host, search) {
- /* iterate over all host templates and check if the search matches */
- for (tmpl in host.templates) {
- if (match(search, tmpl)) {
- return true
- }
- }
+ address = "192.168.1.1"
+}
- /* nothing matched */
- return false
+/* register a global function for the assign where call */
+globals.check_host_templates = function(host, search) {
+ /* iterate over all host templates and check if the search matches */
+ for (tmpl in host.templates) {
+ if (match(search, tmpl)) {
+ return true
}
+ }
- object HostGroup "printers-lexmark" {
- display_name = "Lexmark Printers"
- /* call the global function and pass the arguments */
- assign where check_host_templates(host, "lexmark*")
- }
+ /* nothing matched */
+ return false
+}
+object HostGroup "printers-lexmark" {
+ display_name = "Lexmark Printers"
+ /* call the global function and pass the arguments */
+ assign where check_host_templates(host, "lexmark*")
+}
+```
Take a different more complex example: All hosts with the
custom attribute `vars_app` as nested dictionary should be
It could read as wildcard match for nested dictionaries:
+```
where host.vars.vars_app["*"].app_type == "ABAP"
+```
The solution for this problem is to register a global
function which checks the `app_type` for all hosts
with the `vars_app` dictionary.
- object Host "appserver01" {
- check_command = "dummy"
- vars.vars_app["ABC"] = { app_type = "ABAP" }
- }
- object Host "appserver02" {
- check_command = "dummy"
- vars.vars_app["DEF"] = { app_type = "ABAP" }
- }
-
- globals.check_app_type = function(host, type) {
- /* ensure that other hosts without the custom attribute do not match */
- if (typeof(host.vars.vars_app) != Dictionary) {
- return false
- }
+```
+object Host "appserver01" {
+ check_command = "dummy"
+ vars.vars_app["ABC"] = { app_type = "ABAP" }
+}
+object Host "appserver02" {
+ check_command = "dummy"
+ vars.vars_app["DEF"] = { app_type = "ABAP" }
+}
- /* iterate over the vars_app dictionary */
- for (key => val in host.vars.vars_app) {
- /* if the value is a dictionary and if contains the app_type being the requested type */
- if (typeof(val) == Dictionary && val.app_type == type) {
- return true
- }
- }
+globals.check_app_type = function(host, type) {
+ /* ensure that other hosts without the custom attribute do not match */
+ if (typeof(host.vars.vars_app) != Dictionary) {
+ return false
+ }
- /* nothing matched */
- return false
+ /* iterate over the vars_app dictionary */
+ for (key => val in host.vars.vars_app) {
+ /* if the value is a dictionary and if contains the app_type being the requested type */
+ if (typeof(val) == Dictionary && val.app_type == type) {
+ return true
}
+ }
- object HostGroup "ABAP-app-server" {
- assign where check_app_type(host, "ABAP")
- }
+ /* nothing matched */
+ return false
+}
+object HostGroup "ABAP-app-server" {
+ assign where check_app_type(host, "ABAP")
+}
+```
#### Use Functions in Command Arguments set_if <a id="use-functions-command-arguments-setif"></a>
The following example was found on the community support channels. The user had defined a host
dictionary named `compellent` with the key `disks`. This was then used inside service apply for rules.
- object Host "dict-host" {
- check_command = "check_compellent"
- vars.compellent["disks"] = {
- file = "/var/lib/check_compellent/san_disks.0.json",
- checks = ["disks"]
- }
- }
+```
+object Host "dict-host" {
+ check_command = "check_compellent"
+ vars.compellent["disks"] = {
+ file = "/var/lib/check_compellent/san_disks.0.json",
+ checks = ["disks"]
+ }
+}
+```
The more significant problem was to only add the command parameter `--disk` to the plugin call
when the dictionary `compellent` contains the key `disks`, and omit it if not found.
and evaluating the host custom attribute `compellent` containing the `disks` this problem was
solved like this:
- object CheckCommand "check_compellent" {
- command = [ "/usr/bin/check_compellent" ]
- arguments = {
- "--disks" = {
- set_if = {{
- var host_vars = host.vars
- log(host_vars)
- var compel = host_vars.compellent
- log(compel)
- compel.contains("disks")
- }}
- }
- }
+```
+object CheckCommand "check_compellent" {
+ command = [ "/usr/bin/check_compellent" ]
+ arguments = {
+ "--disks" = {
+ set_if = {{
+ var host_vars = host.vars
+ log(host_vars)
+ var compel = host_vars.compellent
+ log(compel)
+ compel.contains("disks")
+ }}
}
+ }
+}
+```
This implementation uses the dictionary type method [contains](18-library-reference.md#dictionary-contains)
and will fail if `host.vars.compellent` is not of the type `Dictionary`.
You can test the types using the `icinga2 console`:
- # icinga2 console
- Icinga (version: v2.3.0-193-g3eb55ad)
- <1> => srv_vars.compellent["check_a"] = { file="outfile_a.json", checks = [ "disks", "fans" ] }
- null
- <2> => srv_vars.compellent["check_b"] = { file="outfile_b.json", checks = [ "power", "voltages" ] }
- null
- <3> => typeof(srv_vars.compellent)
- type 'Dictionary'
- <4> =>
+```
+# icinga2 console
+Icinga (version: v2.3.0-193-g3eb55ad)
+<1> => srv_vars.compellent["check_a"] = { file="outfile_a.json", checks = [ "disks", "fans" ] }
+null
+<2> => srv_vars.compellent["check_b"] = { file="outfile_b.json", checks = [ "power", "voltages" ] }
+null
+<3> => typeof(srv_vars.compellent)
+type 'Dictionary'
+<4> =>
+```
The more programmatic approach for `set_if` could look like this:
- "--disks" = {
- set_if = {{
- var srv_vars = service.vars
- if(len(srv_vars) > 0) {
- if (typeof(srv_vars.compellent) == Dictionary) {
- return srv_vars.compellent.contains("disks")
- } else {
- log(LogInformationen, "checkcommand set_if", "custom attribute compellent_checks is not a dictionary, ignoring it.")
- return false
- }
- } else {
- log(LogWarning, "checkcommand set_if", "empty custom attributes")
- return false
- }
- }}
+```
+ "--disks" = {
+ set_if = {{
+ var srv_vars = service.vars
+ if(len(srv_vars) > 0) {
+ if (typeof(srv_vars.compellent) == Dictionary) {
+ return srv_vars.compellent.contains("disks")
+ } else {
+ log(LogInformationen, "checkcommand set_if", "custom attribute compellent_checks is not a dictionary, ignoring it.")
+ return false
+ }
+ } else {
+ log(LogWarning, "checkcommand set_if", "empty custom attributes")
+ return false
}
-
+ }}
+ }
+```
#### Use Functions as Command Attribute <a id="use-functions-command-attribute"></a>
specify a custom attribute inside the notification apply rule and decide which notification
script to call based on that.
- object User "short-dummy" {
- }
+```
+object User "short-dummy" {
+}
- object UserGroup "short-dummy-group" {
- assign where user.name == "short-dummy"
- }
+object UserGroup "short-dummy-group" {
+ assign where user.name == "short-dummy"
+}
- apply Notification "mail-admins-short" to Host {
- import "mail-host-notification"
- command = "mail-host-notification-test"
- user_groups = [ "short-dummy-group" ]
- vars.short = true
- assign where host.vars.notification.mail
- }
+apply Notification "mail-admins-short" to Host {
+ import "mail-host-notification"
+ command = "mail-host-notification-test"
+ user_groups = [ "short-dummy-group" ]
+ vars.short = true
+ assign where host.vars.notification.mail
+}
+```
The solution is fairly simple: The `command` attribute is implemented as function returning
an array required by the caller Icinga 2.
You can omit the `log()` calls, they only help debugging.
- object NotificationCommand "mail-host-notification-test" {
- command = {{
- log("command as function")
- var mailscript = "mail-host-notification-long.sh"
- if (notification.vars.short) {
- mailscript = "mail-host-notification-short.sh"
- }
- log("Running command")
- log(mailscript)
-
- var cmd = [ ConfigDir + "/scripts/" + mailscript ]
- log(LogCritical, "me", cmd)
- return cmd
- }}
-
- env = {
- }
+```
+object NotificationCommand "mail-host-notification-test" {
+ command = {{
+ log("command as function")
+ var mailscript = "mail-host-notification-long.sh"
+ if (notification.vars.short) {
+ mailscript = "mail-host-notification-short.sh"
}
+ log("Running command")
+ log(mailscript)
+
+ var cmd = [ ConfigDir + "/scripts/" + mailscript ]
+ log(LogCritical, "me", cmd)
+ return cmd
+ }}
+ env = {
+ }
+}
+```
### Access Object Attributes at Runtime <a id="access-object-attributes-at-runtime"></a>
Available state filters:
- OK
- Warning
- Critical
- Unknown
- Up
- Down
+```
+OK
+Warning
+Critical
+Unknown
+Up
+Down
+```
When using [apply rules](03-monitoring-basics.md#using-apply) for dependencies, you can leave out certain attributes which will be
automatically determined by Icinga 2.
Available notification state filters for Service:
- OK
- Warning
- Critical
- Unknown
+```
+OK
+Warning
+Critical
+Unknown
+```
Available notification state filters for Host:
- Up
- Down
+```
+Up
+Down
+```
Available notification type filters:
- DowntimeStart
- DowntimeEnd
- DowntimeRemoved
- Custom
- Acknowledgement
- Problem
- Recovery
- FlappingStart
- FlappingEnd
+```
+DowntimeStart
+DowntimeEnd
+DowntimeRemoved
+Custom
+Acknowledgement
+Problem
+Recovery
+FlappingStart
+FlappingEnd
+```
Runtime Attributes:
Available notification state filters:
- OK
- Warning
- Critical
- Unknown
- Up
- Down
+```
+OK
+Warning
+Critical
+Unknown
+Up
+Down
+```
Available notification type filters:
- DowntimeStart
- DowntimeEnd
- DowntimeRemoved
- Custom
- Acknowledgement
- Problem
- Recovery
- FlappingStart
- FlappingEnd
+```
+DowntimeStart
+DowntimeEnd
+DowntimeRemoved
+Custom
+Acknowledgement
+Problem
+Recovery
+FlappingStart
+FlappingEnd
+```
Configuration Attributes:
By default the generic templates are included in the [icinga2.conf](04-configuring-icinga-2.md#icinga2-conf) configuration file:
- include <itl>
+```
+include <itl>
+```
These templates are imported by the provided example configuration.
certificates as well as a new API user `root` with an auto-generated password in the
`/etc/icinga2/conf.d/api-users.conf` configuration file:
- # icinga2 api setup
+```
+# icinga2 api setup
+```
Make sure to restart Icinga 2 to enable the changes you just made:
- # service icinga2 restart
+```
+# service icinga2 restart
+```
If you prefer to set up the API manually, you will have to perform the following steps:
All requests apart from `GET` require that the following `Accept` header is set:
- Accept: application/json
+```
+Accept: application/json
+```
Each URL is prefixed with the API version (currently "/v1").
The output will be sent back as a JSON object:
-
- {
- "results": [
- {
- "code": 200.0,
- "status": "Object was created."
- }
- ]
- }
+```
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Object was created."
+ }
+ ]
+}
+```
> **Tip**
>
configuration object. In this example `root` will be the basic auth username
and the `password` attribute contains the basic auth password.
- # vim /etc/icinga2/conf.d/api-users.conf
+```
+# vim /etc/icinga2/conf.d/api-users.conf
- object ApiUser "root" {
- password = "icinga"
- }
+object ApiUser "root" {
+ password = "icinga"
+}
+```
Alternatively you can use X.509 client certificates by specifying the `client_cn`
the API should trust. The X.509 certificate has to be signed by the CA certificate
that is configured in the [ApiListener](09-object-types.md#objecttype-apilistener) object.
- # vim /etc/icinga2/conf.d/api-users.conf
+```
+# vim /etc/icinga2/conf.d/api-users.conf
- object ApiUser "root" {
- client_cn = "CertificateCommonName"
- }
+object ApiUser "root" {
+ client_cn = "CertificateCommonName"
+}
+```
An `ApiUser` object can have both authentication methods configured.
You can test authentication by sending a GET request to the API:
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1'
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1'
+```
In case you get an error message make sure to check the API user credentials.
When using client certificates for authentication you'll need to pass your client certificate
and private key to the curl call:
- $ curl -k --cert example.localdomain.crt --key example.localdomain.key 'https://example.localdomain:5665/v1/status'
+```
+$ curl -k --cert example.localdomain.crt --key example.localdomain.key 'https://example.localdomain:5665/v1/status'
+```
In case of an error make sure to verify the client certificate and CA.
only be used for testing. In order to securely check each connection you'll need to
specify the trusted CA certificate using the curl parameter`--cacert`:
- $ curl -u root:icinga --cacert ca.crt 'icinga2.node1.localdomain:5665/v1'
+```
+$ curl -u root:icinga --cacert ca.crt 'icinga2.node1.localdomain:5665/v1'
+```
Read the next chapter on [API permissions](12-icinga2-api.md#icinga2-api-permissions)
in order to configure authorization settings for your newly created API user.
Example for an API user with all permissions:
- permissions = [ "*" ]
+```
+permissions = [ "*" ]
+```
Note that you can use wildcards to include all possible hierarchically lower items. Here's another example that only allows the user
to perform read-only object queries for hosts and services:
- permissions = [ "objects/query/Host", "objects/query/Service" ]
+```
+permissions = [ "objects/query/Host", "objects/query/Service" ]
+```
You can also further restrict permissions by specifying a filter expression. The
filter expression has to be a [lambda function](17-language-reference.md#nullary-lambdas)
custom attribute `os` that matches the regular expression `^Linux`.
The [regex function](18-library-reference.md#global-functions-regex) is available as global function.
- permissions = [
- {
- permission = "objects/query/Host"
- filter = {{ regex("^Linux", host.vars.os) }}
- },
- {
- permission = "objects/query/Service"
- filter = {{ regex("^Linux", service.vars.os) }}
- }
- ]
+```
+permissions = [
+ {
+ permission = "objects/query/Host"
+ filter = {{ regex("^Linux", host.vars.os) }}
+ },
+ {
+ permission = "objects/query/Service"
+ filter = {{ regex("^Linux", service.vars.os) }}
+ }
+]
+```
More information about filters can be found in the [filters](12-icinga2-api.md#icinga2-api-filters) chapter.
Example for a URL-encoded query string:
- /v1/objects/hosts?filter=match(%22example.localdomain*%22,host.name)&attrs=name&attrs=state
+```
+/v1/objects/hosts?filter=match(%22example.localdomain*%22,host.name)&attrs=name&attrs=state
+```
Here are the exact same query parameters as a JSON object:
- { "filter": "match(\"example.localdomain*\",host.name)", "attrs": [ "host.name", "host.state" ] }
+```
+{ "filter": "match(\"example.localdomain*\",host.name)", "attrs": [ "host.name", "host.state" ] }
+```
The [match function](18-library-reference.md#global-functions-match) is available as global function
in Icinga 2.
Query an existing object by sending a `POST` request with `X-HTTP-Method-Override: GET` as request header:
- $ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -X POST -H 'X-HTTP-Method-Override: GET' 'https://localhost:5665/v1/objects/hosts'
+```
+$ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -X POST -H 'X-HTTP-Method-Override: GET' 'https://localhost:5665/v1/objects/hosts'
+```
Delete an existing object by sending a `POST` request with `X-HTTP-Method-Override: DELETE` as request header:
- $ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -X POST -H 'X-HTTP-Method-Override: DELETE' 'https://localhost:5665/v1/objects/hosts/example.localdomain'
+```
+$ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -X POST -H 'X-HTTP-Method-Override: DELETE' 'https://localhost:5665/v1/objects/hosts/example.localdomain'
+```
### Filters <a id="icinga2-api-filters"></a>
By default actions and queries operate on all objects unless further restricted by the user. For
example, the following query returns all `Host` objects:
- https://localhost:5665/v1/objects/hosts
+```
+https://localhost:5665/v1/objects/hosts
+```
If you're only interested in a single object, you can limit the output to that object by specifying its name:
- https://localhost:5665/v1/objects/hosts?host=localhost
+```
+https://localhost:5665/v1/objects/hosts?host=localhost
+```
**The name of the URL parameter is the lower-case version of the type the query applies to.** For
example, for `Host` objects the URL parameter therefore is `host`, for `Service` objects it is
You can also specify multiple objects:
- https://localhost:5665/v1/objects/hosts?hosts=first-host&hosts=second-host
+```
+https://localhost:5665/v1/objects/hosts?hosts=first-host&hosts=second-host
+```
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.
When specifying names for objects which have composite names like for example services the
full name has to be used:
- https://localhost:5665/v1/objects/services?service=localhost!ping6
+```
+https://localhost:5665/v1/objects/services?service=localhost!ping6
+```
The full name of an object can be obtained by looking at the `__name` attribute.
Example matching all services in NOT-OK state:
- https://localhost:5665/v1/objects/services?filter=service.state!=ServiceOK
+```
+https://localhost:5665/v1/objects/services?filter=service.state!=ServiceOK
+```
Example [matching](18-library-reference.md#global-functions-match) all hosts by a name string pattern:
- https://localhost:5665/v1/objects/hosts?filter=match("example.localdomain*",host.name)
+```
+https://localhost:5665/v1/objects/hosts?filter=match("example.localdomain*",host.name)
+```
Example for all hosts which are in the host group `linux-servers`:
-
- https://localhost:5665/v1/objects/hosts?filter="linux-servers" in host.groups
+```
+https://localhost:5665/v1/objects/hosts?filter="linux-servers" in host.groups
+```
User-specified filters are run in a sandbox environment which ensures that filters cannot
modify Icinga's state, for example object attributes or global variables.
action which can be used for both hosts and services. When using advanced filters you will also have to specify the
type using the `type` parameter:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \
- -d '{ "type": "Service", "filter": "service.name==\"ping6\"", "pretty": true }'
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \
+-d '{ "type": "Service", "filter": "service.name==\"ping6\"", "pretty": true }'
+```
When building filters you have to ensure that values such as
`"linux-servers"` are escaped properly according to the rules of the Icinga 2 configuration
variables which should be made available to your filter expression. This way you don't have
to worry about escaping values:
- $ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts' \
- -d '{ "filter": "host.vars.os == os", "filter_vars": { "os": "Linux" }, "pretty": true }'
+```
+$ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts' \
+-d '{ "filter": "host.vars.os == os", "filter_vars": { "os": "Linux" }, "pretty": true }'
+```
We're using [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override) here because
the HTTP specification does not allow message bodies for GET requests.
to be replaced with the plural name of the object type you are interested
in:
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts'
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts'
+```
A list of all available configuration types is available in the
[object types](09-object-types.md#object-types) chapter.
URL path when querying a single object. For objects with composite names
(e.g. services) the full name (e.g. `example.localdomain!http`) must be specified:
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/services/example.localdomain!http'
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/services/example.localdomain!http'
+```
You can limit the output to specific attributes using the `attrs` URL parameter:
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts/example.localdomain?attrs=name&attrs=address&pretty=1'
- {
- "results": [
- {
- "attrs": {
- "name": "example.localdomain"
- "address": "192.168.1.1"
- },
- "joins": {},
- "meta": {},
- "name": "example.localdomain",
- "type": "Host"
- }
- ]
- }
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts/example.localdomain?attrs=name&attrs=address&pretty=1'
+{
+ "results": [
+ {
+ "attrs": {
+ "name": "example.localdomain"
+ "address": "192.168.1.1"
+ },
+ "joins": {},
+ "meta": {},
+ "name": "example.localdomain",
+ "type": "Host"
+ }
+ ]
+}
+```
#### Object Queries Result <a id="icinga2-api-config-objects-query-result"></a>
The following query retrieves all host attributes:
- https://localhost:5665/v1/objects/services?joins=host
+```
+https://localhost:5665/v1/objects/services?joins=host
+```
Instead of requesting all host attributes you can also limit the output to specific
attributes:
- https://localhost:5665/v1/objects/services?joins=host.name&joins=host.address
+```
+https://localhost:5665/v1/objects/services?joins=host.name&joins=host.address
+```
You can request that all available joins are returned in the result set by using
the `all_joins` query parameter.
- https://localhost:5665/v1/objects/services?all_joins=1
+```
+https://localhost:5665/v1/objects/services?all_joins=1
+```
> **Note**
>
attributes for the service. The query also returns the host's `name` and `address` attribute
via a join:
- $ 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&pretty=1'
-
- {
- "results": [
- {
- "attrs": {
- "check_command": "ping4",
- "display_name": "ping4"
- },
- "joins": {
- "host": {
- "address": "192.168.1.1",
- "name": "example.localdomain"
- }
- },
- "meta": {},
- "name": "example.localdomain!ping4",
- "type": "Service"
+```
+$ 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&pretty=1'
+
+{
+ "results": [
+ {
+ "attrs": {
+ "check_command": "ping4",
+ "display_name": "ping4"
},
- {
- "attrs": {
- "check_command": "ssh",
- "display_name": "ssh"
- },
- "joins": {
- "host": {
- "address": "192.168.1.1",
- "name": "example.localdomain"
- }
- },
- "meta": {},
- "name": "example.localdomain!ssh",
- "type": "Service"
- }
- ]
- }
+ "joins": {
+ "host": {
+ "address": "192.168.1.1",
+ "name": "example.localdomain"
+ }
+ },
+ "meta": {},
+ "name": "example.localdomain!ping4",
+ "type": "Service"
+ },
+ {
+ "attrs": {
+ "check_command": "ssh",
+ "display_name": "ssh"
+ },
+ "joins": {
+ "host": {
+ "address": "192.168.1.1",
+ "name": "example.localdomain"
+ }
+ },
+ "meta": {},
+ "name": "example.localdomain!ssh",
+ "type": "Service"
+ }
+ ]
+}
+```
In case you want to fetch all [comments](09-object-types.md#objecttype-comment)
for hosts and services, you can use the following query URL (similar example
for downtimes):
- https://localhost:5665/v1/objects/comments?joins=host&joins=service
+```
+https://localhost:5665/v1/objects/comments?joins=host&joins=service
+```
This is another example for listing all service objects which are unhandled problems (state is not OK
and no downtime or acknowledgement set). We're using [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
here because we want to pass all query attributes in the request body.
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://127.0.0.1:5665/v1/objects/services' \
- -d '{ "joins": [ "host.name", "host.address" ], "attrs": [ "name", "state", "downtime_depth", "acknowledgement" ], "filter": "service.state != ServiceOK && service.downtime_depth == 0.0 && service.acknowledgement == 0.0", "pretty": true }'
-
- {
- "results": [
- {
- "attrs": {
- "acknowledgement": 0.0,
- "downtime_depth": 0.0,
- "name": "10807-service",
- "state": 3.0
- },
- "joins": {
- "host": {
- "address": "",
- "name": "10807-host"
- }
- },
- "meta": {},
- "name": "10807-host!10807-service",
- "type": "Service"
- }
- ]
- }
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://127.0.0.1:5665/v1/objects/services' \
+-d '{ "joins": [ "host.name", "host.address" ], "attrs": [ "name", "state", "downtime_depth", "acknowledgement" ], "filter": "service.state != ServiceOK && service.downtime_depth == 0.0 && service.acknowledgement == 0.0", "pretty": true }'
+
+{
+ "results": [
+ {
+ "attrs": {
+ "acknowledgement": 0.0,
+ "downtime_depth": 0.0,
+ "name": "10807-service",
+ "state": 3.0
+ },
+ "joins": {
+ "host": {
+ "address": "",
+ "name": "10807-host"
+ }
+ },
+ "meta": {},
+ "name": "10807-host!10807-service",
+ "type": "Service"
+ }
+ ]
+}
+```
In order to list all acknowledgements without expire time, you query the `/v1/objects/comments`
URL endpoint with `joins` and `filter` request parameters using the [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
method:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/comments' \
- -d '{ "joins": [ "service.name", "service.acknowledgement", "service.acknowledgement_expiry" ], "attrs": [ "author", "text" ], "filter": "service.acknowledgement!=0 && service.acknowledgement_expiry==0", "pretty": true }'
-
- {
- "results": [
- {
- "attrs": {
- "author": "icingaadmin",
- "text": "maintenance work"
- },
- "joins": {
- "service": {
- "__name": "example.localdomain!disk /",
- "acknowledgement": 1.0,
- "acknowledgement_expiry": 0.0
- }
- },
- "meta": {},
- "name": "example.localdomain!disk /!example.localdomain-1495457222-0",
- "type": "Comment"
- }
- ]
- }
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/comments' \
+-d '{ "joins": [ "service.name", "service.acknowledgement", "service.acknowledgement_expiry" ], "attrs": [ "author", "text" ], "filter": "service.acknowledgement!=0 && service.acknowledgement_expiry==0", "pretty": true }'
+
+{
+ "results": [
+ {
+ "attrs": {
+ "author": "icingaadmin",
+ "text": "maintenance work"
+ },
+ "joins": {
+ "service": {
+ "__name": "example.localdomain!disk /",
+ "acknowledgement": 1.0,
+ "acknowledgement_expiry": 0.0
+ }
+ },
+ "meta": {},
+ "name": "example.localdomain!disk /!example.localdomain-1495457222-0",
+ "type": "Comment"
+ }
+ ]
+}
+```
### Creating Config Objects <a id="icinga2-api-config-objects-create"></a>
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):
- "attrs": { "vars.os": "Linux" }
+```
+"attrs": { "vars.os": "Linux" }
+```
Example for creating the new host object `example.localdomain`:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
- -d '{ "templates": [ "generic-host" ], "attrs": { "address": "192.168.1.1", "check_command": "hostalive", "vars.os" : "Linux" }, "pretty": true }'
- {
- "results": [
- {
- "code": 200.0,
- "status": "Object was created."
- }
- ]
- }
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
+-d '{ "templates": [ "generic-host" ], "attrs": { "address": "192.168.1.1", "check_command": "hostalive", "vars.os" : "Linux" }, "pretty": true }'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Object was created."
+ }
+ ]
+}
+```
If the configuration validation fails, the new object will not be created and the response body
contains a detailed error message. The following example is missing the `check_command` attribute
which is required for host objects:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
- -d '{ "attrs": { "address": "192.168.1.1", "vars.os" : "Linux" }, "pretty": true }'
- {
- "results": [
- {
- "code": 500.0,
- "errors": [
- "Error: Validation failed for object 'example.localdomain' of type 'Host'; Attribute 'check_command': Attribute must not be empty."
- ],
- "status": "Object could not be created."
- }
- ]
- }
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
+-d '{ "attrs": { "address": "192.168.1.1", "vars.os" : "Linux" }, "pretty": true }'
+{
+ "results": [
+ {
+ "code": 500.0,
+ "errors": [
+ "Error: Validation failed for object 'example.localdomain' of type 'Host'; Attribute 'check_command': Attribute must not be empty."
+ ],
+ "status": "Object could not be created."
+ }
+ ]
+}
+```
Service objects must be created using their full name ("hostname!servicename") referencing an existing host object:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/services/example.localdomain!realtime-load' \
- -d '{ "templates": [ "generic-service" ], "attrs": { "check_command": "load", "check_interval": 1,"retry_interval": 1 } }'
-
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/services/example.localdomain!realtime-load' \
+-d '{ "templates": [ "generic-service" ], "attrs": { "check_command": "load", "check_interval": 1,"retry_interval": 1 } }'
+```
Example for a new CheckCommand object:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/checkcommands/mytest' \
- -d '{ "templates": [ "plugin-check-command" ], "attrs": { "command": [ "/usr/local/sbin/check_http" ], "arguments": { "-I": "$mytest_iparam$" } } }'
-
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/checkcommands/mytest' \
+-d '{ "templates": [ "plugin-check-command" ], "attrs": { "command": [ "/usr/local/sbin/check_http" ], "arguments": { "-I": "$mytest_iparam$" } } }'
+```
### Modifying Objects <a id="icinga2-api-config-objects-modify"></a>
If attributes are of the Dictionary type, you can also use the indexer format:
- "attrs": { "vars.os": "Linux" }
+```
+"attrs": { "vars.os": "Linux" }
+```
The following example updates the `address` attribute and the custom attribute `os` for the `example.localdomain` host:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
- -d '{ "attrs": { "address": "192.168.1.2", "vars.os" : "Windows" }, "pretty": true }'
- {
- "results": [
- {
- "code": 200.0,
- "name": "example.localdomain",
- "status": "Attributes updated.",
- "type": "Host"
- }
- ]
- }
-
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
+-d '{ "attrs": { "address": "192.168.1.2", "vars.os" : "Windows" }, "pretty": true }'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "name": "example.localdomain",
+ "status": "Attributes updated.",
+ "type": "Host"
+ }
+ ]
+}
+```
### Deleting Objects <a id="icinga2-api-config-objects-delete"></a>
Example for deleting the host object `example.localdomain`:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE 'https://localhost:5665/v1/objects/hosts/example.localdomain?cascade=1&pretty=1'
- {
- "results": [
- {
- "code": 200.0,
- "name": "example.localdomain",
- "status": "Object was deleted.",
- "type": "Host"
- }
- ]
- }
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE 'https://localhost:5665/v1/objects/hosts/example.localdomain?cascade=1&pretty=1'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "name": "example.localdomain",
+ "status": "Object was deleted.",
+ "type": "Host"
+ }
+ ]
+}
+```
## Config Templates <a id="icinga2-api-config-templates"></a>
to be replaced with the plural name of the object type you are interested
in:
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts'
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts'
+```
A list of all available configuration types is available in the
[object types](09-object-types.md#object-types) chapter.
The `filter` attribute is passed inside the request body thus requiring to use [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
here.
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5661/v1/templates/hosts' \
- -d '{ "filter": "match(\"g*\", tmpl.name)" }'
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5661/v1/templates/hosts' \
+-d '{ "filter": "match(\"g*\", tmpl.name)" }'
+```
Instead of using a filter you can optionally specify the template name in the
URL path when querying a single object:
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts/generic-host'
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts/generic-host'
+```
The result set contains the type, name as well as the location of the template.
You can request information about global variables by sending
a `GET` query to the `/v1/variables/` URL endpoint:
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables'
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables'
+```
A [filter](12-icinga2-api.md#icinga2-api-filters) may be provided for this query type. The
variable information object can be accessed in the filter using the `variable` variable.
The `filter` attribute is passed inside the request body thus requiring to use [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
here.
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5661/v1/variables' \
- -d '{ "filter": "variable.type in [ \"String\", \"Number\" ]" }'
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5661/v1/variables' \
+-d '{ "filter": "variable.type in [ \"String\", \"Number\" ]" }'
+```
Instead of using a filter you can optionally specify the variable name in the
URL path when querying a single variable:
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables/PrefixDir'
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables/PrefixDir'
+```
The result set contains the type, name and value of the global variable.
[IcingaApplication object](12-icinga2-api.md#icinga2-api-config-objects)
called `app`.
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/icingaapplications/app' -d '{ "attrs": { "enable_notifications": false } }'
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/icingaapplications/app' -d '{ "attrs": { "enable_notifications": false } }'
+```
### process-check-result <a id="icinga2-api-actions-process-check-result"></a>
Example for the service `passive-ping6`:
- $ 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' \
- -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", "pretty": true }'
-
- {
- "results": [
- {
- "code": 200.0,
- "status": "Successfully processed check result for object 'localdomain!passive-ping6'."
- }
- ]
- }
+```
+$ 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' \
+-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", "pretty": true }'
+
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Successfully processed check result for object 'localdomain!passive-ping6'."
+ }
+ ]
+}
+```
Example for using the `Host` type and filter by the host name:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/process-check-result' \
- -d '{ "filter": "host.name==\"example.localdomain\"", "type": "Host", "exit_status": 1, "plugin_output": "Host is not available." }'
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/process-check-result' \
+-d '{ "filter": "host.name==\"example.localdomain\"", "type": "Host", "exit_status": 1, "plugin_output": "Host is not available." }'
+```
You can avoid URL encoding of white spaces in object names by using the `filter` attribute in the request body.
(`next_check` default), ignoring any time periods or whether active checks are
allowed for the service (`force=true`).
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \
- -d '{ "type": "Service", "filter": "service.name==\"ping6\"", "force": true, "pretty": true }'
-
- {
- "results": [
- {
- "code": 200.0,
- "status": "Successfully rescheduled check for object 'example.localdomain!ping6'."
- }
- ]
- }
-
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \
+-d '{ "type": "Service", "filter": "service.name==\"ping6\"", "force": true, "pretty": true }'
+
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Successfully rescheduled check for object 'example.localdomain!ping6'."
+ }
+ ]
+}
+```
### send-custom-notification <a id="icinga2-api-actions-send-custom-notification"></a>
Example for a custom host notification announcing a global maintenance to
host owners:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/send-custom-notification' \
- -d '{ "type": "Host", "author": "icingaadmin", "comment": "System is going down for maintenance", "force": true, "pretty": true }'
-
- {
- "results": [
- {
- "code": 200.0,
- "status": "Successfully sent custom notification for object 'host0'."
- },
- {
- "code": 200.0,
- "status": "Successfully sent custom notification for object 'host1'."
- }
- }
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/send-custom-notification' \
+-d '{ "type": "Host", "author": "icingaadmin", "comment": "System is going down for maintenance", "force": true, "pretty": true }'
+
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Successfully sent custom notification for object 'host0'."
+ },
+ {
+ "code": 200.0,
+ "status": "Successfully sent custom notification for object 'host1'."
+ }
+}
+```
### delay-notification <a id="icinga2-api-actions-delay-notification"></a>
Example:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/delay-notification' \
- -d '{ "type": "Service", "timestamp": 1446389894, "pretty": true }'
-
- {
- "results": [
- {
- "code": 200.0,
- "status": "Successfully delayed notifications for object 'host0!service0'."
- },
- {
- "code": 200.0,
- "status": "Successfully delayed notifications for object 'host1!service1'."
- }
- }
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/delay-notification' \
+-d '{ "type": "Service", "timestamp": 1446389894, "pretty": true }'
+
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Successfully delayed notifications for object 'host0!service0'."
+ },
+ {
+ "code": 200.0,
+ "status": "Successfully delayed notifications for object 'host1!service1'."
+ }
+}
+```
### acknowledge-problem <a id="icinga2-api-actions-acknowledge-problem"></a>
The following example acknowledges all services which are in a hard critical state and sends out
a notification for them:
- $ 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' \
- -d '{ "author": "icingaadmin", "comment": "Global outage. Working on it.", "notify": true, "pretty": true }'
-
- {
- "results": [
- {
- "code": 200.0,
- "status": "Successfully acknowledged problem for object 'example2.localdomain!ping4'."
- },
- {
- "code": 200.0,
- "status": "Successfully acknowledged problem for object 'example.localdomain!ping4'."
- }
- }
-
+```
+$ 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' \
+-d '{ "author": "icingaadmin", "comment": "Global outage. Working on it.", "notify": true, "pretty": true }'
+
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Successfully acknowledged problem for object 'example2.localdomain!ping4'."
+ },
+ {
+ "code": 200.0,
+ "status": "Successfully acknowledged problem for object 'example.localdomain!ping4'."
+ }
+}
+```
### remove-acknowledgement <a id="icinga2-api-actions-remove-acknowledgement"></a>
The example removes all service acknowledgements:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-acknowledgement?type=Service&pretty=1'
-
- {
- "results": [
- {
- "code": 200.0,
- "status": "Successfully removed acknowledgement for object 'host0!service0'."
- },
- {
- "code": 200.0,
- "status": "Successfully removed acknowledgement for object 'example2.localdomain!aws-health'."
- }
- }
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-acknowledgement?type=Service&pretty=1'
+
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Successfully removed acknowledgement for object 'host0!service0'."
+ },
+ {
+ "code": 200.0,
+ "status": "Successfully removed acknowledgement for object 'example2.localdomain!aws-health'."
+ }
+}
+```
### add-comment <a id="icinga2-api-actions-add-comment"></a>
The following example adds a comment for all `ping4` services:
- $ 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.", "pretty": true }'
- {
- "results": [
- {
- "code": 200.0,
- "legacy_id": 26.0,
- "name": "example.localdomain!ping4!example.localdomain-1446824161-0",
- "status": "Successfully added comment 'example.localdomain!ping4!example.localdomain-1446824161-0' for object 'example.localdomain!ping4'."
- },
- {
- "code": 200.0,
- "legacy_id": 27.0,
- "name": "example2.localdomain!ping4!example.localdomain-1446824161-1",
- "status": "Successfully added comment 'example2.localdomain!ping4!example.localdomain-1446824161-1' for object 'example2.localdomain!ping4'."
- }
- ]
- }
+```
+$ 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.", "pretty": true }'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "legacy_id": 26.0,
+ "name": "example.localdomain!ping4!example.localdomain-1446824161-0",
+ "status": "Successfully added comment 'example.localdomain!ping4!example.localdomain-1446824161-0' for object 'example.localdomain!ping4'."
+ },
+ {
+ "code": 200.0,
+ "legacy_id": 27.0,
+ "name": "example2.localdomain!ping4!example.localdomain-1446824161-1",
+ "status": "Successfully added comment 'example2.localdomain!ping4!example.localdomain-1446824161-1' for object 'example2.localdomain!ping4'."
+ }
+ ]
+}
+```
### remove-comment <a id="icinga2-api-actions-remove-comment"></a>
Example for a simple filter using the `comment` URL parameter:
- $ 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&pretty=1'
- {
- "results": [
- {
- "code": 200.0,
- "status": "Successfully removed comment 'example2.localdomain!ping4!mbmif.local-1446986367-0'."
- }
- ]
- }
+```
+$ 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&pretty=1'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Successfully removed comment 'example2.localdomain!ping4!mbmif.local-1446986367-0'."
+ }
+ ]
+}
+```
Example for removing all service comments using a service name filter for `ping4`:
- $ 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&pretty=1'
- {
- "results": [
- {
- "code": 200.0,
- "status": "Successfully removed all comments for object 'example2.localdomain!ping4'."
- },
- {
- "code": 200.0,
- "status": "Successfully removed all comments for object 'example.localdomain!ping4'."
- }
- ]
- }
-
+```
+$ 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&pretty=1'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Successfully removed all comments for object 'example2.localdomain!ping4'."
+ },
+ {
+ "code": 200.0,
+ "status": "Successfully removed all comments for object 'example.localdomain!ping4'."
+ }
+ ]
+}
+```
### schedule-downtime <a id="icinga2-api-actions-schedule-downtime"></a>
Example:
- $ 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", "pretty": true }'
- {
- "results": [
- {
- "code": 200.0,
- "legacy_id": 2.0,
- "name": "example2.localdomain!ping4!example.localdomain-1446822004-0",
- "status": "Successfully scheduled downtime 'example2.localdomain!ping4!example.localdomain-1446822004-0' for object 'example2.localdomain!ping4'."
- },
- {
- "code": 200.0,
- "legacy_id": 3.0,
- "name": "example.localdomain!ping4!example.localdomain-1446822004-1",
- "status": "Successfully scheduled downtime 'example.localdomain!ping4!example.localdomain-1446822004-1' for object 'example.localdomain!ping4'."
- }
- ]
- }
+```
+$ 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", "pretty": true }'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "legacy_id": 2.0,
+ "name": "example2.localdomain!ping4!example.localdomain-1446822004-0",
+ "status": "Successfully scheduled downtime 'example2.localdomain!ping4!example.localdomain-1446822004-0' for object 'example2.localdomain!ping4'."
+ },
+ {
+ "code": 200.0,
+ "legacy_id": 3.0,
+ "name": "example.localdomain!ping4!example.localdomain-1446822004-1",
+ "status": "Successfully scheduled downtime 'example.localdomain!ping4!example.localdomain-1446822004-1' for object 'example.localdomain!ping4'."
+ }
+ ]
+}
+```
### remove-downtime <a id="icinga2-api-actions-remove-downtime"></a>
Example for a simple filter using the `downtime` URL parameter:
- $ 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&pretty=1'
- {
- "results": [
- {
- "code": 200.0,
- "status": "Successfully removed downtime 'example.localdomain!ping4!mbmif.local-1446979168-6'."
- }
- ]
- }
+```
+$ 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&pretty=1'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Successfully removed downtime 'example.localdomain!ping4!mbmif.local-1446979168-6'."
+ }
+ ]
+}
+```
Example for removing all host downtimes using a host name filter for `example.localdomain`:
- $ 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&pretty=1'
- {
- "results": [
- {
- "code": 200.0,
- "status": "Successfully removed all downtimes for object 'example.localdomain'."
- }
- ]
- }
+```
+$ 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&pretty=1'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Successfully removed all downtimes for object 'example.localdomain'."
+ }
+ ]
+}
+```
Example for removing a downtime from a host but not the services filtered by the author name. This example uses
filter variables explained in the [advanced filters](12-icinga2-api.md#icinga2-api-advanced-filters) chapter.
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime' \
- -d $'{
- "type": "Downtime",
- "filter": "host.name == filterHost && !service && downtime.author == filterAuthor",
- "filter_vars": {
- "filterHost": "example.localdomain",
- "filterAuthor": "icingaadmin"
- },
- "pretty": true
- }'
-
- {
- "results": [
- {
- "code": 200.0,
- "status": "Successfully removed downtime 'example.localdomain!mbmif.local-1463043129-3'."
- }
- ]
- }
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime' \
+ -d $'{
+ "type": "Downtime",
+ "filter": "host.name == filterHost && !service && downtime.author == filterAuthor",
+ "filter_vars": {
+ "filterHost": "example.localdomain",
+ "filterAuthor": "icingaadmin"
+ },
+ "pretty": true
+}'
+
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Successfully removed downtime 'example.localdomain!mbmif.local-1463043129-3'."
+ }
+ ]
+}
+```
### shutdown-process <a id="icinga2-api-actions-shutdown-process"></a>
Example:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/shutdown-process?pretty=1'
-
- {
- "results": [
- {
- "code": 200.0,
- "status": "Shutting down Icinga 2."
- }
- ]
- }
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/shutdown-process?pretty=1'
+
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Shutting down Icinga 2."
+ }
+ ]
+}
+```
### restart-process <a id="icinga2-api-actions-restart-process"></a>
Example:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/restart-process?pretty=1'
-
- {
- "results": [
- {
- "code": 200.0,
- "status": "Restarting Icinga 2."
- }
- ]
- }
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/restart-process?pretty=1'
+
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Restarting Icinga 2."
+ }
+ ]
+}
+```
### generate-ticket <a id="icinga2-api-actions-generate-ticket"></a>
Example:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/generate-ticket' \
- -d '{ "cn": "icinga2-client1.localdomain", "pretty": true }'
- {
- "results": [
- {
- "code": 200.0,
- "status": "Generated PKI ticket '4f75d2ecd253575fe9180938ebff7cbca262f96e' for common name 'icinga2-client1.localdomain'.",
- "ticket": "4f75d2ecd253575fe9180938ebff7cbca262f96e"
- }
- ]
- }
-
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/generate-ticket' \
+-d '{ "cn": "icinga2-client1.localdomain", "pretty": true }'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Generated PKI ticket '4f75d2ecd253575fe9180938ebff7cbca262f96e' for common name 'icinga2-client1.localdomain'.",
+ "ticket": "4f75d2ecd253575fe9180938ebff7cbca262f96e"
+ }
+ ]
+}
+```
## Event Streams <a id="icinga2-api-event-streams"></a>
Example for all downtime events:
- &types=DowntimeAdded&types=DowntimeRemoved&types=DowntimeTriggered
+```
+&types=DowntimeAdded&types=DowntimeRemoved&types=DowntimeTriggered
+```
#### <a id="icinga2-api-event-streams-type-checkresult"></a> Event Stream Type: CheckResult
Example for the `CheckResult` type with the `exit_code` set to `2`:
- &types=CheckResult&filter=event.check_result.exit_status==2
+```
+&types=CheckResult&filter=event.check_result.exit_status==2
+```
Example for the `CheckResult` type with the service [matching](18-library-reference.md#global-functions-match)
the string pattern "random\*":
- &types=CheckResult&filter=match%28%22random*%22,event.service%29
-
+```
+&types=CheckResult&filter=match%28%22random*%22,event.service%29
+```
### Event Stream Response <a id="icinga2-api-event-streams-response"></a>
Example:
- $ 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'
-
- {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421319.7226390839,"type":"CheckResult"}
- {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421324.7226390839,"type":"CheckResult"}
- {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421329.7226390839,"type":"CheckResult"}
+```
+$ 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'
+{"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421319.7226390839,"type":"CheckResult"}
+{"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421324.7226390839,"type":"CheckResult"}
+{"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421329.7226390839,"type":"CheckResult"}
+```
## Status and Statistics <a id="icinga2-api-status"></a>
Example:
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/status?pretty=1'
- {
- "results": [
- {
- "name": "ApiListener",
- "perfdata": [ ... ],
- "status": [ ... ]
- },
- ...
- {
- "name": "IcingaAplication",
- "perfdata": [ ... ],
- "status": [ ... ]
- },
- ...
- ]
- }
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/status?pretty=1'
+{
+ "results": [
+ {
+ "name": "ApiListener",
+ "perfdata": [ ... ],
+ "status": [ ... ]
+ },
+ ...
+ {
+ "name": "IcingaAplication",
+ "perfdata": [ ... ],
+ "status": [ ... ]
+ },
+ ...
+ ]
+}
+```
You can limit the output by specifying a status type in the URL, e.g. `IcingaApplication`:
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/status/IcingaApplication?pretty=1'
- {
- "results": [
- {
- "perfdata": [],
- "status": {
- "icingaapplication": {
- "app": {
- "enable_event_handlers": true,
- "enable_flapping": true,
- "enable_host_checks": true,
- "enable_notifications": true,
- "enable_perfdata": true,
- "enable_service_checks": true,
- "node_name": "example.localdomain",
- "pid": 59819.0,
- "program_start": 1443019345.093372,
- "version": "v2.3.0-573-g380a131"
- }
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/status/IcingaApplication?pretty=1'
+{
+ "results": [
+ {
+ "perfdata": [],
+ "status": {
+ "icingaapplication": {
+ "app": {
+ "enable_event_handlers": true,
+ "enable_flapping": true,
+ "enable_host_checks": true,
+ "enable_notifications": true,
+ "enable_perfdata": true,
+ "enable_service_checks": true,
+ "node_name": "example.localdomain",
+ "pid": 59819.0,
+ "program_start": 1443019345.093372,
+ "version": "v2.3.0-573-g380a131"
}
}
}
- ]
- }
-
+ }
+ ]
+}
+```
## Configuration Management <a id="icinga2-api-config-management"></a>
Send a `POST` request to a new config package called `example-cmdb` in this example. This
will create a new empty configuration package.
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \
- 'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1'
- {
- "results": [
- {
- "code": 200.0,
- "package": "example-cmdb",
- "status": "Created package."
- }
- ]
- }
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \
+'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "package": "example-cmdb",
+ "status": "Created package."
+ }
+ ]
+}
+```
Package names starting with an underscore are reserved for internal packages and must not be used.
Example for a local configuration in the `conf.d` directory:
- "files": { "conf.d/host1.conf": "object Host \"local-host\" { address = \"127.0.0.1\", check_command = \"hostalive\" }" }
+```
+"files": { "conf.d/host1.conf": "object Host \"local-host\" { address = \"127.0.0.1\", check_command = \"hostalive\" }" }
+```
Example for a host configuration inside the `satellite` zone in the `zones.d` directory:
- "files": { "zones.d/satellite/host2.conf": "object Host \"satellite-host\" { address = \"192.168.1.100\", check_command = \"hostalive\" }" }
+```
+"files": { "zones.d/satellite/host2.conf": "object Host \"satellite-host\" { address = \"192.168.1.100\", check_command = \"hostalive\" }" }
+```
The example below will create a new file called `test.conf` in the `conf.d`
directory. Note: This example contains an error (`chec_command`). This is
intentional.
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \
- -d '{ "files": { "conf.d/test.conf": "object Host \"cmdb-host\" { chec_command = \"dummy\" }" }, "pretty": true }' \
- 'https://localhost:5665/v1/config/stages/example-cmdb'
- {
- "results": [
- {
- "code": 200.0,
- "package": "example-cmdb",
- "stage": "example.localdomain-1441625839-0",
- "status": "Created stage. Icinga2 will reload."
- }
- ]
- }
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \
+-d '{ "files": { "conf.d/test.conf": "object Host \"cmdb-host\" { chec_command = \"dummy\" }" }, "pretty": true }' \
+'https://localhost:5665/v1/config/stages/example-cmdb'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "package": "example-cmdb",
+ "stage": "example.localdomain-1441625839-0",
+ "status": "Created stage. Icinga2 will reload."
+ }
+ ]
+}
+```
The Icinga 2 API returns the `package` name this stage was created for, and also
generates a unique name for the `stage` attribute you'll need for later requests.
The following example contains one configuration package `example-cmdb`. The package does not currently
have an active stage.
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/packages?pretty=1'
- {
- "results": [
- {
- "active-stage": "",
- "name": "example-cmdb",
- "stages": [
- "example.localdomain-1441625839-0"
- ]
- }
- ]
- }
-
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/packages?pretty=1'
+{
+ "results": [
+ {
+ "active-stage": "",
+ "name": "example-cmdb",
+ "stages": [
+ "example.localdomain-1441625839-0"
+ ]
+ }
+ ]
+}
+```
### List Configuration Packages and their Stages <a id="icinga2-api-config-management-list-config-package-stage-files"></a>
the URL endpoint `/v1/config/stages`. You need to include
the package name (`example-cmdb`) and stage name (`example.localdomain-1441625839-0`) in the URL:
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441625839-0?pretty=1'
- {
- "results": [
- ...
- {
- "name": "startup.log",
- "type": "file"
- },
- {
- "name": "status",
- "type": "file"
- },
- {
- "name": "conf.d",
- "type": "directory"
- },
- {
- "name": "zones.d",
- "type": "directory"
- },
- {
- "name": "conf.d/test.conf",
- "type": "file"
- }
- ]
- }
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441625839-0?pretty=1'
+{
+ "results": [
+...
+ {
+ "name": "startup.log",
+ "type": "file"
+ },
+ {
+ "name": "status",
+ "type": "file"
+ },
+ {
+ "name": "conf.d",
+ "type": "directory"
+ },
+ {
+ "name": "zones.d",
+ "type": "directory"
+ },
+ {
+ "name": "conf.d/test.conf",
+ "type": "file"
+ }
+ ]
+}
+```
### Fetch Configuration Package Stage Files <a id="icinga2-api-config-management-fetch-config-package-stage-files"></a>
The following example fetches the configuration file `conf.d/test.conf`:
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441625839-0/conf.d/test.conf'
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441625839-0/conf.d/test.conf'
- object Host "cmdb-host" { chec_command = "dummy" }
+object Host "cmdb-host" { chec_command = "dummy" }
+```
You can fetch a [list of existing files](12-icinga2-api.md#icinga2-api-config-management-list-config-package-stage-files)
in a configuration stage and then specifically request their content.
by sending a `GET` request to the URL endpoint `/v1/config/files`. You must include
the package name, stage name and the `startup.log` in the URL path.
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441133065-1/startup.log'
- ...
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441133065-1/startup.log'
+...
- critical/config: Error: Attribute 'chec_command' does not exist.
- Location:
- /var/lib/icinga2/api/packages/example-cmdb/example.localdomain-1441133065-1/conf.d/test.conf(1): object Host "cmdb-host" { chec_command = "dummy" }
- ^^^^^^^^^^^^^^^^^^^^^^
+critical/config: Error: Attribute 'chec_command' does not exist.
+Location:
+/var/lib/icinga2/api/packages/example-cmdb/example.localdomain-1441133065-1/conf.d/test.conf(1): object Host "cmdb-host" { chec_command = "dummy" }
+ ^^^^^^^^^^^^^^^^^^^^^^
- critical/config: 1 error
+critical/config: 1 error
+```
The output is similar to the manual [configuration validation](11-cli-commands.md#config-validation).
The following example removes the failed configuration stage `example.localdomain-1441133065-1`
in the `example-cmdb` configuration package:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \
- 'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441133065-1?pretty=1'
- {
- "results": [
- {
- "code": 200.0,
- "status": "Stage deleted."
- }
- ]
- }
-
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \
+'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441133065-1?pretty=1'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Stage deleted."
+ }
+ ]
+}
+```
### Deleting Configuration Package <a id="icinga2-api-config-management-delete-config-package"></a>
This example entirely deletes the configuration package `example-cmdb`:
- $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \
- 'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1'
- {
- "results": [
- {
- "code": 200.0,
- "package": "example-cmdb",
- "status": "Deleted package."
- }
- ]
- }
-
+```
+$ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \
+'https://localhost:5665/v1/config/packages/example-cmdb?pretty=1'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "package": "example-cmdb",
+ "status": "Deleted package."
+ }
+ ]
+}
+```
## Types <a id="icinga2-api-types"></a>
In order to view a specific configuration object type specify its name inside the URL path:
- $ curl -k -s -u root:icinga 'https://localhost:5665/v1/types/Object?pretty=1'
- {
- "results": [
- {
- "abstract": false,
- "fields": {
- "type": {
- "array_rank": 0.0,
- "attributes": {
- "config": false,
- "navigation": false,
- "no_user_modify": false,
- "no_user_view": false,
- "required": false,
- "state": false
- },
- "id": 0.0,
- "type": "String"
- }
- },
- "name": "Object",
- "plural_name": "Objects",
- "prototype_keys": [
- "clone",
- "notify_attribute",
- "to_string"
- ]
- }
- ]
- }
-
+```
+$ curl -k -s -u root:icinga 'https://localhost:5665/v1/types/Object?pretty=1'
+{
+ "results": [
+ {
+ "abstract": false,
+ "fields": {
+ "type": {
+ "array_rank": 0.0,
+ "attributes": {
+ "config": false,
+ "navigation": false,
+ "no_user_modify": false,
+ "no_user_view": false,
+ "required": false,
+ "state": false
+ },
+ "id": 0.0,
+ "type": "String"
+ }
+ },
+ "name": "Object",
+ "plural_name": "Objects",
+ "prototype_keys": [
+ "clone",
+ "notify_attribute",
+ "to_string"
+ ]
+ }
+ ]
+}
+```
## Console <a id="icinga2-api-console"></a>
Example for fetching the command line from the local host's last check result:
- $ 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&pretty=1'
- {
- "results": [
- {
- "code": 200.0,
- "result": [
- "/usr/local/sbin/check_ping",
- "-H",
- "127.0.0.1",
- "-c",
- "5000,100%",
- "-w",
- "3000,80%"
- ],
- "status": "Executed successfully."
- }
- ]
- }
+```
+$ 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&pretty=1'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "result": [
+ "/usr/local/sbin/check_ping",
+ "-H",
+ "127.0.0.1",
+ "-c",
+ "5000,100%",
+ "-w",
+ "3000,80%"
+ ],
+ "status": "Executed successfully."
+ }
+ ]
+}
+```
Example for fetching auto-completion suggestions for the `Host.` type. This works in a
similar fashion when pressing TAB inside the [console CLI command](11-cli-commands.md#cli-command-console):
- $ 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&pretty=1'
- {
- "results": [
- {
- "code": 200.0,
- "status": "Auto-completed successfully.",
- "suggestions": [
- "Host.type",
- "Host.name",
- "Host.prototype",
- "Host.base",
- "Host.register_attribute_handler",
- "Host.clone",
- "Host.notify_attribute",
- "Host.to_string"
- ]
- }
- ]
- }
-
+```
+$ 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&pretty=1'
+{
+ "results": [
+ {
+ "code": 200.0,
+ "status": "Auto-completed successfully.",
+ "suggestions": [
+ "Host.type",
+ "Host.name",
+ "Host.prototype",
+ "Host.base",
+ "Host.register_attribute_handler",
+ "Host.clone",
+ "Host.notify_attribute",
+ "Host.to_string"
+ ]
+ }
+ ]
+}
+```
## API Clients <a id="icinga2-api-clients"></a>
The following example uses **Python** and the `requests` and `json` module:
- # pip install requests
- # pip install json
-
- $ vim icinga2-api-example.py
-
- #!/usr/bin/env python
-
- import requests, json
-
- # Replace 'localhost' with your FQDN and certificate CN
- # for SSL verification
- request_url = "https://localhost:5665/v1/objects/services"
- headers = {
- 'Accept': 'application/json',
- 'X-HTTP-Method-Override': 'GET'
- }
- data = {
- "attrs": [ "name", "state", "last_check_result" ],
- "joins": [ "host.name", "host.state", "host.last_check_result" ],
- "filter": "match(\"ping*\", service.name)",
- }
-
- r = requests.post(request_url,
- headers=headers,
- auth=('root', 'icinga'),
- data=json.dumps(data),
- verify="pki/icinga2-ca.crt")
-
- print "Request URL: " + str(r.url)
- print "Status code: " + str(r.status_code)
-
- if (r.status_code == 200):
- print "Result: " + json.dumps(r.json())
- else:
- print r.text
- r.raise_for_status()
-
- $ python icinga2-api-example.py
-
+```
+# pip install requests
+# pip install json
+
+$ vim icinga2-api-example.py
+
+#!/usr/bin/env python
+
+import requests, json
+
+# Replace 'localhost' with your FQDN and certificate CN
+# for SSL verification
+request_url = "https://localhost:5665/v1/objects/services"
+headers = {
+ 'Accept': 'application/json',
+ 'X-HTTP-Method-Override': 'GET'
+ }
+data = {
+ "attrs": [ "name", "state", "last_check_result" ],
+ "joins": [ "host.name", "host.state", "host.last_check_result" ],
+ "filter": "match(\"ping*\", service.name)",
+}
+
+r = requests.post(request_url,
+ headers=headers,
+ auth=('root', 'icinga'),
+ data=json.dumps(data),
+ verify="pki/icinga2-ca.crt")
+
+print "Request URL: " + str(r.url)
+print "Status code: " + str(r.status_code)
+
+if (r.status_code == 200):
+ print "Result: " + json.dumps(r.json())
+else:
+ print r.text
+ r.raise_for_status()
+
+$ python icinga2-api-example.py
+```
#### Example API Client in Ruby <a id="icinga2-api-clients-programmatic-examples-ruby"></a>
The following example uses **Ruby** and the `rest_client` gem:
- # gem install rest_client
-
- $ vim icinga2-api-example.rb
-
- #!/usr/bin/ruby
-
- require 'rest_client'
-
- # Replace 'localhost' with your FQDN and certificate CN
- # for SSL verification
- request_url = "https://localhost:5665/v1/objects/services"
- headers = {
- "Accept" => "application/json",
- "X-HTTP-Method-Override" => "GET"
- }
- data = {
- "attrs" => [ "name", "state", "last_check_result" ],
- "joins" => [ "host.name", "host.state", "host.last_check_result" ],
- "filter" => "match(\"ping*\", service.name)",
- }
-
- r = RestClient::Resource.new(
- URI.encode(request_url),
- :headers => headers,
- :user => "root",
- :password => "icinga",
- :ssl_ca_file => "pki/icinga2-ca.crt")
-
- begin
- response = r.post(data.to_json)
- rescue => e
- response = e.response
- end
-
- puts "Status: " + response.code.to_s
- if response.code == 200
- puts "Result: " + (JSON.pretty_generate JSON.parse(response.body))
- else
- puts "Error: " + response
- end
-
- $ ruby icinga2-api-example.rb
+```
+# gem install rest_client
+
+$ vim icinga2-api-example.rb
+
+#!/usr/bin/ruby
+
+require 'rest_client'
+
+# Replace 'localhost' with your FQDN and certificate CN
+# for SSL verification
+request_url = "https://localhost:5665/v1/objects/services"
+headers = {
+ "Accept" => "application/json",
+ "X-HTTP-Method-Override" => "GET"
+}
+data = {
+ "attrs" => [ "name", "state", "last_check_result" ],
+ "joins" => [ "host.name", "host.state", "host.last_check_result" ],
+ "filter" => "match(\"ping*\", service.name)",
+}
+
+r = RestClient::Resource.new(
+ URI.encode(request_url),
+ :headers => headers,
+ :user => "root",
+ :password => "icinga",
+ :ssl_ca_file => "pki/icinga2-ca.crt")
+
+begin
+ response = r.post(data.to_json)
+rescue => e
+ response = e.response
+end
+
+puts "Status: " + response.code.to_s
+if response.code == 200
+ puts "Result: " + (JSON.pretty_generate JSON.parse(response.body))
+else
+ puts "Error: " + response
+end
+
+$ ruby icinga2-api-example.rb
+```
A more detailed example can be found in the [Dashing demo](https://github.com/Icinga/dashing-icinga2).
The following example uses **PHP** and its `curl` library:
- $ vim icinga2-api-example.php
-
- #!/usr/bin/env php
- <?php
- # Replace 'localhost' with your FQDN and certificate CN
- # for SSL verification
- $request_url = "https://localhost:5665/v1/objects/services";
- $username = "root";
- $password = "icinga";
- $headers = array(
- 'Accept: application/json',
- 'X-HTTP-Method-Override: GET'
- );
- $data = array(
- attrs => array('name', 'state', 'last_check_result'),
- joins => array('host.name', 'host.state', 'host.last_check_result'),
- filter => 'match("ping*", service.name)',
- );
-
- $ch = curl_init();
- curl_setopt_array($ch, array(
- CURLOPT_URL => $request_url,
- CURLOPT_HTTPHEADER => $headers,
- CURLOPT_USERPWD => $username . ":" . $password,
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_CAINFO => "pki/icinga2-ca.crt",
- CURLOPT_POST => count($data),
- CURLOPT_POSTFIELDS => json_encode($data)
- ));
-
- $response = curl_exec($ch);
- if ($response === false) {
- print "Error: " . curl_error($ch) . "(" . $response . ")\n";
- }
-
- $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- curl_close($ch);
- print "Status: " . $code . "\n";
-
- if ($code == 200) {
- $response = json_decode($response, true);
- print_r($response);
- }
- ?>
-
- $ php icinga2-api-example.php
+```
+$ vim icinga2-api-example.php
+
+#!/usr/bin/env php
+<?php
+# Replace 'localhost' with your FQDN and certificate CN
+# for SSL verification
+$request_url = "https://localhost:5665/v1/objects/services";
+$username = "root";
+$password = "icinga";
+$headers = array(
+ 'Accept: application/json',
+ 'X-HTTP-Method-Override: GET'
+);
+$data = array(
+ attrs => array('name', 'state', 'last_check_result'),
+ joins => array('host.name', 'host.state', 'host.last_check_result'),
+ filter => 'match("ping*", service.name)',
+);
+
+$ch = curl_init();
+curl_setopt_array($ch, array(
+ CURLOPT_URL => $request_url,
+ CURLOPT_HTTPHEADER => $headers,
+ CURLOPT_USERPWD => $username . ":" . $password,
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_CAINFO => "pki/icinga2-ca.crt",
+ CURLOPT_POST => count($data),
+ CURLOPT_POSTFIELDS => json_encode($data)
+));
+
+$response = curl_exec($ch);
+if ($response === false) {
+ print "Error: " . curl_error($ch) . "(" . $response . ")\n";
+}
+
+$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+curl_close($ch);
+print "Status: " . $code . "\n";
+
+if ($code == 200) {
+ $response = json_decode($response, true);
+ print_r($response);
+}
+?>
+
+$ php icinga2-api-example.php
+```
#### Example API Client in Perl <a id="icinga2-api-clients-programmatic-examples-perl"></a>
The following example uses **Perl** and the `Rest::Client` module:
- # perl -MCPAN -e 'install REST::Client'
- # perl -MCPAN -e 'install JSON'
- # perl -MCPAN -e 'install MIME::Base64'
- # perl -MCPAN -e 'install Data::Dumper'
-
- $ vim icinga2-api-example.pl
-
- #!/usr/bin/env perl
-
- use strict;
- use warnings;
- use REST::Client;
- use MIME::Base64;
- use JSON;
- use Data::Dumper;
-
- # Replace 'localhost' with your FQDN and certificate CN
- # for SSL verification
- my $request_host = "https://localhost:5665";
- my $userpass = "root:icinga";
-
- my $client = REST::Client->new();
- $client->setHost($request_host);
- $client->setCa("pki/icinga2-ca.crt");
- $client->addHeader("Accept", "application/json");
- $client->addHeader("X-HTTP-Method-Override", "GET");
- $client->addHeader("Authorization", "Basic " . encode_base64($userpass));
- my %json_data = (
- attrs => ['name', 'state', 'last_check_result'],
- joins => ['host.name', 'host.state', 'host.last_check_result'],
- filter => 'match("ping*", service.name)',
- );
- my $data = encode_json(\%json_data);
- $client->POST("/v1/objects/services", $data);
-
- my $status = $client->responseCode();
- print "Status: " . $status . "\n";
- my $response = $client->responseContent();
- if ($status == 200) {
- print "Result: " . Dumper(decode_json($response)) . "\n";
- } else {
- print "Error: " . $response . "\n";
- }
-
- $ perl icinga2-api-example.pl
-
+```
+# perl -MCPAN -e 'install REST::Client'
+# perl -MCPAN -e 'install JSON'
+# perl -MCPAN -e 'install MIME::Base64'
+# perl -MCPAN -e 'install Data::Dumper'
+
+$ vim icinga2-api-example.pl
+
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+use REST::Client;
+use MIME::Base64;
+use JSON;
+use Data::Dumper;
+
+# Replace 'localhost' with your FQDN and certificate CN
+# for SSL verification
+my $request_host = "https://localhost:5665";
+my $userpass = "root:icinga";
+
+my $client = REST::Client->new();
+$client->setHost($request_host);
+$client->setCa("pki/icinga2-ca.crt");
+$client->addHeader("Accept", "application/json");
+$client->addHeader("X-HTTP-Method-Override", "GET");
+$client->addHeader("Authorization", "Basic " . encode_base64($userpass));
+my %json_data = (
+ attrs => ['name', 'state', 'last_check_result'],
+ joins => ['host.name', 'host.state', 'host.last_check_result'],
+ filter => 'match("ping*", service.name)',
+);
+my $data = encode_json(\%json_data);
+$client->POST("/v1/objects/services", $data);
+
+my $status = $client->responseCode();
+print "Status: " . $status . "\n";
+my $response = $client->responseContent();
+if ($status == 200) {
+ print "Result: " . Dumper(decode_json($response)) . "\n";
+} else {
+ print "Error: " . $response . "\n";
+}
+
+$ perl icinga2-api-example.pl
+```
Use the [GraphiteWriter](14-features.md#graphite-carbon-cache-writer) feature
for sending real-time metrics from Icinga 2 to Graphite.
- # icinga2 feature enable graphite
+```
+# icinga2 feature enable graphite
+```
A popular alternative frontend for Graphite is for example [Grafana](https://grafana.org).
Use the [InfluxdbWriter](14-features.md#influxdb-writer) feature
for sending real-time metrics from Icinga 2 to InfluxDB.
- # icinga2 feature enable influxdb
+```
+# icinga2 feature enable influxdb
+```
A popular frontend for InfluxDB is for example [Grafana](https://grafana.org).
Enable performance data writer in icinga 2
- # icinga2 feature enable perfdata
+```
+# icinga2 feature enable perfdata
+```
Configure npcd to use the performance data created by Icinga 2:
- vim /etc/pnp4nagios/npcd.cfg
+```
+vim /etc/pnp4nagios/npcd.cfg
+```
Set `perfdata_spool_dir = /var/spool/icinga2/perfdata` and restart the `npcd` daemon.
The configuration in nagvis.ini.php should look like this for Livestatus for example:
- [backend_live_1]
- backendtype="mklivestatus"
- socket="unix:/var/run/icinga2/cmd/livestatus"
+```
+[backend_live_1]
+backendtype="mklivestatus"
+socket="unix:/var/run/icinga2/cmd/livestatus"
+```
If you are planning an integration into Icinga Web 2, look at [this module](https://github.com/Icinga/icingaweb2-module-nagvis).
They work in a similar fashion for Icinga 2 and are used for 1.x web interfaces (Icinga Web 2 doesn't require
the action url attribute in its own module).
- template Host "pnp-hst" {
- action_url = "/pnp4nagios/graph?host=$HOSTNAME$"
- }
+```
+template Host "pnp-hst" {
+ action_url = "/pnp4nagios/graph?host=$HOSTNAME$"
+}
- template Service "pnp-svc" {
- action_url = "/pnp4nagios/graph?host=$HOSTNAME$&srv=$SERVICEDESC$"
- }
+template Service "pnp-svc" {
+ action_url = "/pnp4nagios/graph?host=$HOSTNAME$&srv=$SERVICEDESC$"
+}
+```
### PNP Custom Templates with Icinga 2 <a id="addons-graphing-pnp-custom-templates"></a>
Example for services:
- # vim /etc/icinga2/features-enabled/perfdata.conf
+```
+# vim /etc/icinga2/features-enabled/perfdata.conf
- service_format_template = "DATATYPE::SERVICEPERFDATA\tTIMET::$icinga.timet$\tHOSTNAME::$host.name$\tSERVICEDESC::$service.name$\tSERVICEPERFDATA::$service.perfdata$\tSERVICECHECKCOMMAND::$service.check_command$$pnp_check_arg1$\tHOSTSTATE::$host.state$\tHOSTSTATETYPE::$host.state_type$\tSERVICESTATE::$service.state$\tSERVICESTATETYPE::$service.state_type$"
+service_format_template = "DATATYPE::SERVICEPERFDATA\tTIMET::$icinga.timet$\tHOSTNAME::$host.name$\tSERVICEDESC::$service.name$\tSERVICEPERFDATA::$service.perfdata$\tSERVICECHECKCOMMAND::$service.check_command$$pnp_check_arg1$\tHOSTSTATE::$host.state$\tHOSTSTATETYPE::$host.state_type$\tSERVICESTATE::$service.state$\tSERVICESTATETYPE::$service.state_type$"
- # vim /etc/icinga2/conf.d/services.conf
+# vim /etc/icinga2/conf.d/services.conf
- template Service "pnp-svc" {
- action_url = "/pnp4nagios/graph?host=$HOSTNAME$&srv=$SERVICEDESC$"
- vars.pnp_check_arg1 = ""
- }
+template Service "pnp-svc" {
+ action_url = "/pnp4nagios/graph?host=$HOSTNAME$&srv=$SERVICEDESC$"
+ vars.pnp_check_arg1 = ""
+}
- apply Service "nrpe-check" {
- import "pnp-svc"
- check_command = nrpe
- vars.nrpe_command = "check_disk"
+apply Service "nrpe-check" {
+ import "pnp-svc"
+ check_command = nrpe
+ vars.nrpe_command = "check_disk"
- vars.pnp_check_arg1 = "!$nrpe_command$"
- }
+ vars.pnp_check_arg1 = "!$nrpe_command$"
+}
+```
If there are warnings about unresolved macros, make sure to specify a default value for `vars.pnp_check_arg1` inside the
In order to enable the `ExternalCommandListener` configuration use the
following command and restart Icinga 2 afterwards:
- # icinga2 feature enable command
+```
+# icinga2 feature enable command
+```
Icinga 2 creates the command pipe file as `/var/run/icinga2/cmd/icinga2.cmd`
using the default configuration.
Icinga 2 through the external command pipe, for example for rescheduling
a forced service check:
- # /bin/echo "[`date +%s`] SCHEDULE_FORCED_SVC_CHECK;localhost;ping4;`date +%s`" >> /var/run/icinga2/cmd/icinga2.cmd
+```
+# /bin/echo "[`date +%s`] SCHEDULE_FORCED_SVC_CHECK;localhost;ping4;`date +%s`" >> /var/run/icinga2/cmd/icinga2.cmd
- # tail -f /var/log/messages
+# tail -f /var/log/messages
- Oct 17 15:01:25 icinga-server icinga2: Executing external command: [1382014885] SCHEDULE_FORCED_SVC_CHECK;localhost;ping4;1382014885
- Oct 17 15:01:25 icinga-server icinga2: Rescheduling next check for service 'ping4'
+Oct 17 15:01:25 icinga-server icinga2: Executing external command: [1382014885] SCHEDULE_FORCED_SVC_CHECK;localhost;ping4;1382014885
+Oct 17 15:01:25 icinga-server icinga2: Rescheduling next check for service 'ping4'
+```
A list of currently supported external commands can be found [here](24-appendix.md#external-commands-list-detail).
feature allows you to define the output template format for host and services helped
with Icinga 2 runtime vars.
- host_format_template = "DATATYPE::HOSTPERFDATA\tTIMET::$icinga.timet$\tHOSTNAME::$host.name$\tHOSTPERFDATA::$host.perfdata$\tHOSTCHECKCOMMAND::$host.check_command$\tHOSTSTATE::$host.state$\tHOSTSTATETYPE::$host.state_type$"
- service_format_template = "DATATYPE::SERVICEPERFDATA\tTIMET::$icinga.timet$\tHOSTNAME::$host.name$\tSERVICEDESC::$service.name$\tSERVICEPERFDATA::$service.perfdata$\tSERVICECHECKCOMMAND::$service.check_command$\tHOSTSTATE::$host.state$\tHOSTSTATETYPE::$host.state_type$\tSERVICESTATE::$service.state$\tSERVICESTATETYPE::$service.state_type$"
+```
+host_format_template = "DATATYPE::HOSTPERFDATA\tTIMET::$icinga.timet$\tHOSTNAME::$host.name$\tHOSTPERFDATA::$host.perfdata$\tHOSTCHECKCOMMAND::$host.check_command$\tHOSTSTATE::$host.state$\tHOSTSTATETYPE::$host.state_type$"
+service_format_template = "DATATYPE::SERVICEPERFDATA\tTIMET::$icinga.timet$\tHOSTNAME::$host.name$\tSERVICEDESC::$service.name$\tSERVICEPERFDATA::$service.perfdata$\tSERVICECHECKCOMMAND::$service.check_command$\tHOSTSTATE::$host.state$\tHOSTSTATETYPE::$host.state_type$\tSERVICESTATE::$service.state$\tSERVICESTATETYPE::$service.state_type$"
+```
The default templates are already provided with the Icinga 2 feature configuration
which can be enabled using
- # icinga2 feature enable perfdata
+```
+# icinga2 feature enable perfdata
+```
By default all performance data files are rotated in a 15 seconds interval into
the `/var/spool/icinga2/perfdata/` directory as `host-perfdata.<timestamp>` and
You can enable the feature using
- # icinga2 feature enable graphite
+```
+# icinga2 feature enable graphite
+```
By default the [GraphiteWriter](09-object-types.md#objecttype-graphitewriter) feature
expects the Graphite Carbon Cache to listen at `127.0.0.1` on TCP port `2003`.
The default prefix for hosts and services is configured using
[runtime macros](03-monitoring-basics.md#runtime-macros)like this:
- icinga2.$host.name$.host.$host.check_command$
- icinga2.$host.name$.services.$service.name$.$service.check_command$
+```
+icinga2.$host.name$.host.$host.check_command$
+icinga2.$host.name$.services.$service.name$.$service.check_command$
+```
You can customize the prefix name by using the `host_name_template` and
`service_name_template` configuration attributes.
Metric values are stored like this:
- <prefix>.perfdata.<perfdata-label>.value
+```
+<prefix>.perfdata.<perfdata-label>.value
+```
The following characters are escaped in perfdata labels:
By enabling `enable_send_thresholds` Icinga 2 automatically adds the following threshold metrics:
- <prefix>.perfdata.<perfdata-label>.min
- <prefix>.perfdata.<perfdata-label>.max
- <prefix>.perfdata.<perfdata-label>.warn
- <prefix>.perfdata.<perfdata-label>.crit
+```
+<prefix>.perfdata.<perfdata-label>.min
+<prefix>.perfdata.<perfdata-label>.max
+<prefix>.perfdata.<perfdata-label>.warn
+<prefix>.perfdata.<perfdata-label>.crit
+```
By enabling `enable_send_metadata` Icinga 2 automatically adds the following metadata metrics:
- <prefix>.metadata.current_attempt
- <prefix>.metadata.downtime_depth
- <prefix>.metadata.acknowledgement
- <prefix>.metadata.execution_time
- <prefix>.metadata.latency
- <prefix>.metadata.max_check_attempts
- <prefix>.metadata.reachable
- <prefix>.metadata.state
- <prefix>.metadata.state_type
+```
+<prefix>.metadata.current_attempt
+<prefix>.metadata.downtime_depth
+<prefix>.metadata.acknowledgement
+<prefix>.metadata.execution_time
+<prefix>.metadata.latency
+<prefix>.metadata.max_check_attempts
+<prefix>.metadata.reachable
+<prefix>.metadata.state
+<prefix>.metadata.state_type
+```
Metadata metric overview:
The following example illustrates how to configure the storage schemas for Graphite Carbon
Cache.
- [icinga2_default]
- # intervals like PNP4Nagios uses them per default
- pattern = ^icinga2\.
- retentions = 1m:2d,5m:10d,30m:90d,360m:4y
+```
+[icinga2_default]
+# intervals like PNP4Nagios uses them per default
+pattern = ^icinga2\.
+retentions = 1m:2d,5m:10d,30m:90d,360m:4y
+```
### InfluxDB Writer <a id="influxdb-writer"></a>
You can enable the feature using
- # icinga2 feature enable influxdb
+```
+# icinga2 feature enable influxdb
+```
By default the [InfluxdbWriter](09-object-types.md#objecttype-influxdbwriter) feature
expects the InfluxDB daemon to listen at `127.0.0.1` on port `8086`.
Metric values are stored like this:
- check_result.perfdata.<perfdata-label>.value
+```
+check_result.perfdata.<perfdata-label>.value
+```
The following characters are escaped in perfdata labels:
Icinga 2 automatically adds the following threshold metrics
if existing:
- check_result.perfdata.<perfdata-label>.min
- check_result.perfdata.<perfdata-label>.max
- check_result.perfdata.<perfdata-label>.warn
- check_result.perfdata.<perfdata-label>.crit
+```
+check_result.perfdata.<perfdata-label>.min
+check_result.perfdata.<perfdata-label>.max
+check_result.perfdata.<perfdata-label>.warn
+check_result.perfdata.<perfdata-label>.crit
+```
### Graylog Integration <a id="graylog-integration"></a>
You can enable the feature using
- # icinga2 feature enable gelf
+```
+# icinga2 feature enable gelf
+```
By default the `GelfWriter` object expects the GELF receiver to listen at `127.0.0.1` on TCP port `12201`.
The default `source` attribute is set to `icinga2`. You can customize that for your needs if required.
You can enable the feature using
- # icinga2 feature enable opentsdb
+```
+# icinga2 feature enable opentsdb
+```
By default the `OpenTsdbWriter` object expects the TSD to listen at
`127.0.0.1` on port `4242`.
The current naming schema is
- icinga.host.<metricname>
- icinga.service.<servicename>.<metricname>
+```
+icinga.host.<metricname>
+icinga.service.<servicename>.<metricname>
+```
for host and service checks. The tag host is always applied.
To make sure Icinga 2 writes a valid metric into OpenTSDB some characters are replaced
with `_` in the target name:
- \ (and space)
+```
+\ (and space)
+```
The resulting name in OpenTSDB might look like:
- www-01 / http-cert / response time
- icinga.http_cert.response_time
+```
+www-01 / http-cert / response time
+icinga.http_cert.response_time
+```
In addition to the performance data retrieved from the check plugin, Icinga 2 sends
internal check statistic data to OpenTSDB:
While reachable, state and state_type are metrics for the host or service the
other metrics follow the current naming schema
- icinga.check.<metricname>
+```
+icinga.check.<metricname>
+```
with the following tags
You can enable Livestatus using icinga2 feature enable:
- # icinga2 feature enable livestatus
+```
+# icinga2 feature enable livestatus
+```
After that you will have to restart Icinga 2:
- # systemctl restart icinga2
+```
+# systemctl restart icinga2
+```
By default the Livestatus socket is available in `/var/run/icinga2/cmd/livestatus`.
In order for queries and commands to work you will need to add your query user
(e.g. your web server) to the `icingacmd` group:
- # usermod -a -G icingacmd www-data
+```
+# usermod -a -G icingacmd www-data
+```
The Debian packages use `nagios` as the user and group name. Make sure to change `icingacmd` to
`nagios` if you're using Debian.
are expected to be in `/var/log/icinga2/compat`. A different path can be set using the
`compat_log_path` configuration attribute.
- # icinga2 feature enable compatlog
-
+```
+# icinga2 feature enable compatlog
+```
### Livestatus Sockets <a id="livestatus-sockets"></a>
Example using the unix socket:
- # echo -e "GET services\n" | /usr/bin/nc -U /var/run/icinga2/cmd/livestatus
+```
+# echo -e "GET services\n" | /usr/bin/nc -U /var/run/icinga2/cmd/livestatus
Example using the tcp socket listening on port `6558`:
- # echo -e 'GET services\n' | netcat 127.0.0.1 6558
-
- # cat servicegroups <<EOF
- GET servicegroups
+# echo -e 'GET services\n' | netcat 127.0.0.1 6558
- EOF
+# cat servicegroups <<EOF
+GET servicegroups
- (cat servicegroups; sleep 1) | netcat 127.0.0.1 6558
+EOF
+(cat servicegroups; sleep 1) | netcat 127.0.0.1 6558
+```
### Livestatus COMMAND Queries <a id="livestatus-command-queries"></a>
A list of available external commands and their parameters can be found [here](24-appendix.md#external-commands-list-detail)
- $ echo -e 'COMMAND <externalcommandstring>' | netcat 127.0.0.1 6558
-
+```
+$ echo -e 'COMMAND <externalcommandstring>' | netcat 127.0.0.1 6558
+```
### Livestatus Filters <a id="livestatus-filters"></a>
Example:
- GET hosts
- Filter: has_been_checked = 1
- Filter: check_type = 0
- Stats: sum execution_time
- Stats: sum latency
- Stats: sum percent_state_change
- Stats: min execution_time
- Stats: min latency
- Stats: min percent_state_change
- Stats: max execution_time
- Stats: max latency
- Stats: max percent_state_change
- OutputFormat: json
- ResponseHeader: fixed16
+```
+GET hosts
+Filter: has_been_checked = 1
+Filter: check_type = 0
+Stats: sum execution_time
+Stats: sum latency
+Stats: sum percent_state_change
+Stats: min execution_time
+Stats: min latency
+Stats: min percent_state_change
+Stats: max execution_time
+Stats: max latency
+Stats: max percent_state_change
+OutputFormat: json
+ResponseHeader: fixed16
+```
### Livestatus Output <a id="livestatus-output"></a>
Separators can be set using ASCII codes like:
- Separators: 10 59 44 124
+```
+Separators: 10 59 44 124
+```
* JSON
the `StatusDataWriter` object which dumps all configuration objects and
status updates in a regular interval.
- # icinga2 feature enable statusdata
+```
+# icinga2 feature enable statusdata
+```
If you are not using any web interface or addon which uses these files,
you can safely disable this feature.
The `CompatLogger` object can be enabled with
- # icinga2 feature enable compatlog
+```
+# icinga2 feature enable compatlog
+```
By default, the Icinga 1.x log file called `icinga.log` is located
in `/var/log/icinga2/compat`. Rotated log files are moved into
There is no feature configuration available, but it must be defined
on-demand in your Icinga 2 objects configuration.
- object CheckResultReader "reader" {
- spool_dir = "/data/check-results"
- }
-
+```
+object CheckResultReader "reader" {
+ spool_dir = "/data/check-results"
+}
+```
\ No newline at end of file
`/etc/systemd/system/icinga2.service.d/override.conf` with the following
content:
- [Service]
- Restart=always
- RestartSec=1
- StartLimitInterval=10
- StartLimitBurst=3
+```
+[Service]
+Restart=always
+RestartSec=1
+StartLimitInterval=10
+StartLimitBurst=3
+```
Using the watchdog can also help with monitoring Icinga 2, to activate and use it add the following to the override:
- WatchdogSec=30s
+```
+WatchdogSec=30s
+```
This way systemd will kill Icinga 2 if does not notify for over 30 seconds, a timout of less than 10 seconds is not
recommended. When the watchdog is activated, `Restart=` can be set to `watchdog` to restart Icinga 2 in the case of a
Icinga 2 features an object-based configuration format. You can define new
objects using the `object` keyword:
- object Host "host1.example.org" {
- display_name = "host1"
+```
+object Host "host1.example.org" {
+ display_name = "host1"
- address = "192.168.0.1"
- address6 = "2001:db8:1234::42"
- }
+ address = "192.168.0.1"
+ address6 = "2001:db8:1234::42"
+}
+```
In general you need to write each statement on a new line. Expressions started
with `{`, `(` and `[` extend until the matching closing character and can be broken
Alternatively you can write multiple statements on a single line by separating
them with a semicolon:
- object Host "host1.example.org" {
- display_name = "host1"
+```
+object Host "host1.example.org" {
+ display_name = "host1"
- address = "192.168.0.1"; address6 = "2001:db8:1234::42"
- }
+ address = "192.168.0.1"; address6 = "2001:db8:1234::42"
+}
+```
Each object is uniquely identified by its type (`Host`) and name
(`host1.example.org`). Some types have composite names, e.g. the
Example:
- 27.3
+```
+27.3
+```
### Duration Literals <a id="duration-literals"></a>
Example:
- 2.5m
+```
+2.5m
+```
Supported suffixes include ms (milliseconds), s (seconds), m (minutes),
h (hours) and d (days).
Example:
- "Hello World!"
+```
+"Hello World!"
+```
#### String Literals Escape Sequences <a id="string-literals-escape-sequences"></a>
Example:
- {{{This
- is
- a multi-line
- string.}}}
+```
+{{{This
+is
+a multi-line
+string.}}}
+```
Unlike in ordinary strings special characters do not have to be escaped
in multi-line string literals.
Example:
- {
- address = "192.168.0.1"
- port = 443
- }
+```
+{
+ address = "192.168.0.1"
+ port = 443
+}
+```
Identifiers may not contain certain characters (e.g. space) or start
with certain characters (e.g. digits). If you want to use a dictionary
Example:
- [ "hello", 42 ]
+```
+[ "hello", 42 ]
+```
An array may simultaneously contain values of different types, such as
strings and numbers.
A reference to a value can be obtained using the `&` operator. The `*` operator can be used
to dereference a reference:
- var value = "Hello!"
- var p = &value /* p refers to value */
- *p = "Hi!"
- log(value) // Prints "Hi!" because the variable was changed
+```
+var value = "Hello!"
+var p = &value /* p refers to value */
+*p = "Hi!"
+log(value) // Prints "Hi!" because the variable was changed
+```
### Namespaces <a id="namespaces"></a>
Namespaces can be used to organize variables and functions. They are used to avoid name conflicts. The `namespace`
keyword is used to create a new namespace:
- namespace Utils {
- function calculate() {
- return 2 + 2
- }
+```
+namespace Utils {
+ function calculate() {
+ return 2 + 2
}
+}
+```
The namespace is made available as a global variable which has the namespace's name (e.g. `Utils`):
- Utils.calculate()
+```
+Utils.calculate()
+```
The `using` keyword can be used to make all attributes in a namespace available to a script without having to
explicitly specify the namespace's name for each access:
- using Utils
- calculate()
+```
+using Utils
+calculate()
+```
The `using` keyword only has an effect for the current file and only for code that follows the keyword:
- calculate() // This will not work.
- using Utils
+```
+calculate() // This will not work.
+using Utils
+```
The following namespaces are automatically imported as if by using the `using` keyword:
Functions can be called using the `()` operator:
- const MyGroups = [ "test1", "test" ]
+```
+const MyGroups = [ "test1", "test" ]
- {
- check_interval = len(MyGroups) * 1m
- }
+{
+ check_interval = len(MyGroups) * 1m
+}
+```
A list of available functions is available in the [Library Reference](18-library-reference.md#library-reference) chapter.
Example:
- {
- a = 5
- a = 7
- }
+```
+{
+ a = 5
+ a = 7
+}
+```
In this example `a` has the value `7` after both instructions are executed.
The += operator is a shortcut. The following expression:
- {
- a = [ "hello" ]
- a += [ "world" ]
- }
+```
+{
+ a = [ "hello" ]
+ a += [ "world" ]
+}
+```
is equivalent to:
- {
- a = [ "hello" ]
- a = a + [ "world" ]
- }
+```
+{
+ a = [ "hello" ]
+ a = a + [ "world" ]
+}
+```
### Operator -= <a id="operator-substractive-assignment"></a>
The -= operator is a shortcut. The following expression:
- {
- a = 10
- a -= 5
- }
+```
+{
+ a = 10
+ a -= 5
+}
+```
is equivalent to:
- {
- a = 10
- a = a - 5
- }
+```
+{
+ a = 10
+ a = a - 5
+}
+```
### Operator \*= <a id="operator-multiply-assignment"></a>
The *= operator is a shortcut. The following expression:
- {
- a = 60
- a *= 5
- }
+```
+{
+ a = 60
+ a *= 5
+}
+```
is equivalent to:
- {
- a = 60
- a = a * 5
- }
+```
+{
+ a = 60
+ a = a * 5
+}
+```
### Operator /= <a id="operator-dividing-assignment"></a>
The /= operator is a shortcut. The following expression:
- {
- a = 300
- a /= 5
- }
+```
+{
+ a = 300
+ a /= 5
+}
+```
is equivalent to:
- {
- a = 300
- a = a / 5
- }
+```
+{
+ a = 300
+ a = a / 5
+}
+```
## Indexer <a id="indexer"></a>
Example:
- {
- hello.key = "world"
- }
+```
+{
+ hello.key = "world"
+}
+```
Example (alternative syntax):
- {
- hello["key"] = "world"
- }
+```
+{
+ hello["key"] = "world"
+}
+```
This is equivalent to writing:
- {
- hello += {
- key = "world"
- }
- }
+```
+{
+ hello += {
+ key = "world"
+ }
+}
+```
If the `hello` attribute does not already have a value, it is automatically initialized to an empty dictionary.
Example:
- template Host "default-host" {
- vars.colour = "red"
- }
+```
+template Host "default-host" {
+ vars.colour = "red"
+}
- template Host "test-host" {
- import "default-host"
+template Host "test-host" {
+ import "default-host"
- vars.colour = "blue"
- }
+ vars.colour = "blue"
+}
- object Host "localhost" {
- import "test-host"
+object Host "localhost" {
+ import "test-host"
- address = "127.0.0.1"
- address6 = "::1"
- }
+ address = "127.0.0.1"
+ address6 = "::1"
+}
+```
The `default-host` and `test-host` objects are marked as templates
using the `template` keyword. Unlike ordinary objects templates are not
Default templates which are automatically imported into all object definitions
can be specified using the `default` keyword:
- template CheckCommand "plugin-check-command" default {
- // ...
- }
+```
+template CheckCommand "plugin-check-command" default {
+ // ...
+}
+```
Default templates are imported before any other user-specified statement in an
object definition is evaluated.
Global constants can be set using the `const` keyword:
- const VarName = "some value"
+```
+const VarName = "some value"
+```
Once defined a constant can be accessed from any file. Constants cannot be changed
once they are set.
The `apply` keyword can be used to create new objects which are associated with
another group of objects.
- apply Service "ping" to Host {
- import "generic-service"
+```
+apply Service "ping" to Host {
+ import "generic-service"
- check_command = "ping4"
+ check_command = "ping4"
- assign where host.name == "localhost"
- }
+ assign where host.name == "localhost"
+}
+```
In this example the `assign where` condition is a boolean expression which is
evaluated for all objects of type `Host` and a new service with name "ping"
[Apply](17-language-reference.md#apply) rules can be extended with the
[for loop](17-language-reference.md#for-loops) keyword.
- apply Service "prefix-" for (key => value in host.vars.dictionary) to Host {
- import "generic-service"
-
- check_command = "ping4"
- vars.host_value = value
- }
+```
+apply Service "prefix-" for (key => value in host.vars.dictionary) to Host {
+ import "generic-service"
+ check_command = "ping4"
+ vars.host_value = value
+}
+```
Any valid config attribute can be accessed using the `host` and `service`
variables. The attribute must be of the Array or Dictionary type. In this example
Group objects can be assigned to specific member objects using the `assign where`
and `ignore where` conditions.
- object HostGroup "linux-servers" {
- display_name = "Linux Servers"
+```
+object HostGroup "linux-servers" {
+ display_name = "Linux Servers"
- assign where host.vars.os == "Linux"
- }
+ assign where host.vars.os == "Linux"
+}
+```
In this example the `assign where` condition is a boolean expression which is evaluated
for all objects of the type `Host`. Each matching host is added as member to the host group
Example:
- /*
- This is a comment.
- */
- object Host "localhost" {
- check_interval = 30 // this is also a comment.
- retry_interval = 15 # yet another comment
- }
+```
+/*
+ This is a comment.
+ */
+object Host "localhost" {
+ check_interval = 30 // this is also a comment.
+ retry_interval = 15 # yet another comment
+}
+```
## Includes <a id="includes"></a>
Example:
- include "some/other/file.conf"
- include "conf.d/*.conf"
+```
+include "some/other/file.conf"
+include "conf.d/*.conf"
+```
Wildcard includes are not recursive.
Icinga also supports include search paths similar to how they work in a
C/C++ compiler:
- include <itl>
+```
+include <itl>
+```
Note the use of angle brackets instead of double quotes. This causes the
config compiler to search the include search paths for the specified
Example:
- include_recursive "conf.d", "*.conf"
- include_recursive "templates"
+```
+include_recursive "conf.d", "*.conf"
+include_recursive "templates"
+```
The first parameter specifies the directory from which files should be
recursively included.
Example:
- include_zones "etc", "zones.d", "*.conf"
- include_zones "puppet", "puppet-zones"
+```
+include_zones "etc", "zones.d", "*.conf"
+include_zones "puppet", "puppet-zones"
+```
The first parameter specifies a tag name for this directive. Each `include_zones`
invocation should use a unique tag name. When copying the zones' configuration
Example:
- function multiply(a, b) {
- return a * b
- }
+```
+function multiply(a, b) {
+ return a * b
+}
+```
When encountering the `return` keyword further execution of the function is terminated and
the specified value is supplied to the caller of the function:
- log(multiply(3, 5))
+```
+log(multiply(3, 5))
+```
In this example the `multiply` function we declared earlier is invoked with two arguments (3 and 5).
The function computes the product of those arguments and makes the result available to the
last expression which was performed by the function. For example, we could have also written our
`multiply` function like this:
- function multiply(a, b) {
- a * b
- }
+```
+function multiply(a, b) {
+ a * b
+}
+```
Anonymous functions can be created by omitting the name in the function definition. The
resulting function object can be used like any other value:
- var fn = function() { 3 }
+```
+var fn = function() { 3 }
- fn() /* Returns 3 */
+fn() /* Returns 3 */
+```
## Lambda Expressions <a id="lambdas"></a>
Example:
- f = (x) => x * x
+```
+f = (x) => x * x
+```
Multiple statements can be used by putting the function body into braces:
- f = (x) => {
- log("Lambda called")
- x * x
- }
+```
+f = (x) => {
+ log("Lambda called")
+ x * x
+}
+```
Just like with ordinary functions the return value is the value of the last statement.
For lambdas which take exactly one argument the braces around the arguments can be omitted:
- f = x => x * x
+```
+f = x => x * x
+```
## Abbreviated Lambda Syntax <a id="nullary-lambdas"></a>
Example:
- f = {{ 3 }}
+```
+f = {{ 3 }}
+```
This creates a new function which returns the value 3.
The local scope contains variables which only exist during the invocation of the current function,
object or apply statement. Local variables can be declared using the `var` keyword:
- function multiply(a, b) {
- var temp = a * b
- return temp
- }
+```
+function multiply(a, b) {
+ var temp = a * b
+ return temp
+}
+```
Each time the `multiply` function is invoked a new `temp` variable is used which is in no way
related to previous invocations of the function.
The `this` scope refers to the current object which the function or object/apply statement
operates on.
- object Host "localhost" {
- check_interval = 5m
- }
+```
+object Host "localhost" {
+ check_interval = 5m
+}
+```
In this example the `this` scope refers to the "localhost" object. The `check_interval` attribute
is set for this particular host.
You can explicitly access the `this` scope using the `this` keyword:
- object Host "localhost" {
- var check_interval = 5m
-
- /* This explicitly specifies that the attribute should be set
- * for the host, if we had omitted `this.` the (poorly named)
- * local variable `check_interval` would have been modified instead.
- */
- this.check_interval = 1m
- }
-
+```
+object Host "localhost" {
+ var check_interval = 5m
+
+ /* This explicitly specifies that the attribute should be set
+ * for the host, if we had omitted `this.` the (poorly named)
+ * local variable `check_interval` would have been modified instead.
+ */
+ this.check_interval = 1m
+}
+```
Similarly the keywords `locals` and `globals` are available to access the local and global scope.
Functions also have a `this` scope. However unlike for object/apply statements the `this` scope for
a function is set to whichever object was used to invoke the function. Here's an example:
- hm = {
- h_word = null
+```
+ hm = {
+ h_word = null
- function init(word) {
- h_word = word
- }
- }
+ function init(word) {
+ h_word = word
+ }
+ }
- /* Let's invoke the init() function */
- hm.init("hello")
+ /* Let's invoke the init() function */
+ hm.init("hello")
+```
We're using `hm.init` to invoke the function which causes the value of `hm` to become the `this`
scope for this function call.
In order to access variables which are defined in the outer scope the `use` keyword can be used:
- function MakeHelloFunction(name) {
- return function() use(name) {
- log("Hello, " + name)
- }
- }
+```
+function MakeHelloFunction(name) {
+ return function() use(name) {
+ log("Hello, " + name)
+ }
+}
+```
In this case a new variable `name` is created inside the inner function's scope which has the
value of the `name` function argument.
Alternatively a different value for the inner variable can be specified:
- function MakeHelloFunction(name) {
- return function() use (greeting = "Hello, " + name) {
- log(greeting)
- }
- }
+```
+function MakeHelloFunction(name) {
+ return function() use (greeting = "Hello, " + name) {
+ log(greeting)
+ }
+}
+```
## Conditional Statements <a id="conditional-statements"></a>
Example:
- a = 3
+```
+a = 3
- if (a < 5) {
- a *= 7
- } else if (a > 10) {
- a *= 5
- } else {
- a *= 2
- }
+if (a < 5) {
+ a *= 7
+} else if (a > 10) {
+ a *= 5
+} else {
+ a *= 2
+}
+```
An if/else construct can also be used in place of any other value. The value of an if/else statement
is the value of the last statement which was evaluated for the branch which was taken:
- a = if (true) {
- log("Taking the 'true' branch")
- 7 * 3
- } else {
- log("Taking the 'false' branch")
- 9
- }
+```
+a = if (true) {
+ log("Taking the 'true' branch")
+ 7 * 3
+} else {
+ log("Taking the 'false' branch")
+ 9
+}
+```
This example prints the log message "Taking the 'true' branch" and the `a` variable is set to 21 (7 * 3).
Example:
- var num = 5
+```
+var num = 5
- while (num > 5) {
- log("Test")
- num -= 1
- }
+while (num > 5) {
+ log("Test")
+ num -= 1
+}
+```
The `continue` and `break` keywords can be used to control how the loop is executed: The `continue` keyword
skips over the remaining expressions for the loop body and begins the next loop evaluation. The `break` keyword
Example:
- var list = [ "a", "b", "c" ]
+```
+var list = [ "a", "b", "c" ]
- for (var item in list) {
- log("Item: " + item)
- }
+for (var item in list) {
+ log("Item: " + item)
+}
+```
The loop body is evaluated once for each item in the array. The variable `item` is declared as a local
variable just as if the `var` keyword had been used.
Iterating over dictionaries can be accomplished in a similar manner:
- var dict = { a = 3, b = 7 }
+```
+var dict = { a = 3, b = 7 }
- for (var key => var value in dict) {
- log("Key: " + key + ", Value: " + value)
- }
+for (var key => var value in dict) {
+ log("Key: " + key + ", Value: " + value)
+}
+```
The `continue` and `break` keywords can be used to control how the loop is executed: The `continue` keyword
skips over the remaining expressions for the loop body and begins the next loop evaluation. The `break` keyword
Example:
- var pd = PerfdataValue()
- pd.label = "test"
- pd.value = 10
+```
+var pd = PerfdataValue()
+pd.label = "test"
+pd.value = 10
+```
You can also try to convert an existing value to another type by specifying it as an argument for the constructor call.
Example:
- var s = String(3) /* Sets s to "3". */
+```
+var s = String(3) /* Sets s to "3". */
+```
## Throwing Exceptions <a id="throw"></a>
Example:
- throw "An error occurred."
+```
+throw "An error occurred."
+```
## Handling Exceptions <a id="try-except"></a>
Example:
- try {
- throw "Test"
+```
+try {
+ throw "Test"
- log("This statement won't get executed.")
- } except {
- log("An error occurred in the try clause.")
- }
+ log("This statement won't get executed.")
+} except {
+ log("An error occurred in the try clause.")
+}
+```
## Breakpoints <a id="breakpoints"></a>
All values have a static type. The `typeof` function can be used to determine the type of a value:
- typeof(3) /* Returns an object which represents the type for numbers */
+```
+typeof(3) /* Returns an object which represents the type for numbers */
+```
The following built-in types are available:
Each type has an associated type object which describes the type's semantics. These
type objects are made available using global variables which match the type's name:
- /* This logs 'true' */
- log(typeof(3) == Number)
+```
+/* This logs 'true' */
+log(typeof(3) == Number)
+```
The type object's `prototype` property can be used to find out which methods a certain type
supports:
- /* This returns: ["contains","find","len","lower","replace","reverse","split","substr","to_string","trim","upper"] */
- keys(String.prototype)
+```
+/* This returns: ["contains","find","len","lower","replace","reverse","split","substr","to_string","trim","upper"] */
+keys(String.prototype)
+```
Additional documentation on type methods is available in the
[library reference](18-library-reference.md#library-reference).
Example:
- log("Hello from '" + current_filename + "' in line " + current_line)
+```
+log("Hello from '" + current_filename + "' in line " + current_line)
+```
## Reserved Keywords <a id="reserved-keywords"></a>
These keywords are reserved and must not be used as constants or custom attributes.
- object
- template
- include
- include_recursive
- include_zones
- library
- null
- true
- false
- const
- var
- this
- globals
- locals
- use
- default
- ignore_on_error
- current_filename
- current_line
- apply
- to
- where
- import
- assign
- ignore
- function
- return
- break
- continue
- for
- if
- else
- while
- throw
- try
- except
- in
- using
- namespace
-
+```
+object
+template
+include
+include_recursive
+include_zones
+library
+null
+true
+false
+const
+var
+this
+globals
+locals
+use
+default
+ignore_on_error
+current_filename
+current_line
+apply
+to
+where
+import
+assign
+ignore
+function
+return
+break
+continue
+for
+if
+else
+while
+throw
+try
+except
+in
+using
+namespace
+```
You can escape reserved keywords using the `@` character. The following example
tries to set `vars.include` which references a reserved keyword and generates
an error:
- [2014-09-15 17:24:00 +0200] critical/config: Location:
- /etc/icinga2/conf.d/hosts/localhost.conf(13): vars.sla = "24x7"
- /etc/icinga2/conf.d/hosts/localhost.conf(14):
- /etc/icinga2/conf.d/hosts/localhost.conf(15): vars.include = "some cmdb export field"
- ^^^^^^^
- /etc/icinga2/conf.d/hosts/localhost.conf(16): }
- /etc/icinga2/conf.d/hosts/localhost.conf(17):
+```
+[2014-09-15 17:24:00 +0200] critical/config: Location:
+/etc/icinga2/conf.d/hosts/localhost.conf(13): vars.sla = "24x7"
+/etc/icinga2/conf.d/hosts/localhost.conf(14):
+/etc/icinga2/conf.d/hosts/localhost.conf(15): vars.include = "some cmdb export field"
+ ^^^^^^^
+/etc/icinga2/conf.d/hosts/localhost.conf(16): }
+/etc/icinga2/conf.d/hosts/localhost.conf(17):
- Config error: in /etc/icinga2/conf.d/hosts/localhost.conf: 15:8-15:14: syntax error, unexpected include (T_INCLUDE), expecting T_IDENTIFIER
- [2014-09-15 17:24:00 +0200] critical/config: 1 errors, 0 warnings.
+Config error: in /etc/icinga2/conf.d/hosts/localhost.conf: 15:8-15:14: syntax error, unexpected include (T_INCLUDE), expecting T_IDENTIFIER
+[2014-09-15 17:24:00 +0200] critical/config: 1 errors, 0 warnings.
+```
You can escape the `include` keyword by prefixing it with an additional `@` character:
- object Host "localhost" {
- import "generic-host"
+```
+object Host "localhost" {
+ import "generic-host"
- address = "127.0.0.1"
- address6 = "::1"
+ address = "127.0.0.1"
+ address6 = "::1"
- vars.os = "Linux"
- vars.sla = "24x7"
+ vars.os = "Linux"
+ vars.sla = "24x7"
- vars.@include = "some cmdb export field"
- }
+ vars.@include = "some cmdb export field"
+}
+```
\ No newline at end of file
Signature:
- function regex(pattern, value, mode)
+```
+function regex(pattern, value, mode)
+```
Returns true if the regular expression `pattern` matches the `value`, false otherwise.
The `value` can be of the type [String](18-library-reference.md#string-type) or [Array](18-library-reference.md#array-type) (which
Example for string values:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => host.vars.os_type = "Linux/Unix"
- null
- <2> => regex("^Linux", host.vars.os_type)
- true
- <3> => regex("^Linux$", host.vars.os_type)
- false
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => host.vars.os_type = "Linux/Unix"
+null
+<2> => regex("^Linux", host.vars.os_type)
+true
+<3> => regex("^Linux$", host.vars.os_type)
+false
+```
Example for an array of string values:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => host.vars.databases = [ "db-prod1", "db-prod2", "db-dev" ]
- null
- <2> => regex("^db-prod\\d+", host.vars.databases, MatchAny)
- true
- <3> => regex("^db-prod\\d+", host.vars.databases, MatchAll)
- false
-
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => host.vars.databases = [ "db-prod1", "db-prod2", "db-dev" ]
+null
+<2> => regex("^db-prod\\d+", host.vars.databases, MatchAny)
+true
+<3> => regex("^db-prod\\d+", host.vars.databases, MatchAll)
+false
+```
### match <a id="global-functions-match"></a>
Signature:
- function match(pattern, text, mode)
+```
+function match(pattern, text, mode)
+```
Returns true if the wildcard (`?*`) `pattern` matches the `value`, false otherwise.
The `value` can be of the type [String](18-library-reference.md#string-type) or [Array](18-library-reference.md#array-type) (which
Example for string values:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => var name = "db-prod-sfo-657"
- null
- <2> => match("*prod-sfo*", name)
- true
- <3> => match("*-dev-*", name)
- false
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => var name = "db-prod-sfo-657"
+null
+<2> => match("*prod-sfo*", name)
+true
+<3> => match("*-dev-*", name)
+false
+```
Example for an array of string values:
- $ icinga2 console
- Icinga 2 (version: v2.7.0-28)
- <1> => host.vars.application_types = [ "web-wp", "web-rt", "db-local" ]
- null
- <2> => match("web-*", host.vars.application_types, MatchAll)
- false
- <3> => match("web-*", host.vars.application_types, MatchAny)
- true
-
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0-28)
+<1> => host.vars.application_types = [ "web-wp", "web-rt", "db-local" ]
+null
+<2> => match("web-*", host.vars.application_types, MatchAll)
+false
+<3> => match("web-*", host.vars.application_types, MatchAny)
+true
+```
### cidr_match <a id="global-functions-cidr_match"></a>
Signature:
- function cidr_match(pattern, ip, mode)
+```
+function cidr_match(pattern, ip, mode)
+```
Returns true if the CIDR pattern matches the IP address, false otherwise.
Example for a single IP address:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => host.address = "192.168.56.101"
- null
- <2> => cidr_match("192.168.56.0/24", host.address)
- true
- <3> => cidr_match("192.168.56.0/26", host.address)
- false
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => host.address = "192.168.56.101"
+null
+<2> => cidr_match("192.168.56.0/24", host.address)
+true
+<3> => cidr_match("192.168.56.0/26", host.address)
+false
+```
Example for an array of IP addresses:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => host.vars.vhost_ips = [ "192.168.56.101", "192.168.56.102", "10.0.10.99" ]
- null
- <2> => cidr_match("192.168.56.0/24", host.vars.vhost_ips, MatchAll)
- false
- <3> => cidr_match("192.168.56.0/24", host.vars.vhost_ips, MatchAny)
- true
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => host.vars.vhost_ips = [ "192.168.56.101", "192.168.56.102", "10.0.10.99" ]
+null
+<2> => cidr_match("192.168.56.0/24", host.vars.vhost_ips, MatchAll)
+false
+<3> => cidr_match("192.168.56.0/24", host.vars.vhost_ips, MatchAny)
+true
+```
### range <a id="global-functions-range"></a>
Signature:
- function range(end)
- function range(start, end)
- function range(start, end, increment)
+```
+function range(end)
+function range(start, end)
+function range(start, end, increment)
+```
Returns an array of numbers in the specified range.
If you specify one parameter, the first element starts at `0`.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => range(5)
- [ 0.000000, 1.000000, 2.000000, 3.000000, 4.000000 ]
- <2> => range(2,4)
- [ 2.000000, 3.000000 ]
- <3> => range(2,10,2)
- [ 2.000000, 4.000000, 6.000000, 8.000000 ]
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => range(5)
+[ 0.000000, 1.000000, 2.000000, 3.000000, 4.000000 ]
+<2> => range(2,4)
+[ 2.000000, 3.000000 ]
+<3> => range(2,10,2)
+[ 2.000000, 4.000000, 6.000000, 8.000000 ]
+```
### len <a id="global-functions-len"></a>
Signature:
- function len(value)
+```
+function len(value)
+```
Returns the length of the value, i.e. the number of elements for an array
or dictionary, or the length of the string in bytes.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => host.groups = [ "linux-servers", "db-servers" ]
- null
- <2> => host.groups.len()
- 2.000000
- <3> => host.vars.disks["/"] = {}
- null
- <4> => host.vars.disks["/var"] = {}
- null
- <5> => host.vars.disks.len()
- 2.000000
- <6> => host.vars.os_type = "Linux/Unix"
- null
- <7> => host.vars.os_type.len()
- 10.000000
-
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => host.groups = [ "linux-servers", "db-servers" ]
+null
+<2> => host.groups.len()
+2.000000
+<3> => host.vars.disks["/"] = {}
+null
+<4> => host.vars.disks["/var"] = {}
+null
+<5> => host.vars.disks.len()
+2.000000
+<6> => host.vars.os_type = "Linux/Unix"
+null
+<7> => host.vars.os_type.len()
+10.000000
+```
### union <a id="global-functions-union"></a>
Signature:
- function union(array, array, ...)
+```
+function union(array, array, ...)
+```
Returns an array containing all unique elements from the specified arrays.
Example:
-
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => var dev_notification_groups = [ "devs", "slack" ]
- null
- <2> => var host_notification_groups = [ "slack", "noc" ]
- null
- <3> => union(dev_notification_groups, host_notification_groups)
- [ "devs", "noc", "slack" ]
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => var dev_notification_groups = [ "devs", "slack" ]
+null
+<2> => var host_notification_groups = [ "slack", "noc" ]
+null
+<3> => union(dev_notification_groups, host_notification_groups)
+[ "devs", "noc", "slack" ]
+```
### intersection <a id="global-functions-intersection"></a>
Signature:
- function intersection(array, array, ...)
+```
+function intersection(array, array, ...)
+```
Returns an array containing all unique elements which are common to all
specified arrays.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => var dev_notification_groups = [ "devs", "slack" ]
- null
- <2> => var host_notification_groups = [ "slack", "noc" ]
- null
- <3> => intersection(dev_notification_groups, host_notification_groups)
- [ "slack" ]
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => var dev_notification_groups = [ "devs", "slack" ]
+null
+<2> => var host_notification_groups = [ "slack", "noc" ]
+null
+<3> => intersection(dev_notification_groups, host_notification_groups)
+[ "slack" ]
+```
### keys <a id="global-functions-keys"></a>
Signature:
- function keys(dict)
+```
+function keys(dict)
+```
Returns an array containing the dictionary's keys.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => host.vars.disks["/"] = {}
- null
- <2> => host.vars.disks["/var"] = {}
- null
- <3> => host.vars.disks.keys()
- [ "/", "/var" ]
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => host.vars.disks["/"] = {}
+null
+<2> => host.vars.disks["/var"] = {}
+null
+<3> => host.vars.disks.keys()
+[ "/", "/var" ]
+```
### string <a id="global-functions-string"></a>
Signature:
- function string(value)
+```
+function string(value)
+```
Converts the value to a string.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => 5.to_string()
- "5"
- <2> => false.to_string()
- "false"
- <3> => "abc".to_string()
- "abc"
- <4> => [ "dev", "slack" ].to_string()
- "[ \"dev\", \"slack\" ]"
- <5> => { "/" = {}, "/var" = {} }.to_string()
- "{\n\t\"/\" = {\n\t}\n\t\"/var\" = {\n\t}\n}"
- <6> => DateTime(2016, 11, 25).to_string()
- "2016-11-25 00:00:00 +0100"
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => 5.to_string()
+"5"
+<2> => false.to_string()
+"false"
+<3> => "abc".to_string()
+"abc"
+<4> => [ "dev", "slack" ].to_string()
+"[ \"dev\", \"slack\" ]"
+<5> => { "/" = {}, "/var" = {} }.to_string()
+"{\n\t\"/\" = {\n\t}\n\t\"/var\" = {\n\t}\n}"
+<6> => DateTime(2016, 11, 25).to_string()
+"2016-11-25 00:00:00 +0100"
+```
### number <a id="global-functions-number"></a>
Signature:
- function number(value)
+```
+function number(value)
+```
Converts the value to a number.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => number(false)
- 0.000000
- <2> => number("78")
- 78.000000
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => number(false)
+0.000000
+<2> => number("78")
+78.000000
+```
### bool <a id="global-functions-bool"></a>
Signature:
- function bool(value)
+```
+function bool(value)
+```
Converts the value to a bool.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => bool(1)
- true
- <2> => bool(0)
- false
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => bool(1)
+true
+<2> => bool(0)
+false
+```
### random <a id="global-functions-random"></a>
Signature:
- function random()
+```
+function random()
+```
Returns a random value between 0 and RAND\_MAX (as defined in stdlib.h).
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => random()
- 1263171996.000000
- <2> => random()
- 108402530.000000
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => random()
+1263171996.000000
+<2> => random()
+108402530.000000
+```
### log <a id="global-functions-log"></a>
Signature:
- function log(value)
+```
+function log(value)
+```
Writes a message to the log. Non-string values are converted to a JSON string.
Signature:
- function log(severity, facility, value)
+```
+function log(severity, facility, value)
+```
Writes a message to the log. `severity` can be one of `LogDebug`, `LogNotice`,
`LogInformation`, `LogWarning`, and `LogCritical`.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => log(LogCritical, "Console", "First line")
- critical/Console: First line
- null
- <2> => var groups = [ "devs", "slack" ]
- null
- <3> => log(LogCritical, "Console", groups)
- critical/Console: ["devs","slack"]
- null
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => log(LogCritical, "Console", "First line")
+critical/Console: First line
+null
+<2> => var groups = [ "devs", "slack" ]
+null
+<3> => log(LogCritical, "Console", groups)
+critical/Console: ["devs","slack"]
+null
+```
### typeof <a id="global-functions-typeof"></a>
Signature:
- function typeof(value)
+```
+function typeof(value)
+```
Returns the [Type](18-library-reference.md#type-type) object for a value.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => typeof(3) == Number
- true
- <2> => typeof("str") == String
- true
- <3> => typeof(true) == Boolean
- true
- <4> => typeof([ 1, 2, 3]) == Array
- true
- <5> => typeof({ a = 2, b = 3 }) == Dictionary
- true
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => typeof(3) == Number
+true
+<2> => typeof("str") == String
+true
+<3> => typeof(true) == Boolean
+true
+<4> => typeof([ 1, 2, 3]) == Array
+true
+<5> => typeof({ a = 2, b = 3 }) == Dictionary
+true
+```
### get_time <a id="global-functions-get_time"></a>
Signature:
- function get_time()
+```
+function get_time()
+```
Returns the current UNIX timestamp as floating point number.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => get_time()
- 1480072135.633008
- <2> => get_time()
- 1480072140.401207
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => get_time()
+1480072135.633008
+<2> => get_time()
+1480072140.401207
+```
### parse_performance_data <a id="global-functions-parse_performance_data"></a>
Signature:
- function parse_performance_data(pd)
+```
+function parse_performance_data(pd)
+```
Parses a performance data string and returns an array describing the values.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => var pd = "'time'=1480074205.197363;;;"
- null
- <2> => parse_performance_data(pd)
- {
- counter = false
- crit = null
- label = "time"
- max = null
- min = null
- type = "PerfdataValue"
- unit = ""
- value = 1480074205.197363
- warn = null
- }
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => var pd = "'time'=1480074205.197363;;;"
+null
+<2> => parse_performance_data(pd)
+{
+ counter = false
+ crit = null
+ label = "time"
+ max = null
+ min = null
+ type = "PerfdataValue"
+ unit = ""
+ value = 1480074205.197363
+ warn = null
+}
+```
### dirname <a id="global-functions-dirname"></a>
Signature:
- function dirname(path)
+```
+function dirname(path)
+```
Returns the directory portion of the specified path.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => var path = "/etc/icinga2/scripts/xmpp-notification.pl"
- null
- <2> => dirname(path)
- "/etc/icinga2/scripts"
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => var path = "/etc/icinga2/scripts/xmpp-notification.pl"
+null
+<2> => dirname(path)
+"/etc/icinga2/scripts"
+```
### basename <a id="global-functions-basename"></a>
Signature:
- function basename(path)
+```
+function basename(path)
+```
Returns the filename portion of the specified path.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => var path = "/etc/icinga2/scripts/xmpp-notification.pl"
- null
- <2> => basename(path)
- "xmpp-notification.pl"
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => var path = "/etc/icinga2/scripts/xmpp-notification.pl"
+null
+<2> => basename(path)
+"xmpp-notification.pl"
+```
### path\_exists <a id="global-functions-path-exists"></a>
Signature:
- function path_exists(path)
+```
+function path_exists(path)
+```
Returns true if the specified path exists, false otherwise.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => var path = "/etc/icinga2/scripts/xmpp-notification.pl"
- null
- <2> => path_exists(path)
- true
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => var path = "/etc/icinga2/scripts/xmpp-notification.pl"
+null
+<2> => path_exists(path)
+true
+```
### glob <a id="global-functions-glob"></a>
Signature:
- function glob(pathSpec, type)
+```
+function glob(pathSpec, type)
+```
Returns an array containing all paths which match the
`pathSpec` argument.
of paths are matched. This can be a combination of the `GlobFile`
and `GlobDirectory` constants. The default value is `GlobFile | GlobDirectory`.
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => var pathSpec = "/etc/icinga2/conf.d/*.conf"
- null
- <2> => glob(pathSpec)
- [ "/etc/icinga2/conf.d/app.conf", "/etc/icinga2/conf.d/commands.conf", ... ]
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => var pathSpec = "/etc/icinga2/conf.d/*.conf"
+null
+<2> => glob(pathSpec)
+[ "/etc/icinga2/conf.d/app.conf", "/etc/icinga2/conf.d/commands.conf", ... ]
+```
### glob\_recursive <a id="global-functions-glob-recursive"></a>
Signature:
- function glob_recursive(path, pattern, type)
+```
+function glob_recursive(path, pattern, type)
+```
Recursively descends into the specified directory and returns an array containing
all paths which match the `pattern` argument.
of paths are matched. This can be a combination of the `GlobFile`
and `GlobDirectory` constants. The default value is `GlobFile | GlobDirectory`.
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => var path = "/etc/icinga2/zones.d/"
- null
- <2> => var pattern = "*.conf"
- null
- <3> => glob_recursive(path, pattern)
- [ "/etc/icinga2/zones.d/global-templates/templates.conf", "/etc/icinga2/zones.d/master/hosts.conf", ... ]
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => var path = "/etc/icinga2/zones.d/"
+null
+<2> => var pattern = "*.conf"
+null
+<3> => glob_recursive(path, pattern)
+[ "/etc/icinga2/zones.d/global-templates/templates.conf", "/etc/icinga2/zones.d/master/hosts.conf", ... ]
+```
### escape_shell_arg <a id="global-functions-escape_shell_arg"></a>
Signature:
- function escape_shell_arg(text)
+```
+function escape_shell_arg(text)
+```
Escapes a string for use as a single shell argument.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => escape_shell_arg("'$host.name$' '$service.name$'")
- "''\\''$host.name$'\\'' '\\''$service.name$'\\'''"
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => escape_shell_arg("'$host.name$' '$service.name$'")
+"''\\''$host.name$'\\'' '\\''$service.name$'\\'''"
+```
### escape_shell_cmd <a id="global-functions-escape_shell_cmd"></a>
Signature:
- function escape_shell_cmd(text)
+```
+function escape_shell_cmd(text)
+```
Escapes shell meta characters in a string.
Example:
- $ icinga2 console
- Icinga 2 (version: v2.7.0)
- <1> => escape_shell_cmd("/bin/echo 'shell test' $ENV")
- "/bin/echo 'shell test' \\$ENV"
+```
+$ icinga2 console
+Icinga 2 (version: v2.7.0)
+<1> => escape_shell_cmd("/bin/echo 'shell test' $ENV")
+"/bin/echo 'shell test' \\$ENV"
+```
### escape_create_process_arg <a id="global-functions-escape_create_process_arg"></a>
Signature:
- function escape_create_process_arg(text)
+```
+function escape_create_process_arg(text)
+```
Escapes a string for use as an argument for CreateProcess(). Windows only.
Signature:
- function sleep(interval)
+```
+function sleep(interval)
+```
Sleeps for the specified amount of time (in seconds).
Signature:
- function get_check_command(name);
+```
+function get_check_command(name);
+```
Returns the CheckCommand object with the specified name, or `null` if no such CheckCommand object exists.
Signature:
- function get_event_command(name);
+```
+function get_event_command(name);
+```
Returns the EventCommand object with the specified name, or `null` if no such EventCommand object exists.
Signature:
- function get_notification_command(name);
+```
+function get_notification_command(name);
+```
Returns the NotificationCommand object with the specified name, or `null` if no such NotificationCommand object exists.
Signature:
- function get_host(host_name);
+```
+function get_host(host_name);
+```
Returns the Host object with the specified name, or `null` if no such Host object exists.
Signature:
- function get_service(host_name, service_name);
- function get_service(host, service_name);
+```
+function get_service(host_name, service_name);
+function get_service(host, service_name);
+```
Returns the Service object with the specified host name or object and service name pair,
or `null` if no such Service object exists.
Signature:
- function get_services(host_name);
- function get_services(host);
+```
+function get_services(host_name);
+function get_services(host);
+```
Returns an [array](17-language-reference.md#array) of service objects for the specified host name or object,
or `null` if no such host object exists.
Signature:
- function get_user(name);
+```
+function get_user(name);
+```
Returns the User object with the specified name, or `null` if no such User object exists.
Signature:
- function get_host_group(name);
+```
+function get_host_group(name);
+```
Returns the HostGroup object with the specified name, or `null` if no such HostGroup object exists.
Signature:
- function get_service_group(name);
+```
+function get_service_group(name);
+```
Returns the ServiceGroup object with the specified name, or `null` if no such ServiceGroup object exists.
Signature:
- function get_user_group(name);
+```
+function get_user_group(name);
+```
Returns the UserGroup object with the specified name, or `null` if no such UserGroup object exists.
Signature:
- function get_time_period(name);
+```
+function get_time_period(name);
+```
Returns the TimePeriod object with the specified name, or `null` if no such TimePeriod object exists.
Signature:
- function get_object(type, name);
+```
+function get_object(type, name);
+```
Returns the object with the specified type and name, or `null` if no such object exists. `type` must refer
to a type object.
Signature:
- function get_objects(type);
+```
+function get_objects(type);
+```
Returns an array of objects whose type matches the specified type. `type` must refer
to a type object.
Signature:
- function abs(x);
+```
+function abs(x);
+```
Returns the absolute value of `x`.
Signature:
- function acos(x);
+```
+function acos(x);
+```
Returns the arccosine of `x`.
Signature:
- function asin(x);
+```
+function asin(x);
+```
Returns the arcsine of `x`.
Signature:
- function atan(x);
+```
+function atan(x);
+```
Returns the arctangent of `x`.
Signature:
- function atan2(y, x);
-
+```
+function atan2(y, x);
+```
Returns the arctangent of the quotient of `y` and `x`.
### Math.ceil <a id="math-ceil"></a>
Signature:
- function ceil(x);
+```
+function ceil(x);
+```
Returns the smallest integer value not less than `x`.
Signature:
- function cos(x);
+```
+function cos(x);
+```
Returns the cosine of `x`.
Signature:
- function exp(x);
+```
+function exp(x);
+```
Returns E raised to the `x`th power.
Signature:
- function floor(x);
+```
+function floor(x);
+```
Returns the largest integer value not greater than `x`.
Signature:
- function isinf(x);
+```
+function isinf(x);
+```
Returns whether `x` is infinite.
Signature:
- function isnan(x);
+```
+function isnan(x);
+```
Returns whether `x` is NaN (not-a-number).
Signature:
- function log(x);
+```
+function log(x);
+```
Returns the natural logarithm of `x`.
Signature:
- function max(...);
+```
+function max(...);
+```
Returns the largest argument. A variable number of arguments can be specified.
If no arguments are given, -Infinity is returned.
Signature:
- function min(...);
+```
+function min(...);
+```
Returns the smallest argument. A variable number of arguments can be specified.
If no arguments are given, +Infinity is returned.
Signature:
- function pow(x, y);
+```
+function pow(x, y);
+```
Returns `x` raised to the `y`th power.
Signature:
- function random();
+```
+function random();
+```
Returns a pseudo-random number between 0 and 1.
Signature:
- function round(x);
+```
+function round(x);
+```
Returns `x` rounded to the nearest integer value.
Signature:
- function sign(x);
+```
+function sign(x);
+```
Returns -1 if `x` is negative, 1 if `x` is positive
and 0 if `x` is 0.
Signature:
- function sin(x);
+```
+function sin(x);
+```
Returns the sine of `x`.
Signature:
- function sqrt(x);
+```
+function sqrt(x);
+```
Returns the square root of `x`.
Signature:
- function tan(x);
+```
+function tan(x);
+```
Returns the tangent of `x`.
Signature:
- function encode(x);
+```
+function encode(x);
+```
Encodes an arbitrary value into JSON.
Signature:
- function decode(x);
+```
+function decode(x);
+```
Decodes a JSON string.
Signature:
- function to_string();
+```
+function to_string();
+```
The `to_string` method returns a string representation of the number.
Example:
- var example = 7
+```
+var example = 7
example.to_string() /* Returns "7" */
+```
## Boolean type <a id="boolean-type"></a>
Signature:
- function to_string();
+```
+function to_string();
+```
The `to_string` method returns a string representation of the boolean value.
Example:
- var example = true
+```
+var example = true
example.to_string() /* Returns "true" */
+```
## String type <a id="string-type"></a>
Signature:
- function find(str, start);
+```
+function find(str, start);
+```
Returns the zero-based index at which the string `str` was found in the string. If the string
was not found, -1 is returned. `start` specifies the zero-based index at which `find` should
Example:
- "Hello World".find("World") /* Returns 6 */
+```
+"Hello World".find("World") /* Returns 6 */
+```
### String#contains <a id="string-contains"></a>
Signature:
- function contains(str);
+```
+function contains(str);
+```
Returns `true` if the string `str` was found in the string. If the string
was not found, `false` is returned. Use [find](18-library-reference.md#string-find)
Example:
- "Hello World".contains("World") /* Returns true */
+```
+"Hello World".contains("World") /* Returns true */
+```
### String#len <a id="string-len"></a>
Signature
- function len();
+```
+function len();
+```
Returns the length of the string in bytes. Note that depending on the encoding type of the string
this is not necessarily the number of characters.
Example:
- "Hello World".len() /* Returns 11 */
+```
+"Hello World".len() /* Returns 11 */
+```
### String#lower <a id="string-lower"></a>
Signature:
- function lower();
+```
+function lower();
+```
Returns a copy of the string with all of its characters converted to lower-case.
Example:
- "Hello World".lower() /* Returns "hello world" */
+```
+"Hello World".lower() /* Returns "hello world" */
+```
### String#upper <a id="string-upper"></a>
Signature:
- function upper();
+```
+function upper();
+```
Returns a copy of the string with all of its characters converted to upper-case.
Example:
- "Hello World".upper() /* Returns "HELLO WORLD" */
+```
+"Hello World".upper() /* Returns "HELLO WORLD" */
+```
### String#replace <a id="string-replace"></a>
Signature:
- function replace(search, replacement);
+```
+function replace(search, replacement);
+```
Returns a copy of the string with all occurences of the string specified in `search` replaced
with the string specified in `replacement`.
Signature:
- function split(delimiters);
+```
+function split(delimiters);
+```
Splits a string into individual parts and returns them as an array. The `delimiters` argument
specifies the characters which should be used as delimiters between parts.
Example:
- "x-7,y".split("-,") /* Returns [ "x", "7", "y" ] */
+```
+"x-7,y".split("-,") /* Returns [ "x", "7", "y" ] */
+```
### String#substr <a id="string-substr"></a>
Signature:
- function substr(start, len);
+```
+function substr(start, len);
+```
Returns a part of a string. The `start` argument specifies the zero-based index at which the part begins.
The optional `len` argument specifies the length of the part ("until the end of the string" if omitted).
Example:
- "Hello World".substr(6) /* Returns "World" */
+```
+"Hello World".substr(6) /* Returns "World" */
+```
### String#to_string <a id="string-to_string"></a>
Signature:
- function to_string();
+```
+function to_string();
+```
Returns a copy of the string.
Signature:
- function reverse();
+```
+function reverse();
+```
Returns a copy of the string in reverse order.
Signature:
- function trim();
+```
+function trim();
+```
Removes trailing whitespaces and returns the string.
Signature:
- function clone();
+```
+ function clone();
+```
Returns a copy of the object. Note that for object elements which are
reference values (e.g. objects such as arrays or dictionaries) the entire
Signature:
- function to_string();
+```
+function to_string();
+```
Returns a string representation for the object. Unless overridden this returns a string
of the format "Object of type '<typename>'" where <typename> is the name of the
Example:
- [ 3, true ].to_string() /* Returns "[ 3.000000, true ]" */
+```
+[ 3, true ].to_string() /* Returns "[ 3.000000, true ]" */
+```
### Object#type <a id="object-type-field"></a>
Signature:
- String type;
+String type;
Returns the object's type name. This attribute is read-only.
Example:
- get_host("localhost").type /* Returns "Host" */
+```
+get_host("localhost").type /* Returns "Host" */
+```
## Type type <a id="type-type"></a>
Signature:
- Type base;
+```
+Type base;
+```
Returns a reference to the type's base type. This attribute is read-only.
Example:
- Dictionary.base == Object /* Returns true, because the Dictionary type inherits directly from the Object type. */
+```
+Dictionary.base == Object /* Returns true, because the Dictionary type inherits directly from the Object type. */
+```
### Type#name <a id="type-name"></a>
Signature:
- String name;
+```
+String name;
+```
Returns the name of the type.
Signature:
- Object prototype;
+```
+Object prototype;
+```
Returns the prototype object for the type. When an attribute is accessed on an object that doesn't exist the prototype object is checked to see if an attribute with the requested name exists. If it does, the attribute's value is returned.
Example:
- 3.to_string() /* Even though '3' does not have a to_string property the Number type's prototype object does. */
+```
+3.to_string() /* Even though '3' does not have a to_string property the Number type's prototype object does. */
+```
## Array type <a id="array-type"></a>
Signature:
- function add(value);
+```
+function add(value);
+```
Adds a new value after the last element in the array.
Signature:
- function clear();
+```
+function clear();
+```
Removes all elements from the array.
### Array#shallow_clone <a id="array-shallow-clone"></a>
- function shallow_clone();
+```
+function shallow_clone();
+```
Returns a copy of the array. Note that for elements which are reference values (e.g. objects such
as arrays and dictionaries) only the references are copied.
Signature:
- function contains(value);
+```
+function contains(value);
+```
Returns true if the array contains the specified value, false otherwise.
Signature:
- function freeze()
+```
+function freeze()
+```
Disallows further modifications to this array. Trying to modify the array will result in an exception.
Signature:
- function len();
+```
+function len();
+```
Returns the number of elements contained in the array.
Signature:
- function remove(index);
+```
+function remove(index);
+```
Removes the element at the specified zero-based index.
Signature:
- function set(index, value);
+```
+function set(index, value);
+```
Sets the element at the zero-based index to the specified value. The `index` must refer to an element
which already exists in the array.
Signature:
- function get(index);
+```
+function get(index);
+```
Retrieves the element at the specified zero-based index.
Signature:
- function sort(less_cmp);
+```
+function sort(less_cmp);
+```
Returns a copy of the array where all items are sorted. The items are
compared using the `<` (less-than) operator. A custom comparator function
Signature:
- function join(separator);
+```
+function join(separator);
+```
Joins all elements of the array using the specified separator.
Signature:
- function reverse();
+```
+function reverse();
+```
Returns a new array with all elements of the current array in reverse order.
Signature:
- function map(func);
+```
+function map(func);
+```
Calls `func(element)` for each of the elements in the array and returns
a new array containing the return values of these function calls.
Signature:
- function reduce(func);
+```
+function reduce(func);
+```
Reduces the elements of the array into a single value by calling the provided
function `func` as `func(a, b)` repeatedly where `a` and `b` are elements of the array
Signature:
- function filter(func);
+```
+function filter(func);
+```
Returns a copy of the array containing only the elements for which `func(element)`
is true.
Signature:
- function any(func);
+```
+function any(func);
+```
Returns true if the array contains at least one element for which `func(element)`
is true, false otherwise.
Signature:
- function all(func);
+```
+function all(func);
+```
Returns true if the array contains only elements for which `func(element)`
is true, false otherwise.
Signature:
- function unique();
+```
+function unique();
+```
Returns a copy of the array with all duplicate elements removed. The original order
of the array is not preserved.
Signature:
- function shallow_clone();
+```
+function shallow_clone();
+```
Returns a copy of the dictionary. Note that for elements which are reference values (e.g. objects such
as arrays and dictionaries) only the references are copied.
Signature:
- function contains(key);
+```
+function contains(key);
+```
Returns true if a dictionary item with the specified `key` exists, false otherwise.
Signature:
- function freeze()
+```
+function freeze()
+```
Disallows further modifications to this dictionary. Trying to modify the dictionary will result in an exception.
Signature:
- function len();
+```
+function len();
+```
Returns the number of items contained in the dictionary.
Signature:
- function remove(key);
+```
+function remove(key);
+```
Removes the item with the specified `key`. Trying to remove an item which does not exist
is a no-op.
Signature:
- function clear();
+```
+function clear();
+```
Removes all items from the dictionary.
Signature:
- function set(key, value);
+```
+function set(key, value);
+```
Creates or updates an item with the specified `key` and `value`.
Signature:
- function get(key);
+```
+function get(key);
+```
Retrieves the value for the specified `key`. Returns `null` if they `key` does not exist
in the dictionary.
Signature:
- function keys();
+```
+function keys();
+```
Returns a list of keys for all items that are currently in the dictionary.
Signature:
- function values();
+```
+function values();
+```
Returns a list of values for all items that are currently in the dictionary.
Signature:
- function call(thisArg, ...);
+```
+function call(thisArg, ...);
+```
Invokes the function using an alternative `this` scope. The `thisArg` argument specifies the `this`
scope for the function. All other arguments are passed directly to the function.
Example:
- function set_x(val) {
- this.x = val
- }
+```
+function set_x(val) {
+ this.x = val
+}
- dict = {}
+dict = {}
- set_x.call(dict, 7) /* Invokes set_x using `dict` as `this` */
+set_x.call(dict, 7) /* Invokes set_x using `dict` as `this` */
+```
### Function#callv <a id="scriptfunction-callv"></a>
Signature:
- function callv(thisArg, args);
+```
+function callv(thisArg, args);
+```
Invokes the function using an alternative `this` scope. The `thisArg` argument specifies the `this`
scope for the function. The items in the `args` array are passed to the function as individual arguments.
Example:
- function set_x(val) {
- this.x = val
- }
+```
+function set_x(val) {
+ this.x = val
+}
- var dict = {}
+var dict = {}
- var args = [ 7 ]
+var args = [ 7 ]
- set_x.callv(dict, args) /* Invokes set_x using `dict` as `this` */
+set_x.callv(dict, args) /* Invokes set_x using `dict` as `this` */
+```
## DateTime type <a id="datetime-type"></a>
Signature:
- function DateTime()
- function DateTime(unixTimestamp)
- function DateTime(year, month, day)
- function DateTime(year, month, day, hours, minutes, seconds)
+```
+function DateTime()
+function DateTime(unixTimestamp)
+function DateTime(year, month, day)
+function DateTime(year, month, day, hours, minutes, seconds)
+```
Constructs a new DateTime object. When no arguments are specified for the constructor a new
DateTime object representing the current time is created.
Example:
- var d1 = DateTime() /* current time */
- var d2 = DateTime(2016, 5, 21) /* midnight April 21st, 2016 (local time) */
+```
+var d1 = DateTime() /* current time */
+var d2 = DateTime(2016, 5, 21) /* midnight April 21st, 2016 (local time) */
+```
### DateTime arithmetic <a id="datetime-arithmetic"></a>
Example:
- var delta = DateTime() - DateTime(2016, 5, 21) /* seconds since midnight April 21st, 2016 */
+```
+var delta = DateTime() - DateTime(2016, 5, 21) /* seconds since midnight April 21st, 2016 */
+```
Subtracting a number from a DateTime object yields a new DateTime object that is further in the past:
Example:
- var dt = DateTime() - 2 * 60 * 60 /* Current time minus 2 hours */
+```
+var dt = DateTime() - 2 * 60 * 60 /* Current time minus 2 hours */
+```
Adding a number to a DateTime object yields a new DateTime object that is in the future:
Example:
- var dt = DateTime() + 24 * 60 60 /* Current time plus 24 hours */
+```
+var dt = DateTime() + 24 * 60 60 /* Current time plus 24 hours */
+```
### DateTime#format <a id="datetime-format"></a>
Signature:
- function format(fmt)
+```
+function format(fmt)
+```
Returns a string representation for the DateTime object using the specified format string.
The format string may contain format conversion placeholders as specified in strftime(3).
Example:
- var s = DateTime(2016, 4, 21).format("%A") /* Sets s to "Thursday". */
+```
+var s = DateTime(2016, 4, 21).format("%A") /* Sets s to "Thursday". */
+```
### DateTime#to_string <a id="datetime-tostring"></a>
Signature:
- function to_string()
+```
+function to_string()
+```
Returns a string representation for the DateTime object. Uses a suitable default format.
Example:
- var s = DateTime(2016, 4, 21).to_string() /* Sets s to "2016-04-21 00:00:00 +0200". */
+```
+var s = DateTime(2016, 4, 21).to_string() /* Sets s to "2016-04-21 00:00:00 +0200". */
+```
You can run the Icinga 2 daemon with the `-X` (`--script-debugger`)
parameter to enable the script debugger:
- # icinga2 daemon -X
+```
+# icinga2 daemon -X
+```
When an exception occurs or the [debugger](17-language-reference.md#breakpoints)
keyword is encountered in a user script, Icinga 2 launches a console that
You can also attach the script debugger to the [configuration validation](11-cli-commands.md#config-validation):
- # icinga2 daemon -C -X
+```
+# icinga2 daemon -C -X
+```
Here is a list of common errors which can be diagnosed with the script debugger:
which expects a dictionary value for `config`, but the host custom attribute only
provides a string value:
- object Host "script-debugger-host" {
- check_command = "icinga"
+```
+object Host "script-debugger-host" {
+ check_command = "icinga"
- vars.http_vhosts["example.org"] = "192.168.1.100" // a string value
- }
+ vars.http_vhosts["example.org"] = "192.168.1.100" // a string value
+}
- apply Service for (http_vhost => config in host.vars.http_vhosts) {
- import "generic-service"
+apply Service for (http_vhost => config in host.vars.http_vhosts) {
+ import "generic-service"
- vars += config // expects a dictionary
+ vars += config // expects a dictionary
- check_command = "http"
- }
+ check_command = "http"
+}
+```
The error message on config validation will warn about the wrong value type,
but does not provide any context which objects are affected.
Enable the script debugger and run the config validation:
- # icinga2 daemon -C -X
-
- Breakpoint encountered in /etc/icinga2/conf.d/services.conf: 59:67-65:1
- Exception: Error: Error while evaluating expression: Cannot convert value of type 'String' to an object.
- Location:
- /etc/icinga2/conf.d/services.conf(62): check_command = "http"
- /etc/icinga2/conf.d/services.conf(63):
- /etc/icinga2/conf.d/services.conf(64): vars += config
- ^^^^^^^^^^^^^^
- /etc/icinga2/conf.d/services.conf(65): }
- /etc/icinga2/conf.d/services.conf(66):
- You can inspect expressions (such as variables) by entering them at the prompt.
- To leave the debugger and continue the program use "$continue".
- <1> =>
+```
+# icinga2 daemon -C -X
+
+Breakpoint encountered in /etc/icinga2/conf.d/services.conf: 59:67-65:1
+Exception: Error: Error while evaluating expression: Cannot convert value of type 'String' to an object.
+Location:
+/etc/icinga2/conf.d/services.conf(62): check_command = "http"
+/etc/icinga2/conf.d/services.conf(63):
+/etc/icinga2/conf.d/services.conf(64): vars += config
+ ^^^^^^^^^^^^^^
+/etc/icinga2/conf.d/services.conf(65): }
+/etc/icinga2/conf.d/services.conf(66):
+You can inspect expressions (such as variables) by entering them at the prompt.
+To leave the debugger and continue the program use "$continue".
+<1> =>
+```
You can print the variables `vars` and `config` to get an idea about
their values:
- <1> => vars
- null
- <2> => config
- "192.168.1.100"
- <3> =>
+```
+<1> => vars
+null
+<2> => config
+"192.168.1.100"
+<3> =>
+```
The `vars` attribute has to be a dictionary. Trying to set this attribute to a string caused
the error in our configuration example.
In order to determine the name of the host where the value of the `config` variable came from
you can inspect attributes of the service object:
- <3> => host_name
- "script-debugger-host-01"
- <4> => name
- "http"
+```
+<3> => host_name
+"script-debugger-host-01"
+<4> => name
+"http"
+```
Additionally you can view the service object attributes by printing the value of `this`.
In order to halt execution in a script you can use the `debugger` keyword:
- object Host "script-debugger-host-02" {
- check_command = "dummy"
- check_interval = 5s
-
- vars.dummy_text = {{
- var text = "Hello from " + macro("$name$")
- debugger
- return text
- }}
- }
+```
+object Host "script-debugger-host-02" {
+ check_command = "dummy"
+ check_interval = 5s
+
+ vars.dummy_text = {{
+ var text = "Hello from " + macro("$name$")
+ debugger
+ return text
+ }}
+}
+```
Icinga 2 will spawn a debugger console every time the function is executed:
- # icinga2 daemon -X
- ...
- Breakpoint encountered in /etc/icinga2/tests/script-debugger.conf: 7:5-7:12
- You can inspect expressions (such as variables) by entering them at the prompt.
- To leave the debugger and continue the program use "$continue".
- <1> => text
- "Hello from script-debugger-host-02"
- <2> => $continue
-
+```
+# icinga2 daemon -X
+...
+Breakpoint encountered in /etc/icinga2/tests/script-debugger.conf: 7:5-7:12
+You can inspect expressions (such as variables) by entering them at the prompt.
+To leave the debugger and continue the program use "$continue".
+<1> => text
+"Hello from script-debugger-host-02"
+<2> => $continue
+```
## Debugging API Filters <a id="script-debugger-api-filters"></a>
Breakpoint Example:
- (gdb) b __cxa_throw
- (gdb) r
- (gdb) up
- ....
- (gdb) up
- #11 0x00007ffff7cbf9ff in icinga::Utility::GlobRecursive(icinga::String const&, icinga::String const&, boost::function<void (icinga::String const&)> const&, int) (path=..., pattern=..., callback=..., type=1)
- at /home/michi/coding/icinga/icinga2/lib/base/utility.cpp:609
- 609 callback(cpath);
- (gdb) l
- 604
- 605 #endif /* _WIN32 */
- 606
- 607 std::sort(files.begin(), files.end());
- 608 BOOST_FOREACH(const String& cpath, files) {
- 609 callback(cpath);
- 610 }
- 611
- 612 std::sort(dirs.begin(), dirs.end());
- 613 BOOST_FOREACH(const String& cpath, dirs) {
- (gdb) p files
- $3 = std::vector of length 11, capacity 16 = {{static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/agent.conf"}, {static NPos = 18446744073709551615,
- m_Data = "/etc/icinga2/conf.d/commands.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/downtimes.conf"}, {static NPos = 18446744073709551615,
- m_Data = "/etc/icinga2/conf.d/groups.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/notifications.conf"}, {static NPos = 18446744073709551615,
- m_Data = "/etc/icinga2/conf.d/satellite.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/services.conf"}, {static NPos = 18446744073709551615,
- m_Data = "/etc/icinga2/conf.d/templates.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/test.conf"}, {static NPos = 18446744073709551615,
- m_Data = "/etc/icinga2/conf.d/timeperiods.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/users.conf"}}
+```
+(gdb) b __cxa_throw
+(gdb) r
+(gdb) up
+....
+(gdb) up
+#11 0x00007ffff7cbf9ff in icinga::Utility::GlobRecursive(icinga::String const&, icinga::String const&, boost::function<void (icinga::String const&)> const&, int) (path=..., pattern=..., callback=..., type=1)
+ at /home/michi/coding/icinga/icinga2/lib/base/utility.cpp:609
+609 callback(cpath);
+(gdb) l
+604
+605 #endif /* _WIN32 */
+606
+607 std::sort(files.begin(), files.end());
+608 BOOST_FOREACH(const String& cpath, files) {
+609 callback(cpath);
+610 }
+611
+612 std::sort(dirs.begin(), dirs.end());
+613 BOOST_FOREACH(const String& cpath, dirs) {
+(gdb) p files
+$3 = std::vector of length 11, capacity 16 = {{static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/agent.conf"}, {static NPos = 18446744073709551615,
+ m_Data = "/etc/icinga2/conf.d/commands.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/downtimes.conf"}, {static NPos = 18446744073709551615,
+ m_Data = "/etc/icinga2/conf.d/groups.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/notifications.conf"}, {static NPos = 18446744073709551615,
+ m_Data = "/etc/icinga2/conf.d/satellite.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/services.conf"}, {static NPos = 18446744073709551615,
+ m_Data = "/etc/icinga2/conf.d/templates.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/test.conf"}, {static NPos = 18446744073709551615,
+ m_Data = "/etc/icinga2/conf.d/timeperiods.conf"}, {static NPos = 18446744073709551615, m_Data = "/etc/icinga2/conf.d/users.conf"}}
+```
### Core Dump <a id="development-debug-core-dump"></a>
Install the `boost`, `python` and `icinga2` pretty printers. Absolute paths are required,
so please make sure to update the installation paths accordingly (`pwd`).
- $ mkdir -p ~/.gdb_printers && cd ~/.gdb_printers
+```
+$ mkdir -p ~/.gdb_printers && cd ~/.gdb_printers
+```
Boost Pretty Printers compatible with Python 3:
- $ git clone https://github.com/mateidavid/Boost-Pretty-Printer.git && cd Boost-Pretty-Printer
- $ git checkout python-3
- $ pwd
- /home/michi/.gdb_printers/Boost-Pretty-Printer
+```
+$ git clone https://github.com/mateidavid/Boost-Pretty-Printer.git && cd Boost-Pretty-Printer
+$ git checkout python-3
+$ pwd
+/home/michi/.gdb_printers/Boost-Pretty-Printer
+```
Python Pretty Printers:
- $ cd ~/.gdb_printers
- $ svn co svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python
+```
+$ cd ~/.gdb_printers
+$ svn co svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python
+```
Icinga 2 Pretty Printers:
- $ mkdir -p ~/.gdb_printers/icinga2 && cd ~/.gdb_printers/icinga2
- $ wget https://raw.githubusercontent.com/Icinga/icinga2/master/tools/debug/gdb/icingadbg.py
+```
+$ mkdir -p ~/.gdb_printers/icinga2 && cd ~/.gdb_printers/icinga2
+$ wget https://raw.githubusercontent.com/Icinga/icinga2/master/tools/debug/gdb/icingadbg.py
+```
Now you'll need to modify/setup your `~/.gdbinit` configuration file.
You can download the one from Icinga 2 and modify all paths.
Example on Fedora 22:
- $ wget https://raw.githubusercontent.com/Icinga/icinga2/master/tools/debug/gdb/gdbinit -O ~/.gdbinit
- $ vim ~/.gdbinit
-
- set print pretty on
-
- python
- import sys
- sys.path.insert(0, '/home/michi/.gdb_printers/icinga2')
- from icingadbg import register_icinga_printers
- register_icinga_printers()
- end
-
- python
- import sys
- sys.path.insert(0, '/home/michi/.gdb_printers/python')
- from libstdcxx.v6.printers import register_libstdcxx_printers
- try:
- register_libstdcxx_printers(None)
- except:
- pass
- end
-
- python
- import sys
- sys.path.insert(0, '/home/michi/.gdb_printers/Boost-Pretty-Printer')
- import boost_print
- boost_print.register_printers()
- end
+```
+$ wget https://raw.githubusercontent.com/Icinga/icinga2/master/tools/debug/gdb/gdbinit -O ~/.gdbinit
+$ vim ~/.gdbinit
+
+set print pretty on
+
+python
+import sys
+sys.path.insert(0, '/home/michi/.gdb_printers/icinga2')
+from icingadbg import register_icinga_printers
+register_icinga_printers()
+end
+python
+import sys
+sys.path.insert(0, '/home/michi/.gdb_printers/python')
+from libstdcxx.v6.printers import register_libstdcxx_printers
+try:
+ register_libstdcxx_printers(None)
+except:
+ pass
+end
+
+python
+import sys
+sys.path.insert(0, '/home/michi/.gdb_printers/Boost-Pretty-Printer')
+import boost_print
+boost_print.register_printers()
+end
+```
If you are getting the following error when running gdb, the `libstdcxx`
printers are already preloaded in your environment and you can remove
the duplicate import in your `~/.gdbinit` file.
- RuntimeError: pretty-printer already registered: libstdc++-v6
-
+```
+RuntimeError: pretty-printer already registered: libstdc++-v6
+```
## Development Tests <a id="development-tests"></a>
If the system runs in enforcing mode and you encounter problems you can set Icinga 2's domain to permissive mode.
- # sestatus
- SELinux status: enabled
- SELinuxfs mount: /sys/fs/selinux
- SELinux root directory: /etc/selinux
- Loaded policy name: targeted
- Current mode: enforcing
- Mode from config file: enforcing
- Policy MLS status: enabled
- Policy deny_unknown status: allowed
- Max kernel policy version: 28
+```
+# sestatus
+SELinux status: enabled
+SELinuxfs mount: /sys/fs/selinux
+SELinux root directory: /etc/selinux
+Loaded policy name: targeted
+Current mode: enforcing
+Mode from config file: enforcing
+Policy MLS status: enabled
+Policy deny_unknown status: allowed
+Max kernel policy version: 28
+```
You can change the configured mode by editing `/etc/selinux/config` and the current mode by executing `setenforce 0`.
Simply add the `icinga2-selinux` package to your installation.
- # yum install icinga2-selinux
+```
+# yum install icinga2-selinux
+```
Ensure that the `icinga2` process is running in its own `icinga2_t` domain after installing the policy package:
- # systemctl restart icinga2.service
- # ps -eZ | grep icinga2
- system_u:system_r:icinga2_t:s0 2825 ? 00:00:00 icinga2
+```
+# systemctl restart icinga2.service
+# ps -eZ | grep icinga2
+system_u:system_r:icinga2_t:s0 2825 ? 00:00:00 icinga2
+```
#### Manual installation <a id="selinux-policy-installation-manual"></a>
As a prerequisite install the `git`, `selinux-policy-devel` and `audit` packages. Enable and start the audit daemon afterwards:
- # yum install git selinux-policy-devel audit
- # systemctl enable auditd.service
- # systemctl start auditd.service
+```
+# yum install git selinux-policy-devel audit
+# systemctl enable auditd.service
+# systemctl start auditd.service
+```
After that clone the icinga2 git repository:
- # git clone https://github.com/icinga/icinga2
+```
+# git clone https://github.com/icinga/icinga2
+```
To create and install the policy package run the installation script which also labels the resources. (The script assumes Icinga 2 was started once after system startup, the labeling of the port will only happen once and fail later on.)
- # cd tools/selinux/
- # ./icinga.sh
+```
+# cd tools/selinux/
+# ./icinga.sh
+```
After that restart Icinga 2 and verify it running in its own domain `icinga2_t`.
- # systemctl restart icinga2.service
- # ps -eZ | grep icinga2
- system_u:system_r:icinga2_t:s0 2825 ? 00:00:00 icinga2
+```
+# systemctl restart icinga2.service
+# ps -eZ | grep icinga2
+system_u:system_r:icinga2_t:s0 2825 ? 00:00:00 icinga2
+```
### General <a id="selinux-policy-general"></a>
Download and install a plugin, for example check_mysql_health.
- # wget https://labs.consol.de/download/shinken-nagios-plugins/check_mysql_health-2.1.9.2.tar.gz
- # tar xvzf check_mysql_health-2.1.9.2.tar.gz
- # cd check_mysql_health-2.1.9.2/
- # ./configure --libexecdir /usr/lib64/nagios/plugins
- # make
- # make install
+```
+# wget https://labs.consol.de/download/shinken-nagios-plugins/check_mysql_health-2.1.9.2.tar.gz
+# tar xvzf check_mysql_health-2.1.9.2.tar.gz
+# cd check_mysql_health-2.1.9.2/
+# ./configure --libexecdir /usr/lib64/nagios/plugins
+# make
+# make install
+```
It is labeled `nagios_unconfined_plugins_exec_t` by default, so it runs without restrictions.
- # ls -lZ /usr/lib64/nagios/plugins/check_mysql_health
- -rwxr-xr-x. root root system_u:object_r:nagios_unconfined_plugin_exec_t:s0 /usr/lib64/nagios/plugins/check_mysql_health
+```
+# ls -lZ /usr/lib64/nagios/plugins/check_mysql_health
+-rwxr-xr-x. root root system_u:object_r:nagios_unconfined_plugin_exec_t:s0 /usr/lib64/nagios/plugins/check_mysql_health
+```
In this case the plugin is monitoring a service, so it should be labeled `nagios_services_plugin_exec_t` to restrict its permissions.
- # chcon -t nagios_services_plugin_exec_t /usr/lib64/nagios/plugins/check_mysql_health
- # ls -lZ /usr/lib64/nagios/plugins/check_mysql_health
- -rwxr-xr-x. root root system_u:object_r:nagios_services_plugin_exec_t:s0 /usr/lib64/nagios/plugins/check_mysql_health
+```
+# chcon -t nagios_services_plugin_exec_t /usr/lib64/nagios/plugins/check_mysql_health
+# ls -lZ /usr/lib64/nagios/plugins/check_mysql_health
+-rwxr-xr-x. root root system_u:object_r:nagios_services_plugin_exec_t:s0 /usr/lib64/nagios/plugins/check_mysql_health
+```
The plugin still runs fine but if someone changes the script to do weird stuff it will fail to do so.
Change the port value for the graphite feature according to your graphite installation before enabling it.
- # cat /etc/icinga2/features-enabled/graphite.conf
- /**
- * The GraphiteWriter type writes check result metrics and
- * performance data to a graphite tcp socket.
- */
+```
+# cat /etc/icinga2/features-enabled/graphite.conf
+/**
+ * The GraphiteWriter type writes check result metrics and
+ * performance data to a graphite tcp socket.
+ */
- library "perfdata"
+library "perfdata"
- object GraphiteWriter "graphite" {
- //host = "127.0.0.1"
- //port = 2003
- port = 2004
- }
- # icinga2 feature enable graphite
+object GraphiteWriter "graphite" {
+ //host = "127.0.0.1"
+ //port = 2003
+ port = 2004
+}
+# icinga2 feature enable graphite
+```
Before you restart the icinga2 service allow it to connect to all ports by enabling the boolean ´icinga2_can_connect_all` (now and permanent).
- # setsebool icinga2_can_connect_all true
- # setsebool -P icinga2_can_connect_all true
+```
+# setsebool icinga2_can_connect_all true
+# setsebool -P icinga2_can_connect_all true
+```
If you restart the daemon now it will successfully connect to graphite.
Start by adding the Icinga 2 administrator role `icinga2adm_r` to the administrative SELinux user `staff_u`.
- # semanage user -m -R "staff_r sysadm_r system_r unconfined_r icinga2adm_r" staff_u
+```
+# semanage user -m -R "staff_r sysadm_r system_r unconfined_r icinga2adm_r" staff_u
+```
Confine your user login and create a sudo rule.
- # semanage login -a dirk -s staff_u
- # echo "dirk ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dirk
+```
+# semanage login -a dirk -s staff_u
+# echo "dirk ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dirk
+```
Login to the system using ssh and verify your id.
- $ id -Z
- staff_u:staff_r:staff_t:s0-s0:c0.c1023
+```
+$ id -Z
+staff_u:staff_r:staff_t:s0-s0:c0.c1023
+```
Try to execute some commands as root using sudo.
- $ sudo id -Z
- staff_u:staff_r:staff_t:s0-s0:c0.c1023
- $ sudo vi /etc/icinga2/icinga2.conf
- "/etc/icinga2/icinga2.conf" [Permission Denied]
- $ sudo cat /var/log/icinga2/icinga2.log
- cat: /var/log/icinga2/icinga2.log: Keine Berechtigung
- $ sudo systemctl reload icinga2.service
- Failed to get D-Bus connection: No connection to service manager.
+```
+$ sudo id -Z
+staff_u:staff_r:staff_t:s0-s0:c0.c1023
+$ sudo vi /etc/icinga2/icinga2.conf
+"/etc/icinga2/icinga2.conf" [Permission Denied]
+$ sudo cat /var/log/icinga2/icinga2.log
+cat: /var/log/icinga2/icinga2.log: Keine Berechtigung
+$ sudo systemctl reload icinga2.service
+Failed to get D-Bus connection: No connection to service manager.
+```
Those commands fail because you only switch to root but do not change your SELinux role. Try again but tell sudo also to switch the SELinux role and type.
- $ sudo -r icinga2adm_r -t icinga2adm_t id -Z
- staff_u:icinga2adm_r:icinga2adm_t:s0-s0:c0.c1023
- $ sudo -r icinga2adm_r -t icinga2adm_t vi /etc/icinga2/icinga2.conf
- "/etc/icinga2/icinga2.conf"
- $ sudo -r icinga2adm_r -t icinga2adm_t cat /var/log/icinga2/icinga2.log
- [2015-03-26 20:48:14 +0000] information/DynamicObject: Dumping program state to file '/var/lib/icinga2/icinga2.state'
- $ sudo -r icinga2adm_r -t icinga2adm_t systemctl reload icinga2.service
+```
+$ sudo -r icinga2adm_r -t icinga2adm_t id -Z
+staff_u:icinga2adm_r:icinga2adm_t:s0-s0:c0.c1023
+$ sudo -r icinga2adm_r -t icinga2adm_t vi /etc/icinga2/icinga2.conf
+"/etc/icinga2/icinga2.conf"
+$ sudo -r icinga2adm_r -t icinga2adm_t cat /var/log/icinga2/icinga2.log
+[2015-03-26 20:48:14 +0000] information/DynamicObject: Dumping program state to file '/var/lib/icinga2/icinga2.state'
+$ sudo -r icinga2adm_r -t icinga2adm_t systemctl reload icinga2.service
+```
Now the commands will work, but you have always to remember to add the arguments, so change the sudo rule to set it by default.
- # echo "dirk ALL=(ALL) ROLE=icinga2adm_r TYPE=icinga2adm_t NOPASSWD: ALL" > /etc/sudoers.d/dirk
+```
+# echo "dirk ALL=(ALL) ROLE=icinga2adm_r TYPE=icinga2adm_t NOPASSWD: ALL" > /etc/sudoers.d/dirk
+```
Now try the commands again without providing the role and type and they will work, but if you try to read apache logs or restart apache for example it will still fail.
- $ sudo cat /var/log/httpd/error_log
- /bin/cat: /var/log/httpd/error_log: Keine Berechtigung
- $ sudo systemctl reload httpd.service
- Failed to issue method call: Access denied
+```
+$ sudo cat /var/log/httpd/error_log
+/bin/cat: /var/log/httpd/error_log: Keine Berechtigung
+$ sudo systemctl reload httpd.service
+Failed to issue method call: Access denied
+```
## Bugreports <a id="selinux-bugreports"></a>
Icinga 1.x:
- define service {
- service_description service1
- host_name localhost1
- check_command test_customvar
- use generic-service
- check_interval 5
- retry_interval 1
- }
+```
+define service {
+ service_description service1
+ host_name localhost1
+ check_command test_customvar
+ use generic-service
+ check_interval 5
+ retry_interval 1
+}
+```
Icinga 2:
- object Service "service1" {
- import "generic-service"
- host_name = "localhost1"
- check_command = "test_customvar"
- check_interval = 5m
- retry_interval = 1m
- }
+```
+object Service "service1" {
+ import "generic-service"
+ host_name = "localhost1"
+ check_command = "test_customvar"
+ check_interval = 5m
+ retry_interval = 1m
+}
+```
#### Manual Config Migration Hints for Services <a id="manual-config-migration-hints-services"></a>
Icinga 1.x:
- define service {
- service_description service1
- host_name localhost1,localhost2
- check_command test_check
- use generic-service
- }
+```
+define service {
+ service_description service1
+ host_name localhost1,localhost2
+ check_command test_check
+ use generic-service
+}
+```
Icinga 2:
- apply Service "service1" {
- import "generic-service"
- check_command = "test_check"
+```
+apply Service "service1" {
+ import "generic-service"
+ check_command = "test_check"
- assign where host.name in [ "localhost1", "localhost2" ]
- }
+ assign where host.name in [ "localhost1", "localhost2" ]
+}
+```
In Icinga 1.x you would have organized your services with hostgroups using the `hostgroup_name` attribute
like the following example:
- define service {
- service_description servicewithhostgroups
- hostgroup_name hostgroup1,hostgroup3
- check_command test_check
- use generic-service
- }
+```
+define service {
+ service_description servicewithhostgroups
+ hostgroup_name hostgroup1,hostgroup3
+ check_command test_check
+ use generic-service
+}
+```
Using Icinga 2 you can migrate this to the [apply rules](03-monitoring-basics.md#using-apply) syntax:
- apply Service "servicewithhostgroups" {
- import "generic-service"
- check_command = "test_check"
+```
+apply Service "servicewithhostgroups" {
+ import "generic-service"
+ check_command = "test_check"
- assign where "hostgroup1" in host.groups
- assign where "hostgroup3" in host.groups
- }
+ assign where "hostgroup1" in host.groups
+ assign where "hostgroup3" in host.groups
+}
+```
#### Manual Config Migration Hints for Group Members <a id="manual-config-migration-hints-group-members"></a>
The Icinga 1.x hostgroup `hg1` has two members `host1` and `host2`. The hostgroup `hg2` has `host3` as
a member and includes all members of the `hg1` hostgroup.
- define hostgroup {
- hostgroup_name hg1
- members host1,host2
- }
+```
+define hostgroup {
+ hostgroup_name hg1
+ members host1,host2
+}
- define hostgroup {
- hostgroup_name hg2
- members host3
- hostgroup_members hg1
- }
+define hostgroup {
+ hostgroup_name hg2
+ members host3
+ hostgroup_members hg1
+}
+```
This can be migrated to Icinga 2 and [using group assign](17-language-reference.md#group-assign). The additional nested hostgroup
`hg1` is included into `hg2` with the `groups` attribute.
+```
+object HostGroup "hg1" {
+ groups = [ "hg2" ]
+ assign where host.name in [ "host1", "host2" ]
+}
- object HostGroup "hg1" {
- groups = [ "hg2" ]
- assign where host.name in [ "host1", "host2" ]
- }
-
- object HostGroup "hg2" {
- assign where host.name == "host3"
- }
+object HostGroup "hg2" {
+ assign where host.name == "host3"
+}
+```
These assign rules can be applied for all groups: `HostGroup`, `ServiceGroup` and `UserGroup`
(requires renaming from `contactgroup`).
Host and service check command arguments are separated by a `!` in Icinga 1.x. Their order is important and they
are referenced as `$ARGn$` where `n` is the argument counter.
- define command {
- command_name my-ping
- command_line $USER1$/check_ping -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ -p 5
- }
+```
+define command {
+ command_name my-ping
+ command_line $USER1$/check_ping -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ -p 5
+}
- define service {
- use generic-service
- host_name my-server
- service_description my-ping
- check_command my-ping-check!100.0,20%!500.0,60%
- }
+define service {
+ use generic-service
+ host_name my-server
+ service_description my-ping
+ check_command my-ping-check!100.0,20%!500.0,60%
+}
+```
While you could manually migrate this like (please note the new generic command arguments and default argument values!):
- object CheckCommand "my-ping-check" {
- command = [
- PluginDir + "/check_ping", "-4"
- ]
-
- arguments = {
- "-H" = "$ping_address$"
- "-w" = "$ping_wrta$,$ping_wpl$%"
- "-c" = "$ping_crta$,$ping_cpl$%"
- "-p" = "$ping_packets$"
- "-t" = "$ping_timeout$"
- }
-
- vars.ping_address = "$address$"
- vars.ping_wrta = 100
- vars.ping_wpl = 5
- vars.ping_crta = 200
- vars.ping_cpl = 15
- }
-
- object Service "my-ping" {
- import "generic-service"
- host_name = "my-server"
- check_command = "my-ping-check"
-
- vars.ping_wrta = 100
- vars.ping_wpl = 20
- vars.ping_crta = 500
- vars.ping_cpl = 60
- }
+```
+object CheckCommand "my-ping-check" {
+ command = [
+ PluginDir + "/check_ping", "-4"
+ ]
+
+ arguments = {
+ "-H" = "$ping_address$"
+ "-w" = "$ping_wrta$,$ping_wpl$%"
+ "-c" = "$ping_crta$,$ping_cpl$%"
+ "-p" = "$ping_packets$"
+ "-t" = "$ping_timeout$"
+ }
+
+ vars.ping_address = "$address$"
+ vars.ping_wrta = 100
+ vars.ping_wpl = 5
+ vars.ping_crta = 200
+ vars.ping_cpl = 15
+}
+
+object Service "my-ping" {
+ import "generic-service"
+ host_name = "my-server"
+ check_command = "my-ping-check"
+
+ vars.ping_wrta = 100
+ vars.ping_wpl = 20
+ vars.ping_crta = 500
+ vars.ping_cpl = 60
+}
+```
#### Manual Config Migration Hints for Runtime Macros <a id="manual-config-migration-hints-runtime-macros"></a>
For example, accessing the service check output looks like the following in Icinga 1.x:
- $SERVICEOUTPUT$
+```
+$SERVICEOUTPUT$
+```
In Icinga 2 you will need to write:
- $service.output$
+```
+$service.output$
+```
Another example referencing the host's address attribute in Icinga 1.x:
- $HOSTADDRESS$
+```
+$HOSTADDRESS$
+```
In Icinga 2 you'd just use the following macro to access all `address` attributes (even overridden from the service objects):
- $address$
-
+```
+$address$
+```
#### Manual Config Migration Hints for Runtime Custom Attributes <a id="manual-config-migration-hints-runtime-custom-attributes"></a>
Custom variables from Icinga 1.x are available as Icinga 2 custom attributes.
- define command {
- command_name test_customvar
- command_line echo "Host CV: $_HOSTCVTEST$ Service CV: $_SERVICECVTEST$\n"
- }
-
- define host {
- host_name localhost1
- check_command test_customvar
- use generic-host
- _CVTEST host cv value
- }
-
- define service {
- service_description service1
- host_name localhost1
- check_command test_customvar
- use generic-service
- _CVTEST service cv value
- }
+```
+define command {
+ command_name test_customvar
+ command_line echo "Host CV: $_HOSTCVTEST$ Service CV: $_SERVICECVTEST$\n"
+}
+
+define host {
+ host_name localhost1
+ check_command test_customvar
+ use generic-host
+ _CVTEST host cv value
+}
+
+define service {
+ service_description service1
+ host_name localhost1
+ check_command test_customvar
+ use generic-service
+ _CVTEST service cv value
+}
+```
Can be written as the following in Icinga 2:
- object CheckCommand "test_customvar" {
- command = "echo "Host CV: $host.vars.CVTEST$ Service CV: $service.vars.CVTEST$\n""
- }
+```
+object CheckCommand "test_customvar" {
+ command = "echo "Host CV: $host.vars.CVTEST$ Service CV: $service.vars.CVTEST$\n""
+}
- object Host "localhost1" {
- import "generic-host"
- check_command = "test_customvar"
- vars.CVTEST = "host cv value"
- }
+object Host "localhost1" {
+ import "generic-host"
+ check_command = "test_customvar"
+ vars.CVTEST = "host cv value"
+}
- object Service "service1" {
- host_name = "localhost1"
- check_command = "test_customvar"
- vars.CVTEST = "service cv value"
- }
+object Service "service1" {
+ host_name = "localhost1"
+ check_command = "test_customvar"
+ vars.CVTEST = "service cv value"
+}
+```
If you are just defining `$CVTEST$` in your command definition, its value depends on the
execution scope -- the host check command will fetch the host attribute value of `vars.CVTEST`
Contacts in Icinga 1.x act as users in Icinga 2, but do not have any notification commands specified.
This migration part is explained in the [next chapter](23-migrating-from-icinga-1x.md#manual-config-migration-hints-notifications).
- define contact{
- contact_name testconfig-user
- use generic-user
- alias Icinga Test User
- service_notification_options c,f,s,u
- email icinga@localhost
- }
+```
+define contact{
+ contact_name testconfig-user
+ use generic-user
+ alias Icinga Test User
+ service_notification_options c,f,s,u
+ email icinga@localhost
+}
+```
The `service_notification_options` can be [mapped](23-migrating-from-icinga-1x.md#manual-config-migration-hints-notification-filters)
into generic `state` and `type` filters, if additional notification filtering is required. `alias` gets
renamed to `display_name`.
- object User "testconfig-user" {
- import "generic-user"
- display_name = "Icinga Test User"
- email = "icinga@localhost"
- }
+```
+object User "testconfig-user" {
+ import "generic-user"
+ display_name = "Icinga Test User"
+ email = "icinga@localhost"
+}
+```
This user can be put into usergroups (former contactgroups) or referenced in newly migration notification
objects.
Generate a new notification object based on these values. Import the generic template based on the type (`host` or `service`).
Assign it to the host or service and set the newly generated notification command name as `command` attribute.
- object Notification "<notificationname>" {
- import "mail-host-notification"
- host_name = "<thishostname>"
- command = "<notificationcommandname>"
-
+```
+object Notification "<notificationname>" {
+ import "mail-host-notification"
+ host_name = "<thishostname>"
+ command = "<notificationcommandname>"
+```
Convert the `notification_options` attribute from Icinga 1.x to Icinga 2 `states` and `types`. Details
[here](23-migrating-from-icinga-1x.md#manual-config-migration-hints-notification-filters). Add the notification period.
- states = [ OK, Warning, Critical ]
- types = [ Recovery, Problem, Custom ]
- period = "24x7"
+```
+ states = [ OK, Warning, Critical ]
+ types = [ Recovery, Problem, Custom ]
+ period = "24x7"
+```
The current contact acts as `users` attribute.
- users = [ "<contactwithnotificationcommand>" ]
- }
+```
+ users = [ "<contactwithnotificationcommand>" ]
+}
+```
Do this in a loop for all notification commands (depending if host or service contact). Once done, dump the
collected notification commands.
After 20 minutes (`10*2`, notification_interval * first_notification) the notification is escalated to the
`cg_ops` contactgroup until 60 minutes (`10*6`) have passed.
- define service {
- service_description dep_svc01
- host_name dep_hostsvc01,dep_hostsvc03
- check_command test2
- use generic-service
- notification_interval 10
- contact_groups cg_admin
- }
-
- define hostgroup {
- hostgroup_name hg_svcdep2
- members dep_hostsvc03
- }
-
- # with hostgroup_name and service_description
- define serviceescalation {
- hostgroup_name hg_svcdep2
- service_description dep_svc01
- first_notification 2
- last_notification 6
- contact_groups cg_ops
- }
+```
+define service {
+ service_description dep_svc01
+ host_name dep_hostsvc01,dep_hostsvc03
+ check_command test2
+ use generic-service
+ notification_interval 10
+ contact_groups cg_admin
+}
+
+define hostgroup {
+ hostgroup_name hg_svcdep2
+ members dep_hostsvc03
+}
+
+# with hostgroup_name and service_description
+define serviceescalation {
+ hostgroup_name hg_svcdep2
+ service_description dep_svc01
+ first_notification 2
+ last_notification 6
+ contact_groups cg_ops
+}
+```
In Icinga 2 the service and hostgroup definition will look quite the same. Save the `notification_interval`
and `contact_groups` attribute for an additional notification.
- apply Service "dep_svc01" {
- import "generic-service"
+```
+apply Service "dep_svc01" {
+ import "generic-service"
- check_command = "test2"
+ check_command = "test2"
- assign where host.name == "dep_hostsvc01"
- assign where host.name == "dep_hostsvc03"
- }
+ assign where host.name == "dep_hostsvc01"
+ assign where host.name == "dep_hostsvc03"
+}
- object HostGroup "hg_svcdep2" {
- assign where host.name == "dep_hostsvc03"
- }
+object HostGroup "hg_svcdep2" {
+ assign where host.name == "dep_hostsvc03"
+}
- apply Notification "email" to Service {
- import "service-mail-notification"
+apply Notification "email" to Service {
+ import "service-mail-notification"
- interval = 10m
- user_groups = [ "cg_admin" ]
+ interval = 10m
+ user_groups = [ "cg_admin" ]
- assign where service.name == "dep_svc01" && (host.name == "dep_hostsvc01" || host.name == "dep_hostsvc03")
- }
+ assign where service.name == "dep_svc01" && (host.name == "dep_hostsvc01" || host.name == "dep_hostsvc03")
+}
+```
Calculate the begin and end time for the newly created escalation notification:
Assign the notification escalation to the service `dep_svc01` on all hosts in the hostgroup `hg_svcdep2`.
- apply Notification "email-escalation" to Service {
- import "service-mail-notification"
+```
+apply Notification "email-escalation" to Service {
+ import "service-mail-notification"
- interval = 10m
- user_groups = [ "cg_ops" ]
+ interval = 10m
+ user_groups = [ "cg_ops" ]
- times = {
- begin = 20m
- end = 1h
- }
+ times = {
+ begin = 20m
+ end = 1h
+ }
- assign where service.name == "dep_svc01" && "hg_svcdep2" in host.groups
- }
+ assign where service.name == "dep_svc01" && "hg_svcdep2" in host.groups
+}
+```
The assign rule could be made more generic and the notification be applied to more than
just this service belonging to hosts in the matched hostgroup.
The following example describes service dependencies. If you migrate from Icinga 1.x, you will only
want to use the classic `Host-to-Host` and `Service-to-Service` dependency relationships.
- define service {
- service_description dep_svc01
- hostgroup_name hg_svcdep1
- check_command test2
- use generic-service
- }
-
- define service {
- service_description dep_svc02
- hostgroup_name hg_svcdep2
- check_command test2
- use generic-service
- }
-
- define hostgroup {
- hostgroup_name hg_svcdep2
- members host2
- }
-
- define host{
- use linux-server-template
- host_name host1
- address 192.168.1.10
- }
-
- # with hostgroup_name and service_description
- define servicedependency {
- host_name host1
- dependent_hostgroup_name hg_svcdep2
- service_description dep_svc01
- dependent_service_description *
- execution_failure_criteria u,c
- notification_failure_criteria w,u,c
- inherits_parent 1
- }
+```
+define service {
+ service_description dep_svc01
+ hostgroup_name hg_svcdep1
+ check_command test2
+ use generic-service
+}
+
+define service {
+ service_description dep_svc02
+ hostgroup_name hg_svcdep2
+ check_command test2
+ use generic-service
+}
+
+define hostgroup {
+ hostgroup_name hg_svcdep2
+ members host2
+}
+
+define host{
+ use linux-server-template
+ host_name host1
+ address 192.168.1.10
+}
+
+# with hostgroup_name and service_description
+define servicedependency {
+ host_name host1
+ dependent_hostgroup_name hg_svcdep2
+ service_description dep_svc01
+ dependent_service_description *
+ execution_failure_criteria u,c
+ notification_failure_criteria w,u,c
+ inherits_parent 1
+}
+```
Map the dependency attributes accordingly.
And migrate the host and services.
- object Host "host1" {
- import "linux-server-template"
- address = "192.168.1.10"
- }
+```
+object Host "host1" {
+ import "linux-server-template"
+ address = "192.168.1.10"
+}
- object HostGroup "hg_svcdep2" {
- assign where host.name == "host2"
- }
+object HostGroup "hg_svcdep2" {
+ assign where host.name == "host2"
+}
- apply Service "dep_svc01" {
- import "generic-service"
- check_command = "test2"
+apply Service "dep_svc01" {
+ import "generic-service"
+ check_command = "test2"
- assign where "hp_svcdep1" in host.groups
- }
+ assign where "hp_svcdep1" in host.groups
+}
- apply Service "dep_svc02" {
- import "generic-service"
- check_command = "test2"
+apply Service "dep_svc02" {
+ import "generic-service"
+ check_command = "test2"
- assign where "hp_svcdep2" in host.groups
- }
+ assign where "hp_svcdep2" in host.groups
+}
+```
When it comes to the `execution_failure_criteria` and `notification_failure_criteria` attribute migration,
you will need to map the most common values, in this example `u,c` (`Unknown` and `Critical` will cause the
dependency to fail). Therefore the `Dependency` should be ok on Ok and Warning. `inherits_parents` is always
enabled.
- apply Dependency "all-svc-for-hg-hg_svcdep2-on-host1-dep_svc01" to Service {
- parent_host_name = "host1"
- parent_service_name = "dep_svc01"
+```
+apply Dependency "all-svc-for-hg-hg_svcdep2-on-host1-dep_svc01" to Service {
+ parent_host_name = "host1"
+ parent_service_name = "dep_svc01"
- states = [ Ok, Warning ]
- disable_checks = true
- disable_notifications = true
+ states = [ Ok, Warning ]
+ disable_checks = true
+ disable_notifications = true
- assign where "hg_svcdep2" in host.groups
- }
+ assign where "hg_svcdep2" in host.groups
+}
+```
Host dependencies are explained in the [next chapter](23-migrating-from-icinga-1x.md#manual-config-migration-hints-host-parents).
By default all hosts in the hostgroup `vmware` should get the parent assigned. This isn't really
solvable with Icinga 1.x parents, but only with host dependencies.
- define host{
- use linux-server-template
- host_name vmware-master
- hostgroups vmware
- address 192.168.1.10
- }
-
- define host{
- use linux-server-template
- host_name vmware-vm1
- hostgroups vmware
- address 192.168.27.1
- parents vmware-master
- }
-
- define host{
- use linux-server-template
- host_name vmware-vm2
- hostgroups vmware
- address 192.168.28.1
- parents vmware-master
- }
+```
+define host{
+ use linux-server-template
+ host_name vmware-master
+ hostgroups vmware
+ address 192.168.1.10
+}
+
+define host{
+ use linux-server-template
+ host_name vmware-vm1
+ hostgroups vmware
+ address 192.168.27.1
+ parents vmware-master
+}
+
+define host{
+ use linux-server-template
+ host_name vmware-vm2
+ hostgroups vmware
+ address 192.168.28.1
+ parents vmware-master
+}
+```
By default all hosts in the hostgroup `vmware` should get the parent assigned (but not the `vmware-master`
host itself). This isn't really solvable with Icinga 1.x parents, but only with host dependencies as shown
below:
- define hostdependency {
- dependent_hostgroup_name vmware
- dependent_host_name !vmware-master
- host_name vmware-master
- inherits_parent 1
- notification_failure_criteria d,u
- execution_failure_criteria d,u
- dependency_period testconfig-24x7
- }
+```
+define hostdependency {
+ dependent_hostgroup_name vmware
+ dependent_host_name !vmware-master
+ host_name vmware-master
+ inherits_parent 1
+ notification_failure_criteria d,u
+ execution_failure_criteria d,u
+ dependency_period testconfig-24x7
+}
+```
When migrating to Icinga 2, the parents must be changed to a newly created host dependency.
The Icinga 2 configuration looks like this:
-
- object Host "vmware-master" {
- import "linux-server-template"
- groups += [ "vmware" ]
- address = "192.168.1.10"
- vars.is_vmware_master = true
- }
-
- object Host "vmware-vm1" {
- import "linux-server-template"
- groups += [ "vmware" ]
- address = "192.168.27.1"
- }
-
- object Host "vmware-vm2" {
- import "linux-server-template"
- groups += [ "vmware" ]
- address = "192.168.28.1"
- }
-
- apply Dependency "vmware-master" to Host {
- parent_host_name = "vmware-master"
-
- assign where "vmware" in host.groups
- ignore where host.vars.is_vmware_master
- ignore where host.name == "vmware-master"
- }
+```
+object Host "vmware-master" {
+ import "linux-server-template"
+ groups += [ "vmware" ]
+ address = "192.168.1.10"
+ vars.is_vmware_master = true
+}
+
+object Host "vmware-vm1" {
+ import "linux-server-template"
+ groups += [ "vmware" ]
+ address = "192.168.27.1"
+}
+
+object Host "vmware-vm2" {
+ import "linux-server-template"
+ groups += [ "vmware" ]
+ address = "192.168.28.1"
+}
+
+apply Dependency "vmware-master" to Host {
+ parent_host_name = "vmware-master"
+
+ assign where "vmware" in host.groups
+ ignore where host.vars.is_vmware_master
+ ignore where host.name == "vmware-master"
+}
+```
For easier identification you could add the `vars.is_vmware_master` attribute to the `vmware-master`
host and let the dependency ignore that instead of the hardcoded host name. That's different
Another way to express the same configuration would be something like:
- object Host "vmware-master" {
- import "linux-server-template"
- groups += [ "vmware" ]
- address = "192.168.1.10"
- }
-
- object Host "vmware-vm1" {
- import "linux-server-template"
- groups += [ "vmware" ]
- address = "192.168.27.1"
- vars.parents = [ "vmware-master" ]
- }
-
- object Host "vmware-vm2" {
- import "linux-server-template"
- groups += [ "vmware" ]
- address = "192.168.28.1"
- vars.parents = [ "vmware-master" ]
- }
-
- apply Dependency "host-to-parent-" for (parent in host.vars.parents) to Host {
- parent_host_name = parent
- }
+```
+object Host "vmware-master" {
+ import "linux-server-template"
+ groups += [ "vmware" ]
+ address = "192.168.1.10"
+}
+
+object Host "vmware-vm1" {
+ import "linux-server-template"
+ groups += [ "vmware" ]
+ address = "192.168.27.1"
+ vars.parents = [ "vmware-master" ]
+}
+
+object Host "vmware-vm2" {
+ import "linux-server-template"
+ groups += [ "vmware" ]
+ address = "192.168.28.1"
+ vars.parents = [ "vmware-master" ]
+}
+
+apply Dependency "host-to-parent-" for (parent in host.vars.parents) to Host {
+ parent_host_name = parent
+}
+```
This example allows finer grained host-to-host dependency, as well as multiple dependency support.
icinga.cfg:
- enable_notifications=1
+```
+enable_notifications=1
+```
objects.cfg:
- define service {
- notifications_enabled 0
- }
+```
+define service {
+ notifications_enabled 0
+}
+```
Icinga 2 supports objects and (global) variables, but does not make a difference
between the main configuration file or any other included file.
icinga2.conf:
- const EnableNotifications = true
+```
+const EnableNotifications = true
- object Service "test" {
- enable_notifications = false
- }
+object Service "test" {
+ enable_notifications = false
+}
+```
#### Sample Configuration and ITL <a id="differences-1x-2-sample-configuration-itl"></a>
and `cfg_dir` directives can include the same file twice which leads to
configuration errors in Icinga 1.x.
- cfg_file=/etc/icinga/objects/commands.cfg
- cfg_dir=/etc/icinga/objects
+```
+cfg_file=/etc/icinga/objects/commands.cfg
+cfg_dir=/etc/icinga/objects
+```
Icinga 2 supports wildcard includes and relative paths, e.g. for including
`conf.d/*.conf` in the same directory.
- include "conf.d/*.conf"
+```
+include "conf.d/*.conf"
+```
If you want to include files and directories recursively, you need to define
a separate option and add the directory and an optional pattern.
- include_recursive "conf.d"
+```
+include_recursive "conf.d"
+```
A global search path for includes is available for advanced features like
the Icinga Template Library (ITL) or additional monitoring plugins check
command configuration.
- include <itl>
- include <plugins>
+```
+include <itl>
+include <plugins>
+```
By convention the `.conf` suffix is used for Icinga 2 configuration files.
Icinga 2 uses global constants instead. In the default config these are
set in the `constants.conf` configuration file:
- /**
- * This file defines global constants which can be used in
- * the other configuration files. At a minimum the
- * PluginDir constant should be defined.
- */
+```
+/**
+ * This file defines global constants which can be used in
+ * the other configuration files. At a minimum the
+ * PluginDir constant should be defined.
+ */
- const PluginDir = "/usr/lib/nagios/plugins"
+const PluginDir = "/usr/lib/nagios/plugins"
+```
[Global macros](17-language-reference.md#constants) can only be defined once. Trying to modify a
global constant will result in an error.
Object names are not specified using attributes (e.g. `service_description` for
services) like in Icinga 1.x but directly after their type definition.
- define service {
- host_name localhost
- service_description ping4
- }
+```
+define service {
+ host_name localhost
+ service_description ping4
+}
- object Service "ping4" {
- host_name = "localhost"
- }
+object Service "ping4" {
+ host_name = "localhost"
+}
+```
### Templates <a id="differences-1x-2-templates"></a>
In Icinga 1.x templates are identified using the `register 0` setting. Icinga 2
uses the `template` identifier:
- template Service "ping4-template" { }
+```
+template Service "ping4-template" { }
+```
Icinga 1.x objects inherit from templates using the `use` attribute.
Icinga 2 uses the keyword `import` with template names in double quotes.
- define service {
- service_description testservice
- use tmpl1,tmpl2,tmpl3
- }
+```
+define service {
+ service_description testservice
+ use tmpl1,tmpl2,tmpl3
+}
- object Service "testservice" {
- import "tmpl1"
- import "tmpl2"
- import "tmpl3"
- }
+object Service "testservice" {
+ import "tmpl1"
+ import "tmpl2"
+ import "tmpl3"
+}
+```
The last template overrides previously set values.
Icinga 1.x separates attribute and value pairs with whitespaces/tabs. Icinga 2
requires an equal sign (=) between them.
- define service {
- check_interval 5
- }
+```
+define service {
+ check_interval 5
+}
- object Service "test" {
- check_interval = 5m
- }
+object Service "test" {
+ check_interval = 5m
+}
+```
Please note that the default time value is seconds if no duration literal
is given. `check_interval = 5` behaves the same as `check_interval = 5s`.
Icinga 1.x custom variable attributes must be prefixed using an underscore (`_`).
In Icinga 2 these attributes must be added to the `vars` dictionary as custom attributes.
- vars.dn = "cn=icinga2-dev-host,ou=icinga,ou=main,ou=IcingaConfig,ou=LConf,dc=icinga,dc=org"
- vars.cv = "my custom cmdb description"
+```
+vars.dn = "cn=icinga2-dev-host,ou=icinga,ou=main,ou=IcingaConfig,ou=LConf,dc=icinga,dc=org"
+vars.cv = "my custom cmdb description"
+```
These custom attributes are also used as [command parameters](03-monitoring-basics.md#command-passing-parameters).
The following external commands are not supported:
- CHANGE_*MODATTR
- CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD
- CHANGE_HOST_NOTIFICATION_TIMEPERIOD
- CHANGE_SVC_NOTIFICATION_TIMEPERIOD
- DEL_DOWNTIME_BY_HOSTGROUP_NAME
- DEL_DOWNTIME_BY_START_TIME_COMMENT
- DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST
- DISABLE_CONTACT_HOST_NOTIFICATIONS
- DISABLE_CONTACT_SVC_NOTIFICATIONS
- DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS
- DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS
- DISABLE_FAILURE_PREDICTION
- DISABLE_HOST_AND_CHILD_NOTIFICATIONS
- DISABLE_HOST_FRESHNESS_CHECKS
- DISABLE_NOTIFICATIONS_EXPIRE_TIME
- DISABLE_SERVICE_FRESHNESS_CHECKS
- ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST
- ENABLE_CONTACT_HOST_NOTIFICATIONS
- ENABLE_CONTACT_SVC_NOTIFICATIONS
- ENABLE_CONTACTGROUP_HOST_NOTIFICATIONS
- ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS
- ENABLE_FAILURE_PREDICTION
- ENABLE_HOST_AND_CHILD_NOTIFICATIONS
- ENABLE_HOST_FRESHNESS_CHECKS
- ENABLE_SERVICE_FRESHNESS_CHECKS
- READ_STATE_INFORMATION
- SAVE_STATE_INFORMATION
- SET_HOST_NOTIFICATION_NUMBER
- SET_SVC_NOTIFICATION_NUMBER
- START_ACCEPTING_PASSIVE_HOST_CHECKS
- START_ACCEPTING_PASSIVE_SVC_CHECKS
- START_OBSESSING_OVER_HOST
- START_OBSESSING_OVER_HOST_CHECKS
- START_OBSESSING_OVER_SVC
- START_OBSESSING_OVER_SVC_CHECKS
- STOP_ACCEPTING_PASSIVE_HOST_CHECKS
- STOP_ACCEPTING_PASSIVE_SVC_CHECKS
- STOP_OBSESSING_OVER_HOST
- STOP_OBSESSING_OVER_HOST_CHECKS
- STOP_OBSESSING_OVER_SVC
- STOP_OBSESSING_OVER_SVC_CHECKS
+```
+CHANGE_*MODATTR
+CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD
+CHANGE_HOST_NOTIFICATION_TIMEPERIOD
+CHANGE_SVC_NOTIFICATION_TIMEPERIOD
+DEL_DOWNTIME_BY_HOSTGROUP_NAME
+DEL_DOWNTIME_BY_START_TIME_COMMENT
+DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST
+DISABLE_CONTACT_HOST_NOTIFICATIONS
+DISABLE_CONTACT_SVC_NOTIFICATIONS
+DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS
+DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS
+DISABLE_FAILURE_PREDICTION
+DISABLE_HOST_AND_CHILD_NOTIFICATIONS
+DISABLE_HOST_FRESHNESS_CHECKS
+DISABLE_NOTIFICATIONS_EXPIRE_TIME
+DISABLE_SERVICE_FRESHNESS_CHECKS
+ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST
+ENABLE_CONTACT_HOST_NOTIFICATIONS
+ENABLE_CONTACT_SVC_NOTIFICATIONS
+ENABLE_CONTACTGROUP_HOST_NOTIFICATIONS
+ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS
+ENABLE_FAILURE_PREDICTION
+ENABLE_HOST_AND_CHILD_NOTIFICATIONS
+ENABLE_HOST_FRESHNESS_CHECKS
+ENABLE_SERVICE_FRESHNESS_CHECKS
+READ_STATE_INFORMATION
+SAVE_STATE_INFORMATION
+SET_HOST_NOTIFICATION_NUMBER
+SET_SVC_NOTIFICATION_NUMBER
+START_ACCEPTING_PASSIVE_HOST_CHECKS
+START_ACCEPTING_PASSIVE_SVC_CHECKS
+START_OBSESSING_OVER_HOST
+START_OBSESSING_OVER_HOST_CHECKS
+START_OBSESSING_OVER_SVC
+START_OBSESSING_OVER_SVC_CHECKS
+STOP_ACCEPTING_PASSIVE_HOST_CHECKS
+STOP_ACCEPTING_PASSIVE_SVC_CHECKS
+STOP_OBSESSING_OVER_HOST
+STOP_OBSESSING_OVER_HOST_CHECKS
+STOP_OBSESSING_OVER_SVC
+STOP_OBSESSING_OVER_SVC_CHECKS
+```
### Asynchronous Event Execution <a id="differences-1x-2-async-event-execution"></a>
`members` attribute is available through `assign where` and `ignore where`
expressions by using [group assign](03-monitoring-basics.md#group-assign-intro).
- object Host "web-dev" {
- import "generic-host"
- }
+```
+object Host "web-dev" {
+ import "generic-host"
+}
- object HostGroup "dev-hosts" {
- display_name = "Dev Hosts"
- assign where match("*-dev", host.name)
- }
+object HostGroup "dev-hosts" {
+ display_name = "Dev Hosts"
+ assign where match("*-dev", host.name)
+}
+```
#### Add Service to Hostgroup where Host is Member <a id="differences-1x-2-service-hostgroup-host"></a>
In order to associate a service with all hosts in a host group the [apply](03-monitoring-basics.md#using-apply)
keyword can be used:
- apply Service "ping4" {
- import "generic-service"
+```
+apply Service "ping4" {
+ import "generic-service"
- check_command = "ping4"
+ check_command = "ping4"
- assign where "dev-hosts" in host.groups
- }
+ assign where "dev-hosts" in host.groups
+}
+```
### Notifications <a id="differences-1x-2-notifications"></a>
Previously in Icinga 1.x it looked like this:
- service -> (contact, contactgroup) -> notification command
+```
+service -> (contact, contactgroup) -> notification command
+```
In Icinga 2 it will look like this:
- Service -> Notification -> NotificationCommand
- -> User, UserGroup
+```
+Service -> Notification -> NotificationCommand
+ -> User, UserGroup
+```
#### Escalations <a id="differences-1x-2-escalations"></a>
objects. Escalations happen between a defined start and end time which is
calculated from the notification_interval:
- start = notification start + (notification_interval * first_notification)
- end = notification start + (notification_interval * last_notification)
+```
+start = notification start + (notification_interval * first_notification)
+end = notification start + (notification_interval * last_notification)
+```
In theory first_notification and last_notification can be set to readable
numbers. In practice users are manipulating those attributes in combination
state and type filters, Icinga 2 uses two configuration attributes for that.
All state and type filter use long names OR'd with a pipe together
- notification_options w,u,c,r,f,s
+```
+notification_options w,u,c,r,f,s
- states = [ Warning, Unknown, Critical ]
- types = [ Problem, Recovery, FlappingStart, FlappingEnd, DowntimeStart, DowntimeEnd, DowntimeRemoved ]
+states = [ Warning, Unknown, Critical ]
+types = [ Problem, Recovery, FlappingStart, FlappingEnd, DowntimeStart, DowntimeEnd, DowntimeRemoved ]
+```
Icinga 2 adds more fine-grained type filters for acknowledgements, downtime,
and flapping type (start, end, ...).
value is hardcoded and cannot be changed. The algorithm on determining a flapping state
is as follows:
- flapping value = (number of actual state changes / number of possible state changes)
+```
+flapping value = (number of actual state changes / number of possible state changes)
+```
The flapping value is then compared to the low and high flapping thresholds.