Sensu is monitoring services like Nagios and the things it should monitor can be configured with JSON check definition files.
A JSON check definition file can have one or more check definitions. Here is a simplified example:
{
"checks": {
"cron": {
"command": "check-process.rb -p cron",
"interval": 60
}
}
}
Let’s say I have defined the following template for generating check files:
{
"checks": {
{% for check_def in item.check_defs %}
"{{ check_def.name }}": {
"command": "{{ check_def.command }}",
"interval": {{ check_def.check_interval }}
}{{ ',' if not loop.last else '' }}
{% endfor %}
}
}
I apply this template a task like this:
- copy:
content: "{{ lookup('template', 'check_def.json.j2') | to_nice_json }}"
dest: "{{ somewhere }}"
with_items: "{{ check_sets }}"
notify: Restart Sensu
The check_sets
variable is defined similar to:
vars:
services:
- foo
- bar
- baz
tasks:
set_fact:
check_defs: >
{{
check_defs|default([]) + [
{
'name' : 'my-check-def-for' + item.name,
'command' : 'check-process.rb',
'command_args' : '-p ' + item
}
]
}}
with_items: "{{ services }}"
I find this approach to defining check_defs
to be ugly for several reasons:
1- It is not declarative (e.g. check_defs|default([])
as well as appending items to the list are not declarative).
2- I don’t like the string concat logic using +
and using quotes around hardcoded strings
3- For newcomers, it is not easy to understand what is going on
If I use a static list, I have to repeat some variables/values. For example:
check_defs:
- name: my-check-def-for-foo
command: check-process.rb
command_args: -p foo
Here foo
is repeated twice.
Also users might diverge from the naming convention. For example by providing:
check_defs:
- name: foo-check
command: check-process.rb
command_args: -p foo
Is there a more elegant way to declare the check_defs
variable that doesn’t have any of these drawbacks?
Thanks in advance.