grafana-ansible-collection/plugins/modules/alert_notification_policy.py

228 lines
7.9 KiB
Python
Raw Normal View History

2022-08-09 08:37:47 +02:00
#!/usr/bin/python
# -*- coding: utf-8 -*-
2022-08-11 12:17:51 +02:00
# Copyright: (c) 2021, Ishan Jain (@ishanjainn)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
2022-08-09 08:37:47 +02:00
DOCUMENTATION = '''
---
module: alert_notification_policy
2022-08-09 08:37:47 +02:00
author:
- Ishan Jain (@ishanjainn)
version_added: "0.0.1"
2022-08-30 08:46:55 +02:00
short_description: Sets the notification policy tree in Alerting on Grafana Cloud
2022-08-09 08:37:47 +02:00
description:
2022-08-30 08:46:55 +02:00
- Set the notification policy tree using Ansible.
requirements: [ "requests >= 1.0.0" ]
notes:
- Does not support C(check_mode).
2022-08-09 08:37:47 +02:00
options:
Continue:
description:
- Continue matching subsequent sibling nodes if set to C(true).
2022-08-09 08:37:47 +02:00
type: bool
default: false
groupByStr:
2022-08-09 08:37:47 +02:00
description:
- List of string.
- Group alerts when you receive a notification based on labels. If empty it will be inherited from the parent policy.
type: list
default: []
elements: str
muteTimeIntervals:
2022-08-09 08:37:47 +02:00
description:
- List of string.
2022-08-30 08:46:55 +02:00
- Sets the mute timing for the notfification policy.
2022-08-09 08:37:47 +02:00
type: list
default: []
elements: str
2022-08-30 08:46:55 +02:00
rootPolicyReceiver:
2022-08-09 08:37:47 +02:00
description:
2022-08-30 08:46:55 +02:00
- Sets the name of the contact point to be set as the default receiver.
2022-08-09 08:37:47 +02:00
type: str
default: grafana-default-email
routes:
2022-08-09 08:37:47 +02:00
description:
- List of objects
2022-08-30 08:46:55 +02:00
- Sets the Route that contains definitions of how to handle alerts.
2022-08-09 08:37:47 +02:00
type: list
required: true
elements: dict
2022-08-09 08:37:47 +02:00
groupInterval:
description:
2022-08-30 08:46:55 +02:00
- Sets the wait time to send a batch of new alerts for that group after the first notification was sent. Inherited from the parent policy if empty.
2022-08-09 08:37:47 +02:00
type: str
default: 5m
groupWait:
description:
2022-08-30 08:46:55 +02:00
- Sets the wait time until the initial notification is sent for a new group created by an incoming alert. Inherited from the parent policy if empty.
2022-08-09 08:37:47 +02:00
type: str
default: 30s
objectMatchers:
description:
- Matchers is a slice of Matchers that is sortable, implements Stringer, and provides a Matches method to match a LabelSet.
type: list
default: []
elements: dict
2022-08-09 08:37:47 +02:00
repeatInterval:
description:
2022-08-30 08:46:55 +02:00
- Sets the waiting time to resend an alert after they have successfully been sent.
2022-08-10 12:43:04 +02:00
type: str
2022-08-09 08:37:47 +02:00
default: 4h
stack_slug:
description:
2022-08-30 08:46:55 +02:00
- Name of the Grafana Cloud stack to which the notification policies will be added.
2022-08-09 08:37:47 +02:00
type: str
required: true
grafana_api_key:
description:
- Grafana API Key used to authenticate with Grafana.
type: str
required : true
'''
EXAMPLES = '''
- name: Set Notification policy tree
2022-08-11 07:09:04 +02:00
grafana.grafana.alert_notification_policy:
2022-08-09 08:37:47 +02:00
stack_slug: "{{ stack_slug }}"
grafana_api_key: "{{ grafana_api_key }}"
routes: [
{
receiver: myReceiver,
object_matchers: [["env", "=", "Production"]],
}
]
2022-08-10 12:43:04 +02:00
2022-08-09 08:37:47 +02:00
- name: Set nested Notification policies
2022-08-11 07:09:04 +02:00
grafana.grafana.alert_notification_policy:
2022-08-09 08:37:47 +02:00
routes: [
{
receiver: myReceiver,
object_matchers: [["env", "=", "Production"],["team", "=", "ops"]],
routes: [
{
receiver: myReceiver2,
object_matchers: [["region", "=", "eu"]],
}
]
},
{
receiver: myReceiver3,
object_matchers: [["env", "=", "Staging"]]
}
]
stack_slug: "{{ stack_slug }}"
grafana_api_key: "{{ grafana_api_key }}"
'''
RETURN = r'''
2022-08-10 12:43:04 +02:00
output:
description: Dict object containing Notification tree information.
2022-08-09 08:37:47 +02:00
returned: On success
type: dict
contains:
group_interval:
description: The waiting time to send a batch of new alerts for that group after the first notification was sent. This is of the parent policy.
returned: on success
type: str
sample: "5m"
2022-08-09 08:37:47 +02:00
group_wait:
description: The waiting time until the initial notification is sent for a new group created by an incoming alert. This is of the parent policy.
returned: on success
type: str
sample: "30s"
2022-08-09 08:37:47 +02:00
receiver:
description: The name of the default contact point.
2022-08-09 08:37:47 +02:00
returned: state is present and on success
type: str
sample: "grafana-default-email"
2022-08-09 08:37:47 +02:00
repeat_interval:
description: The waiting time to resend an alert after they have successfully been sent. This is of the parent policy
returned: on success
type: str
sample: "4h"
2022-08-09 08:37:47 +02:00
routes:
description: The entire notification tree returned as a list.
2022-08-09 08:37:47 +02:00
returned: on success
type: list
sample: [
{
"object_matchers": [
[
"env",
"=",
"Production"
]
],
"receiver": "grafana-default-email"
}
]
2022-08-09 08:37:47 +02:00
'''
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
__metaclass__ = type
2022-08-09 08:37:47 +02:00
def alert_notification_policy(module):
body = {'routes': module.params['routes'], 'Continue': module.params['Continue'],
'groupByStr': module.params['groupByStr'], 'muteTimeIntervals': module.params['muteTimeIntervals'],
2022-08-30 08:46:55 +02:00
'receiver': module.params['rootPolicyReceiver'], 'group_interval': module.params['groupInterval'],
2022-08-09 08:37:47 +02:00
'group_wait': module.params['groupWait'], 'object_matchers': module.params['objectMatchers'],
'repeat_interval': module.params['repeatInterval']}
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/v1/provisioning/policies'
result = requests.get(api_url, headers={"Authorization": 'Bearer ' + module.params['grafana_api_key']})
2022-08-09 08:37:47 +02:00
if (result.json()['receiver'] == module.params['rootPolicyReceiver'] and result.json()['routes'] == module.params['routes']
and result.json()['group_wait'] == module.params['groupWait'] and result.json()['group_interval'] == module.params['groupInterval']
and result.json()['repeat_interval'] == module.params['repeatInterval']):
return False, False, result.json()
else:
2022-08-09 08:37:47 +02:00
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/v1/provisioning/policies'
result = requests.put(api_url, json=body, headers={"Authorization": 'Bearer ' + module.params['grafana_api_key']})
if result.status_code == 202:
return False, True, result.json()
else:
return True, False, {"status": result.status_code, 'response': result.json()['message']}
2022-08-09 08:37:47 +02:00
def main():
2022-08-09 08:37:47 +02:00
module_args = dict(Continue=dict(type='bool', required=False, default=False),
groupByStr=dict(type='list', required=False, default=[], elements='str'),
muteTimeIntervals=dict(type='list', required=False, default=[], elements='str'),
2022-08-30 08:46:55 +02:00
rootPolicyReceiver=dict(type='str', required=False, default='grafana-default-email'),
routes=dict(type='list', required=True, elements='dict'),
2022-08-09 08:37:47 +02:00
groupInterval=dict(type='str', required=False, default='5m'),
groupWait=dict(type='str', required=False, default='30s'),
repeatInterval=dict(type='str', required=False, default='4h'),
objectMatchers=dict(type='list', required=False, default=[], elements='dict'),
2022-08-09 08:37:47 +02:00
stack_slug=dict(type='str', required=True),
grafana_api_key=dict(type='str', required=True, no_log=True), )
2022-08-09 08:37:47 +02:00
module = AnsibleModule(argument_spec=module_args)
if not HAS_REQUESTS:
module.fail_json(msg=missing_required_lib('requests'))
2022-08-09 08:37:47 +02:00
is_error, has_changed, result = alert_notification_policy(module)
if not is_error:
module.exit_json(changed=has_changed, output=result)
else:
module.fail_json(msg='Status code is ' + str(result['status']), output=result['response'])
if __name__ == '__main__':
main()