Vendor Galaxy Roles and Collections
This commit is contained in:
parent
c1e1897cda
commit
2aed20393f
3553 changed files with 387444 additions and 2 deletions
|
|
@ -0,0 +1,257 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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)
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: alert_contact_point
|
||||
author:
|
||||
- Ishan Jain (@ishanjainn)
|
||||
version_added: "0.0.1"
|
||||
short_description: Manage Alerting Contact points in Grafana
|
||||
description:
|
||||
- Create, Update and delete Contact points using Ansible.
|
||||
requirements: [ "requests >= 1.0.0" ]
|
||||
notes:
|
||||
- Does not support C(check_mode).
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Sets the name of the contact point.
|
||||
type: str
|
||||
required: true
|
||||
uid:
|
||||
description:
|
||||
- Sets the UID of the Contact point.
|
||||
type: str
|
||||
required: true
|
||||
type:
|
||||
description:
|
||||
- Sets Contact point type.
|
||||
type: str
|
||||
required: true
|
||||
settings:
|
||||
description:
|
||||
- Sets Contact point settings.
|
||||
type: dict
|
||||
required: true
|
||||
disableResolveMessage:
|
||||
description:
|
||||
- When set to C(true), Disables the resolve message [OK] that is sent when alerting state returns to C(false).
|
||||
type: bool
|
||||
default: false
|
||||
grafana_api_key:
|
||||
description:
|
||||
- Grafana API Key used to authenticate with Grafana.
|
||||
type: str
|
||||
required : true
|
||||
grafana_url:
|
||||
description:
|
||||
- URL of the Grafana instance.
|
||||
type: str
|
||||
required: true
|
||||
state:
|
||||
description:
|
||||
- State for the Grafana Alert Contact Point.
|
||||
choices: [ present, absent ]
|
||||
type: str
|
||||
default: present
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Create/Update Alerting contact point
|
||||
grafana.grafana.alert_contact_point:
|
||||
name: ops-email
|
||||
uid: opsemail
|
||||
type: email
|
||||
settings:
|
||||
addresses: "ops@mydomain.com,devs@mydomain.com"
|
||||
grafana_url: "{{ grafana_url }}"
|
||||
grafana_api_key: "{{ grafana_api_key }}"
|
||||
state: present
|
||||
|
||||
- name: Delete Alerting contact point
|
||||
grafana.grafana.alert_contact_point:
|
||||
name: ops-email
|
||||
uid: opsemail
|
||||
type: email
|
||||
settings:
|
||||
addresses: "ops@mydomain.com,devs@mydomain.com"
|
||||
grafana_url: "{{ grafana_url }}"
|
||||
grafana_api_key: "{{ grafana_api_key }}"
|
||||
state: absent
|
||||
'''
|
||||
|
||||
RETURN = r'''
|
||||
output:
|
||||
description: Dict object containing Contact point information information.
|
||||
returned: On success
|
||||
type: dict
|
||||
contains:
|
||||
disableResolveMessage:
|
||||
description: When set to True, Disables the resolve message [OK] that is sent when alerting state returns to false.
|
||||
returned: state is present and on success
|
||||
type: bool
|
||||
sample: false
|
||||
name:
|
||||
description: The name for the contact point.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: ops-email
|
||||
settings:
|
||||
description: Contains contact point settings.
|
||||
returned: state is present and on success
|
||||
type: dict
|
||||
sample: {
|
||||
addresses: "ops@mydomain.com,devs@mydomain.com"
|
||||
}
|
||||
uid:
|
||||
description: The UID for the contact point.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: opsemail
|
||||
type:
|
||||
description: The type of contact point.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: email
|
||||
'''
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
try:
|
||||
import requests
|
||||
HAS_REQUESTS = True
|
||||
except ImportError:
|
||||
HAS_REQUESTS = False
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
def present_alert_contact_point(module):
|
||||
body = {
|
||||
'Name': module.params['name'],
|
||||
'UID': module.params['uid'],
|
||||
'type': module.params['type'],
|
||||
'settings': module.params['settings'],
|
||||
'DisableResolveMessage': module.params['disableResolveMessage']
|
||||
}
|
||||
|
||||
if module.params['grafana_url'][-1] == '/':
|
||||
module.params['grafana_url'] = module.params['grafana_url'][:-1]
|
||||
|
||||
api_url = module.params['grafana_url'] + '/api/v1/provisioning/contact-points'
|
||||
|
||||
headers = {
|
||||
'Authorization': 'Bearer ' + module.params['grafana_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
}
|
||||
result = requests.post(api_url, json=body, headers=headers)
|
||||
|
||||
if result.status_code == 202:
|
||||
return False, True, result.json()
|
||||
elif result.status_code == 500:
|
||||
sameConfig = False
|
||||
contactPointInfo = {}
|
||||
|
||||
api_url = module.params['grafana_url'] + '/api/v1/provisioning/contact-points'
|
||||
|
||||
result = requests.get(api_url, headers=headers)
|
||||
|
||||
for contact_points in result.json():
|
||||
if contact_points['uid'] == module.params['uid']:
|
||||
if (contact_points['name'] == module.params['name'] and contact_points['type'] == module.params['type'] and contact_points['settings']
|
||||
and contact_points['settings'] == module.params['settings']
|
||||
and contact_points['disableResolveMessage'] == module.params['disableResolveMessage']):
|
||||
|
||||
sameConfig = True
|
||||
contactPointInfo = contact_points
|
||||
if sameConfig:
|
||||
return False, False, contactPointInfo
|
||||
else:
|
||||
api_url = module.params['grafana_url'] + '/api/v1/provisioning/contact-points/' + module.params['uid']
|
||||
|
||||
result = requests.put(api_url, json=body, headers=headers)
|
||||
|
||||
if result.status_code == 202:
|
||||
api_url = module.params['grafana_url'] + '/api/v1/provisioning/contact-points'
|
||||
|
||||
result = requests.get(api_url, headers=headers)
|
||||
|
||||
for contact_points in result.json():
|
||||
if contact_points['uid'] == module.params['uid']:
|
||||
return False, True, contact_points
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def absent_alert_contact_point(module):
|
||||
already_exists = False
|
||||
|
||||
if module.params['grafana_url'][-1] == '/':
|
||||
module.params['grafana_url'] = module.params['grafana_url'][:-1]
|
||||
|
||||
api_url = module.params['grafana_url'] + '/api/v1/provisioning/contact-points'
|
||||
headers = {
|
||||
'Authorization': 'Bearer ' + module.params['grafana_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
}
|
||||
|
||||
result = requests.get(api_url, headers=headers)
|
||||
|
||||
for contact_points in result.json():
|
||||
if contact_points['uid'] == module.params['uid']:
|
||||
already_exists = True
|
||||
if already_exists:
|
||||
api_url = module.params['grafana_url'] + '/api/v1/provisioning/contact-points/' + module.params['uid']
|
||||
|
||||
result = requests.delete(api_url, headers=headers)
|
||||
|
||||
if result.status_code == 202:
|
||||
return False, True, result.json()
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
else:
|
||||
return True, False, "Alert Contact point does not exist"
|
||||
|
||||
|
||||
def main():
|
||||
module_args = dict(
|
||||
name=dict(type='str', required=True),
|
||||
uid=dict(type='str', required=True),
|
||||
type=dict(type='str', required=True),
|
||||
settings=dict(type='dict', required=True),
|
||||
disableResolveMessage=dict(type='bool', required=False, default=False),
|
||||
grafana_url=dict(type='str', required=True),
|
||||
grafana_api_key=dict(type='str', required=True, no_log=True),
|
||||
state=dict(type='str', required=False, default='present', choices=['present', 'absent'])
|
||||
)
|
||||
|
||||
choice_map = {
|
||||
"present": present_alert_contact_point,
|
||||
"absent": absent_alert_contact_point,
|
||||
}
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=module_args
|
||||
)
|
||||
|
||||
if not HAS_REQUESTS:
|
||||
module.fail_json(msg=missing_required_lib('requests'))
|
||||
|
||||
is_error, has_changed, result = choice_map.get(
|
||||
module.params['state'])(module)
|
||||
|
||||
if not is_error:
|
||||
module.exit_json(changed=has_changed, output=result)
|
||||
else:
|
||||
module.fail_json(msg=result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -0,0 +1,242 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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)
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: alert_notification_policy
|
||||
author:
|
||||
- Ishan Jain (@ishanjainn)
|
||||
version_added: "0.0.1"
|
||||
short_description: Manage Alerting Policies points in Grafana
|
||||
description:
|
||||
- Set the notification policy tree using Ansible.
|
||||
requirements: [ "requests >= 1.0.0" ]
|
||||
notes:
|
||||
- Does not support C(check_mode).
|
||||
options:
|
||||
Continue:
|
||||
description:
|
||||
- Continue matching subsequent sibling nodes if set to C(true).
|
||||
type: bool
|
||||
default: false
|
||||
groupByStr:
|
||||
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:
|
||||
description:
|
||||
- List of string.
|
||||
- Sets the mute timing for the notfification policy.
|
||||
type: list
|
||||
default: []
|
||||
elements: str
|
||||
rootPolicyReceiver:
|
||||
description:
|
||||
- Sets the name of the contact point to be set as the default receiver.
|
||||
type: str
|
||||
default: grafana-default-email
|
||||
routes:
|
||||
description:
|
||||
- List of objects
|
||||
- Sets the Route that contains definitions of how to handle alerts.
|
||||
type: list
|
||||
required: true
|
||||
elements: dict
|
||||
groupInterval:
|
||||
description:
|
||||
- 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.
|
||||
type: str
|
||||
default: 5m
|
||||
groupWait:
|
||||
description:
|
||||
- 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.
|
||||
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
|
||||
repeatInterval:
|
||||
description:
|
||||
- Sets the waiting time to resend an alert after they have successfully been sent.
|
||||
type: str
|
||||
default: 4h
|
||||
grafana_url:
|
||||
description:
|
||||
- URL of the Grafana instance.
|
||||
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
|
||||
grafana.grafana.alert_notification_policy:
|
||||
grafana_url: "{{ grafana_url }}"
|
||||
grafana_api_key: "{{ grafana_api_key }}"
|
||||
routes: [
|
||||
{
|
||||
receiver: myReceiver,
|
||||
object_matchers: [["env", "=", "Production"]],
|
||||
}
|
||||
]
|
||||
|
||||
- name: Set nested Notification policies
|
||||
grafana.grafana.alert_notification_policy:
|
||||
routes: [
|
||||
{
|
||||
receiver: myReceiver,
|
||||
object_matchers: [["env", "=", "Production"],["team", "=", "ops"]],
|
||||
routes: [
|
||||
{
|
||||
receiver: myReceiver2,
|
||||
object_matchers: [["region", "=", "eu"]],
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
receiver: myReceiver3,
|
||||
object_matchers: [["env", "=", "Staging"]]
|
||||
}
|
||||
]
|
||||
grafana_url: "{{ grafana_url }}"
|
||||
grafana_api_key: "{{ grafana_api_key }}"
|
||||
'''
|
||||
|
||||
RETURN = r'''
|
||||
output:
|
||||
description: Dict object containing Notification tree information.
|
||||
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"
|
||||
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"
|
||||
receiver:
|
||||
description: The name of the default contact point.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: "grafana-default-email"
|
||||
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"
|
||||
routes:
|
||||
description: The entire notification tree returned as a list.
|
||||
returned: on success
|
||||
type: list
|
||||
sample: [
|
||||
{
|
||||
"object_matchers": [
|
||||
[
|
||||
"env",
|
||||
"=",
|
||||
"Production"
|
||||
]
|
||||
],
|
||||
"receiver": "grafana-default-email"
|
||||
}
|
||||
]
|
||||
'''
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
try:
|
||||
import requests
|
||||
HAS_REQUESTS = True
|
||||
except ImportError:
|
||||
HAS_REQUESTS = False
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
def alert_notification_policy(module):
|
||||
body = {'routes': module.params['routes'], 'Continue': module.params['Continue'],
|
||||
'groupByStr': module.params['groupByStr'], 'muteTimeIntervals': module.params['muteTimeIntervals'],
|
||||
'receiver': module.params['rootPolicyReceiver'], 'group_interval': module.params['groupInterval'],
|
||||
'group_wait': module.params['groupWait'], 'object_matchers': module.params['objectMatchers'],
|
||||
'repeat_interval': module.params['repeatInterval']}
|
||||
|
||||
if module.params['grafana_url'][-1] == '/':
|
||||
module.params['grafana_url'] = module.params['grafana_url'][:-1]
|
||||
|
||||
api_url = module.params['grafana_url'] + '/api/v1/provisioning/policies'
|
||||
headers = {
|
||||
'Authorization': 'Bearer ' + module.params['grafana_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
}
|
||||
result = requests.get(api_url, headers=headers)
|
||||
|
||||
if 'routes' not in result.json():
|
||||
api_url = module.params['grafana_url'] + '/api/v1/provisioning/policies'
|
||||
result = requests.put(api_url, json=body, headers=headers)
|
||||
|
||||
if result.status_code == 202:
|
||||
return False, True, result.json()
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
elif (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:
|
||||
api_url = module.params['grafana_url'] + '/api/v1/provisioning/policies'
|
||||
|
||||
result = requests.put(api_url, json=body, headers=headers)
|
||||
|
||||
if result.status_code == 202:
|
||||
return False, True, result.json()
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
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'),
|
||||
rootPolicyReceiver=dict(type='str', required=False, default='grafana-default-email'),
|
||||
routes=dict(type='list', required=True, elements='dict'),
|
||||
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'),
|
||||
grafana_url=dict(type='str', required=True),
|
||||
grafana_api_key=dict(type='str', required=True, no_log=True), )
|
||||
|
||||
module = AnsibleModule(argument_spec=module_args)
|
||||
|
||||
if not HAS_REQUESTS:
|
||||
module.fail_json(msg=missing_required_lib('requests'))
|
||||
|
||||
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()
|
||||
|
|
@ -0,0 +1,152 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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)
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: cloud_api_key
|
||||
author:
|
||||
- Ishan Jain (@ishanjainn)
|
||||
version_added: "0.0.1"
|
||||
short_description: Manage Grafana Cloud API keys
|
||||
description:
|
||||
- Create and delete Grafana Cloud API keys using Ansible.
|
||||
requirements: [ "requests >= 1.0.0" ]
|
||||
notes:
|
||||
- Does not support C(check_mode).
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Sets the name of the Grafana Cloud API key.
|
||||
type: str
|
||||
required: true
|
||||
role:
|
||||
description:
|
||||
- Sets the role to be associated with the Cloud API key.
|
||||
type: str
|
||||
required: true
|
||||
choices: [Admin, Viewer, Editor, MetricsPublisher]
|
||||
org_slug:
|
||||
description:
|
||||
- Name of the Grafana Cloud organization in which Cloud API key will be created.
|
||||
type: str
|
||||
required: true
|
||||
existing_cloud_api_key:
|
||||
description:
|
||||
- Cloud API Key to authenticate with Grafana Cloud.
|
||||
type: str
|
||||
required : true
|
||||
fail_if_already_created:
|
||||
description:
|
||||
- If set to C(true), the task will fail if the API key with same name already exists in the Organization.
|
||||
type: bool
|
||||
default: True
|
||||
state:
|
||||
description:
|
||||
- State for the Grafana Cloud API Key.
|
||||
type: str
|
||||
default: present
|
||||
choices: [ present, absent ]
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Create Grafana Cloud API key
|
||||
grafana.grafana.cloud_api_key:
|
||||
name: key_name
|
||||
role: Admin
|
||||
org_slug: "{{ org_slug }}"
|
||||
existing_cloud_api_key: "{{ grafana_cloud_api_key }}"
|
||||
fail_if_already_created: False
|
||||
state: present
|
||||
|
||||
- name: Delete Grafana Cloud API key
|
||||
grafana.grafana.cloud_api_key:
|
||||
name: key_name
|
||||
org_slug: "{{ org_slug }}"
|
||||
existing_cloud_api_key: "{{ grafana_cloud_api_key }}"
|
||||
state: absent
|
||||
'''
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
try:
|
||||
import requests
|
||||
HAS_REQUESTS = True
|
||||
except ImportError:
|
||||
HAS_REQUESTS = False
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
def present_cloud_api_key(module):
|
||||
body = {
|
||||
'name': module.params['name'],
|
||||
'role': module.params['role']
|
||||
}
|
||||
|
||||
api_url = 'https://grafana.com/api/orgs/' + module.params['org_slug'] + '/api-keys'
|
||||
|
||||
result = requests.post(api_url, json=body, headers={
|
||||
"Authorization": 'Bearer ' + module.params['existing_cloud_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
})
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
elif result.status_code == 409:
|
||||
return module.params['fail_if_already_created'], False, "A Cloud API key with the same name already exists"
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def absent_cloud_api_key(module):
|
||||
api_url = 'https://grafana.com/api/orgs/' + module.params['org_slug'] + '/api-keys/' + module.params['name']
|
||||
|
||||
result = requests.delete(api_url, headers={
|
||||
"Authorization": 'Bearer ' + module.params['existing_cloud_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
})
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, "Cloud API key is deleted"
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
module_args = dict(
|
||||
name=dict(type='str', required=True),
|
||||
role=dict(type='str', required=True, choices=['Admin', 'Viewer', 'Editor', 'MetricsPublisher']),
|
||||
org_slug=dict(type='str', required=True),
|
||||
existing_cloud_api_key=dict(type='str', required=True, no_log=True),
|
||||
fail_if_already_created=dict(type='bool', required=False, default='True'),
|
||||
state=dict(type='str', required=False, default='present', choices=['present', 'absent'])
|
||||
)
|
||||
|
||||
choice_map = {
|
||||
"present": present_cloud_api_key,
|
||||
"absent": absent_cloud_api_key,
|
||||
}
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=module_args
|
||||
)
|
||||
|
||||
if not HAS_REQUESTS:
|
||||
module.fail_json(msg=missing_required_lib('requests'))
|
||||
|
||||
is_error, has_changed, result = choice_map.get(
|
||||
module.params['state'])(module)
|
||||
|
||||
if not is_error:
|
||||
module.exit_json(changed=has_changed, output=result)
|
||||
else:
|
||||
module.fail_json(msg=result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -0,0 +1,189 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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)
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: cloud_plugin
|
||||
author:
|
||||
- Ishan Jain (@ishanjainn)
|
||||
version_added: "0.0.1"
|
||||
short_description: Manage Grafana Cloud Plugins
|
||||
description:
|
||||
- Create, Update and delete Grafana Cloud plugins using Ansible.
|
||||
requirements: [ "requests >= 1.0.0" ]
|
||||
notes:
|
||||
- Does not support C(check_mode).
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Name of the plugin, e.g. grafana-github-datasource.
|
||||
type: str
|
||||
required: true
|
||||
version:
|
||||
description:
|
||||
- Version of the plugin to install.
|
||||
type: str
|
||||
default: latest
|
||||
stack_slug:
|
||||
description:
|
||||
- Name of the Grafana Cloud stack to which the plugin will be added.
|
||||
type: str
|
||||
required: true
|
||||
cloud_api_key:
|
||||
description:
|
||||
- Cloud API Key to authenticate with Grafana Cloud.
|
||||
type: str
|
||||
required : true
|
||||
state:
|
||||
description:
|
||||
- State for the Grafana Cloud Plugin.
|
||||
type: str
|
||||
default: present
|
||||
choices: [ present, absent ]
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Create/Update a plugin
|
||||
grafana.grafana.cloud_plugin:
|
||||
name: grafana-github-datasource
|
||||
version: 1.0.14
|
||||
stack_slug: "{{ stack_slug }}"
|
||||
cloud_api_key: "{{ grafana_cloud_api_key }}"
|
||||
state: present
|
||||
|
||||
- name: Delete a Grafana Cloud stack
|
||||
grafana.grafana.cloud_plugin:
|
||||
name: grafana-github-datasource
|
||||
stack_slug: "{{ stack_slug }}"
|
||||
cloud_api_key: "{{ grafana_cloud_api_key }}"
|
||||
state: absent
|
||||
'''
|
||||
|
||||
RETURN = r'''
|
||||
current_version:
|
||||
description: Current version of the plugin.
|
||||
returned: On success
|
||||
type: str
|
||||
sample: "1.0.14"
|
||||
latest_version:
|
||||
description: Latest version available for the plugin.
|
||||
returned: On success
|
||||
type: str
|
||||
sample: "1.0.15"
|
||||
pluginId:
|
||||
description: Id for the Plugin.
|
||||
returned: On success
|
||||
type: int
|
||||
sample: 663
|
||||
pluginName:
|
||||
description: Name of the plugin.
|
||||
returned: On success
|
||||
type: str
|
||||
sample: "GitHub"
|
||||
pluginSlug:
|
||||
description: Slug for the Plugin.
|
||||
returned: On success
|
||||
type: str
|
||||
sample: "grafana-github-datasource"
|
||||
'''
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
try:
|
||||
import requests
|
||||
HAS_REQUESTS = True
|
||||
except ImportError:
|
||||
HAS_REQUESTS = False
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
def present_cloud_plugin(module):
|
||||
body = {
|
||||
'plugin': module.params['name'],
|
||||
'version': module.params['version']
|
||||
}
|
||||
|
||||
api_url = 'https://grafana.com/api/instances/' + module.params['stack_slug'] + '/plugins'
|
||||
headers = {
|
||||
'Authorization': 'Bearer ' + module.params['grafana_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
}
|
||||
|
||||
result = requests.post(api_url, json=body, headers=headers)
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
elif result.status_code == 409:
|
||||
api_url = 'https://grafana.com/api/instances/' + module.params['stack_slug'] + '/plugins/' + module.params['name']
|
||||
result = requests.get(api_url, headers=headers)
|
||||
|
||||
if result.json()['pluginSlug'] == module.params['name'] and result.json()['version'] == module.params['version']:
|
||||
return False, False, result.json()
|
||||
else:
|
||||
api_url = 'https://grafana.com/api/instances/' + module.params['stack_slug'] + '/plugins/' + module.params[
|
||||
'name']
|
||||
result = requests.post(api_url, json={'version': module.params['version']},
|
||||
headers=headers)
|
||||
|
||||
return False, True, result.json()
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def absent_cloud_plugin(module):
|
||||
api_url = 'https://grafana.com/api/instances/' + module.params['stack_slug'] + '/plugins/' + module.params['name']
|
||||
|
||||
result = requests.delete(api_url, headers={
|
||||
"Authorization": 'Bearer ' + module.params['cloud_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
})
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
module_args = dict(
|
||||
name=dict(type='str', required=True),
|
||||
version=dict(type='str', required=False, default='latest'),
|
||||
stack_slug=dict(type='str', required=True),
|
||||
cloud_api_key=dict(type='str', required=True, no_log=True),
|
||||
state=dict(type='str', required=False, default='present', choices=['present', 'absent'])
|
||||
)
|
||||
|
||||
choice_map = {
|
||||
"present": present_cloud_plugin,
|
||||
"absent": absent_cloud_plugin,
|
||||
}
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=module_args
|
||||
)
|
||||
|
||||
if not HAS_REQUESTS:
|
||||
module.fail_json(msg=missing_required_lib('requests'))
|
||||
|
||||
is_error, has_changed, result = choice_map.get(
|
||||
module.params['state'])(module)
|
||||
|
||||
if not is_error:
|
||||
module.exit_json(changed=has_changed,
|
||||
pluginId=result['pluginId'],
|
||||
pluginName=result['pluginName'],
|
||||
pluginSlug=result['pluginSlug'],
|
||||
current_version=result['version'],
|
||||
latest_version=result['latestVersion'])
|
||||
else:
|
||||
module.fail_json(msg=result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -0,0 +1,259 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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)
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: cloud_stack
|
||||
author:
|
||||
- Ishan Jain (@ishanjainn)
|
||||
version_added: "0.0.1"
|
||||
short_description: Manage Grafana Cloud stack
|
||||
description:
|
||||
- Create and delete Grafana Cloud stacks using Ansible.
|
||||
requirements: [ "requests >= 1.0.0" ]
|
||||
notes:
|
||||
- Does not support C(check_mode).
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Sets the name of stack. Conventionally matches the URL of the instance. For example, C(stackslug.grafana.net).
|
||||
type: str
|
||||
required: true
|
||||
stack_slug:
|
||||
description:
|
||||
- Sets the subdomain of the Grafana instance. For example, if slug is B(stackslug), the instance URL will be C(https://stackslug.grafana.net).
|
||||
type: str
|
||||
required: true
|
||||
cloud_api_key:
|
||||
description:
|
||||
- Cloud API Key to authenticate with Grafana Cloud.
|
||||
type: str
|
||||
required : true
|
||||
region:
|
||||
description:
|
||||
- Sets the region for the Grafana Cloud stack.
|
||||
type: str
|
||||
default: us
|
||||
choices: [ us, us-azure, eu, au, eu-azure, prod-ap-southeast-0, prod-gb-south-0, prod-eu-west-3]
|
||||
url:
|
||||
description:
|
||||
- If you use a custom domain for the instance, you can provide it here. If not provided, Will be set to C(https://stackslug.grafana.net).
|
||||
type: str
|
||||
org_slug:
|
||||
description:
|
||||
- Name of the organization under which Cloud stack is created.
|
||||
type: str
|
||||
required: true
|
||||
delete_protection:
|
||||
description:
|
||||
- Enables or disables deletion protection for the Cloud stack.
|
||||
- When set to true, the stack cannot be deleted unless this flag is explicitly disabled.
|
||||
type: bool
|
||||
default: true
|
||||
required: false
|
||||
state:
|
||||
description:
|
||||
- State for the Grafana Cloud stack.
|
||||
type: str
|
||||
default: present
|
||||
choices: [ present, absent ]
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Create a Grafana Cloud stack
|
||||
grafana.grafana.cloud_stack:
|
||||
name: stack_name
|
||||
stack_slug: stack_name
|
||||
cloud_api_key: "{{ grafana_cloud_api_key }}"
|
||||
region: eu
|
||||
url: https://grafana.company_name.com
|
||||
org_slug: org_name
|
||||
delete_protection: true
|
||||
state: present
|
||||
|
||||
- name: Delete a Grafana Cloud stack
|
||||
grafana.grafana.cloud_stack:
|
||||
name: stack_name
|
||||
slug: stack_name
|
||||
cloud_api_key: "{{ grafana_cloud_api_key }}"
|
||||
org_slug: org_name
|
||||
state: absent
|
||||
'''
|
||||
|
||||
RETURN = r'''
|
||||
alertmanager_name:
|
||||
description: Name of the alertmanager instance.
|
||||
returned: always
|
||||
type: str
|
||||
sample: "stackname-alerts"
|
||||
alertmanager_url:
|
||||
description: URL of the alertmanager instance.
|
||||
returned: always
|
||||
type: str
|
||||
sample: "https://alertmanager-eu-west-0.grafana.net"
|
||||
cluster_slug:
|
||||
description: Slug for the cluster where the Grafana stack is deployed.
|
||||
returned: always
|
||||
type: str
|
||||
sample: "prod-eu-west-0"
|
||||
id:
|
||||
description: ID of the Grafana Cloud stack.
|
||||
returned: always
|
||||
type: int
|
||||
sample: 458182
|
||||
loki_url:
|
||||
description: URl for the Loki instance.
|
||||
returned: always
|
||||
type: str
|
||||
sample: "https://logs-prod-eu-west-0.grafana.net"
|
||||
orgID:
|
||||
description: ID of the Grafana Cloud organization.
|
||||
returned: always
|
||||
type: int
|
||||
sample: 652992
|
||||
prometheus_url:
|
||||
description: URl for the Prometheus instance.
|
||||
returned: always
|
||||
type: str
|
||||
sample: "https://prometheus-prod-01-eu-west-0.grafana.net"
|
||||
tempo_url:
|
||||
description: URl for the Tempo instance.
|
||||
returned: always
|
||||
type: str
|
||||
sample: "https://tempo-eu-west-0.grafana.net"
|
||||
url:
|
||||
description: URL of the Grafana Cloud stack.
|
||||
returned: always
|
||||
type: str
|
||||
sample: "https://stackname.grafana.net"
|
||||
delete_protection:
|
||||
description:
|
||||
- Enables or disables deletion protection for the Cloud stack.
|
||||
- When set to true, the stack cannot be deleted unless this flag is explicitly disabled.
|
||||
returned: always
|
||||
type: bool
|
||||
sample: true
|
||||
'''
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
try:
|
||||
import requests
|
||||
HAS_REQUESTS = True
|
||||
except ImportError:
|
||||
HAS_REQUESTS = False
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
def present_cloud_stack(module):
|
||||
if not module.params['url']:
|
||||
module.params['url'] = 'https://' + module.params['stack_slug'] + '.grafana.net'
|
||||
|
||||
body = {
|
||||
'name': module.params['name'],
|
||||
'slug': module.params['stack_slug'],
|
||||
'region': module.params['region'],
|
||||
'url': module.params['url'],
|
||||
'deleteProtection': module.params.get('delete_protection', True),
|
||||
}
|
||||
api_url = 'https://grafana.com/api/instances'
|
||||
headers = {
|
||||
"Authorization": 'Bearer ' + module.params['cloud_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
}
|
||||
|
||||
result = requests.post(api_url, json=body, headers=headers)
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
elif result.status_code in [409, 403] and result.json()['message'] in ["That URL has already been taken, please try an alternate URL", "Hosted instance limit reached"]:
|
||||
stack_found = False
|
||||
if result.json()['message'] == "That URL has already been taken, please try an alternate URL":
|
||||
api_url = 'https://grafana.com/api/orgs/' + module.params['org_slug'] + '/instances'
|
||||
result = requests.get(api_url, headers=headers)
|
||||
stackInfo = {}
|
||||
for stack in result.json()['items']:
|
||||
if stack['slug'] == module.params['stack_slug']:
|
||||
stack_found = True
|
||||
stackInfo = stack
|
||||
if stack_found:
|
||||
if body['deleteProtection'] == stackInfo['deleteProtection']:
|
||||
return False, False, stackInfo
|
||||
api_url = f'https://grafana.com/api/instances/{stackInfo["id"]}'
|
||||
result = requests.post(api_url, json={'deleteProtection': body['deleteProtection']}, headers=headers)
|
||||
if result.status_code != 200:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
return False, True, result.json()
|
||||
else:
|
||||
return True, False, "Stack is not found under your org"
|
||||
elif result.json()['message'] == "Hosted instance limit reached":
|
||||
return True, False, "You have reached Maximum number of Cloud Stacks in your Org."
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def absent_cloud_stack(module):
|
||||
api_url = 'https://grafana.com/api/instances/' + module.params['stack_slug']
|
||||
|
||||
result = requests.delete(api_url, headers={
|
||||
"Authorization": 'Bearer ' + module.params['cloud_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
})
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
module_args = dict(
|
||||
name=dict(type='str', required=True),
|
||||
stack_slug=dict(type='str', required=True),
|
||||
cloud_api_key=dict(type='str', required=True, no_log=True),
|
||||
region=dict(type='str', required=False, default='us',
|
||||
choices=['us', 'us-azure', 'eu', 'au', 'eu-azure', 'prod-ap-southeast-0', 'prod-gb-south-0',
|
||||
'prod-eu-west-3']),
|
||||
url=dict(type='str', required=False),
|
||||
org_slug=dict(type='str', required=True),
|
||||
state=dict(type='str', required=False, default='present', choices=['present', 'absent']),
|
||||
delete_protection=dict(type=bool, required=False),
|
||||
)
|
||||
|
||||
choice_map = {
|
||||
"present": present_cloud_stack,
|
||||
"absent": absent_cloud_stack,
|
||||
}
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=module_args
|
||||
)
|
||||
|
||||
if not HAS_REQUESTS:
|
||||
module.fail_json(msg=missing_required_lib('requests'))
|
||||
|
||||
is_error, has_changed, result = choice_map.get(
|
||||
module.params['state'])(module)
|
||||
|
||||
if not is_error:
|
||||
module.exit_json(changed=has_changed,
|
||||
alertmanager_name=result['amInstanceName'],
|
||||
url=result['url'], id=result['id'],
|
||||
cluster_slug=result['clusterName'],
|
||||
orgID=result['orgId'],
|
||||
loki_url=result['hlInstanceUrl'],
|
||||
prometheus_url=result['hmInstancePromUrl'],
|
||||
tempo_url=result['htInstanceUrl'],
|
||||
alertmanager_url=result['amInstanceUrl'],
|
||||
delete_protection=result['deleteProtection'])
|
||||
else:
|
||||
module.fail_json(msg=result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
190
ansible_collections/grafana/grafana/plugins/modules/dashboard.py
Normal file
190
ansible_collections/grafana/grafana/plugins/modules/dashboard.py
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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)
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: dashboard
|
||||
author:
|
||||
- Ishan Jain (@ishanjainn)
|
||||
version_added: "0.0.1"
|
||||
short_description: Manage Dashboards in Grafana
|
||||
description:
|
||||
- Create, Update and delete Dashboards using Ansible.
|
||||
requirements: [ "requests >= 1.0.0" ]
|
||||
notes:
|
||||
- Does not support C(check_mode).
|
||||
- Does not support C(Idempotency).
|
||||
options:
|
||||
dashboard:
|
||||
description:
|
||||
- JSON source code for dashboard.
|
||||
type: dict
|
||||
required: true
|
||||
grafana_url:
|
||||
description:
|
||||
- URL of the Grafana instance.
|
||||
type: str
|
||||
required: true
|
||||
grafana_api_key:
|
||||
description:
|
||||
- Grafana API Key to authenticate with Grafana Cloud.
|
||||
type: str
|
||||
required : true
|
||||
state:
|
||||
description:
|
||||
- State for the Grafana Dashboard.
|
||||
choices: [ present, absent ]
|
||||
default: present
|
||||
type: str
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Create/Update a dashboard
|
||||
grafana.grafana.dashboard:
|
||||
dashboard: "{{ lookup('ansible.builtin.file', 'dashboard.json') }}"
|
||||
grafana_url: "{{ grafana_url }}"
|
||||
grafana_api_key: "{{ grafana_api_key }}"
|
||||
state: present
|
||||
|
||||
- name: Delete dashboard
|
||||
grafana.grafana.dashboard:
|
||||
dashboard: "{{ lookup('ansible.builtin.file', 'dashboard.json') }}"
|
||||
grafana_url: "{{ grafana_url }}"
|
||||
grafana_api_key: "{{ grafana_api_key }}"
|
||||
state: absent
|
||||
'''
|
||||
|
||||
RETURN = r'''
|
||||
output:
|
||||
description: Dict object containing folder information.
|
||||
returned: On success
|
||||
type: dict
|
||||
contains:
|
||||
id:
|
||||
description: The ID for the dashboard.
|
||||
returned: on success
|
||||
type: int
|
||||
sample: 17
|
||||
slug:
|
||||
description: The slug for the dashboard.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: ansible-integration-test
|
||||
status:
|
||||
description: The status of the dashboard.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: success
|
||||
uid:
|
||||
description: The UID for the dashboard.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: "test1234"
|
||||
url:
|
||||
description: The endpoint for the dashboard.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: "/d/test1234/ansible-integration-test"
|
||||
version:
|
||||
description: The version of the dashboard.
|
||||
returned: state is present and on success
|
||||
type: int
|
||||
sample: 2
|
||||
message:
|
||||
description: The message returned after the operation on the dashboard.
|
||||
returned: state is absent and on success
|
||||
type: str
|
||||
sample: "Dashboard Ansible Integration Test deleted"
|
||||
title:
|
||||
description: The name of the dashboard.
|
||||
returned: state is absent and on success
|
||||
type: str
|
||||
sample: "Ansible Integration Test"
|
||||
'''
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
try:
|
||||
import requests
|
||||
HAS_REQUESTS = True
|
||||
except ImportError:
|
||||
HAS_REQUESTS = False
|
||||
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
def present_dashboard(module):
|
||||
|
||||
if module.params['grafana_url'][-1] == '/':
|
||||
module.params['grafana_url'] = module.params['grafana_url'][:-1]
|
||||
|
||||
api_url = module.params['grafana_url'] + '/api/dashboards/db'
|
||||
|
||||
result = requests.post(api_url, json=module.params['dashboard'], headers={
|
||||
"Authorization": 'Bearer ' + module.params['grafana_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
})
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def absent_dashboard(module):
|
||||
if module.params['grafana_url'][-1] == '/':
|
||||
module.params['grafana_url'] = module.params['grafana_url'][:-1]
|
||||
|
||||
if 'uid' not in module.params['dashboard']['dashboard']:
|
||||
return True, False, "UID is not defined in the the Dashboard configuration"
|
||||
|
||||
api_url = api_url = module.params['grafana_url'] + '/api/dashboards/uid/' + module.params['dashboard']['dashboard']['uid']
|
||||
|
||||
result = requests.delete(api_url, headers={
|
||||
"Authorization": 'Bearer ' + module.params['grafana_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
})
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
module_args = dict(
|
||||
dashboard=dict(type='dict', required=True),
|
||||
grafana_url=dict(type='str', required=True),
|
||||
grafana_api_key=dict(type='str', required=True, no_log=True),
|
||||
state=dict(type='str', required=False, default='present', choices=['present', 'absent'])
|
||||
)
|
||||
|
||||
choice_map = {
|
||||
"present": present_dashboard,
|
||||
"absent": absent_dashboard,
|
||||
}
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=module_args
|
||||
)
|
||||
|
||||
if not HAS_REQUESTS:
|
||||
module.fail_json(msg=missing_required_lib('requests'))
|
||||
|
||||
is_error, has_changed, result = choice_map.get(
|
||||
module.params['state'])(module)
|
||||
|
||||
if not is_error:
|
||||
module.exit_json(changed=has_changed, output=result)
|
||||
else:
|
||||
module.fail_json(msg=result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -0,0 +1,209 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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)
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: datasource
|
||||
author:
|
||||
- Ishan Jain (@ishanjainn)
|
||||
version_added: "0.0.1"
|
||||
short_description: Manage Data sources in Grafana
|
||||
description:
|
||||
- Create, Update and delete Data sources using Ansible.
|
||||
requirements: [ "requests >= 1.0.0" ]
|
||||
notes:
|
||||
- Does not support C(check_mode).
|
||||
- Does not support C(Idempotency).
|
||||
options:
|
||||
dataSource:
|
||||
description:
|
||||
- JSON source code for the Data source.
|
||||
type: dict
|
||||
required: true
|
||||
grafana_url:
|
||||
description:
|
||||
- URL of the Grafana instance.
|
||||
type: str
|
||||
required: true
|
||||
grafana_api_key:
|
||||
description:
|
||||
- Grafana API Key to authenticate with Grafana Cloud.
|
||||
type: str
|
||||
required : true
|
||||
state:
|
||||
description:
|
||||
- State for the Grafana Datasource.
|
||||
choices: [ present, absent ]
|
||||
default: present
|
||||
type: str
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Create/Update Data sources
|
||||
grafana.grafana.datasource:
|
||||
dataSource:
|
||||
name: Prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://localhost:9090
|
||||
jsonData:
|
||||
httpMethod: POST
|
||||
manageAlerts: true
|
||||
prometheusType: Prometheus
|
||||
cacheLevel: High
|
||||
grafana_url: "{{ grafana_url }}"
|
||||
grafana_api_key: "{{ grafana_api_key }}"
|
||||
state: present
|
||||
|
||||
- name: Delete Data sources
|
||||
grafana.grafana.datasource:
|
||||
dataSource: "{{ lookup('ansible.builtin.file', 'datasource.json') | to_yaml }}"
|
||||
grafana_url: "{{ grafana_url }}"
|
||||
grafana_api_key: "{{ grafana_api_key }}"
|
||||
state: absent
|
||||
'''
|
||||
|
||||
RETURN = r'''
|
||||
output:
|
||||
description: Dict object containing Data source information.
|
||||
returned: On success
|
||||
type: dict
|
||||
contains:
|
||||
datasource:
|
||||
description: The response body content for the data source configuration.
|
||||
returned: state is present and on success
|
||||
type: dict
|
||||
sample: {
|
||||
"access": "proxy",
|
||||
"basicAuth": false,
|
||||
"basicAuthUser": "",
|
||||
"database": "db-name",
|
||||
"id": 20,
|
||||
"isDefault": false,
|
||||
"jsonData": {},
|
||||
"name": "ansible-integration",
|
||||
"orgId": 1,
|
||||
"readOnly": false,
|
||||
"secureJsonFields": {
|
||||
"password": true
|
||||
},
|
||||
"type": "influxdb",
|
||||
"typeLogoUrl": "",
|
||||
"uid": "ansibletest",
|
||||
"url": "https://grafana.github.com/grafana-ansible-collection",
|
||||
"user": "user",
|
||||
"version": 1,
|
||||
"withCredentials": false
|
||||
}
|
||||
id:
|
||||
description: The ID assigned to the data source.
|
||||
returned: on success
|
||||
type: int
|
||||
sample: 20
|
||||
name:
|
||||
description: The name of the data source defined in the JSON source code.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: "ansible-integration"
|
||||
message:
|
||||
description: The message returned after the operation on the Data source.
|
||||
returned: on success
|
||||
type: str
|
||||
sample: "Datasource added"
|
||||
'''
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
try:
|
||||
import requests
|
||||
HAS_REQUESTS = True
|
||||
except ImportError:
|
||||
HAS_REQUESTS = False
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
def present_datasource(module):
|
||||
if module.params['grafana_url'][-1] == '/':
|
||||
module.params['grafana_url'] = module.params['grafana_url'][:-1]
|
||||
|
||||
api_url = module.params['grafana_url'] + '/api/datasources'
|
||||
|
||||
headers = {
|
||||
"Authorization": 'Bearer ' + module.params['grafana_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
}
|
||||
result = requests.post(api_url, json=module.params['dataSource'], headers=headers)
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
elif result.status_code == 409:
|
||||
get_id_url = requests.get(module.params['grafana_url'] + '/api/datasources/id/' + module.params['dataSource']['name'],
|
||||
headers=headers)
|
||||
|
||||
api_url = module.params['grafana_url'] + '/api/datasources/' + str(get_id_url.json()['id'])
|
||||
|
||||
result = requests.put(api_url, json=module.params['dataSource'], headers=headers)
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def absent_datasource(module):
|
||||
if module.params['grafana_url'][-1] == '/':
|
||||
module.params['grafana_url'] = module.params['grafana_url'][:-1]
|
||||
|
||||
api_url = module.params['grafana_url'] + '/api/datasources/name/' + module.params['dataSource']['name']
|
||||
|
||||
result = requests.delete(api_url, headers={
|
||||
"Authorization": 'Bearer ' + module.params['grafana_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
})
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, {"status": result.status_code, 'response': result.json()['message']}
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
module_args = dict(
|
||||
dataSource=dict(type='dict', required=True),
|
||||
grafana_url=dict(type='str', required=True),
|
||||
grafana_api_key=dict(type='str', required=True, no_log=True),
|
||||
state=dict(type='str', required=False, default='present', choices=['present', 'absent'])
|
||||
)
|
||||
|
||||
choice_map = {
|
||||
"present": present_datasource,
|
||||
"absent": absent_datasource,
|
||||
}
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=module_args
|
||||
)
|
||||
|
||||
if not HAS_REQUESTS:
|
||||
module.fail_json(msg=missing_required_lib('requests'))
|
||||
|
||||
is_error, has_changed, result = choice_map.get(
|
||||
module.params['state'])(module)
|
||||
|
||||
if not is_error:
|
||||
module.exit_json(changed=has_changed, output=result)
|
||||
else:
|
||||
module.fail_json(msg=result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
280
ansible_collections/grafana/grafana/plugins/modules/folder.py
Normal file
280
ansible_collections/grafana/grafana/plugins/modules/folder.py
Normal file
|
|
@ -0,0 +1,280 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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)
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: folder
|
||||
author:
|
||||
- Ishan Jain (@ishanjainn)
|
||||
version_added: "0.0.1"
|
||||
short_description: Manage Folders in Grafana
|
||||
description:
|
||||
- Create, Update and delete Folders via Ansible.
|
||||
requirements: [ "requests >= 1.0.0" ]
|
||||
notes:
|
||||
- Does not support C(check_mode).
|
||||
options:
|
||||
title:
|
||||
description:
|
||||
- Sets the title of the folder.
|
||||
type: str
|
||||
required: true
|
||||
uid:
|
||||
description:
|
||||
- Sets the UID for your folder.
|
||||
type: str
|
||||
required: true
|
||||
overwrite:
|
||||
description:
|
||||
- Set to C(false) if you dont want to overwrite existing folder with newer version.
|
||||
type: bool
|
||||
required: false
|
||||
default: true
|
||||
grafana_api_key:
|
||||
description:
|
||||
- Grafana API Key to authenticate with Grafana.
|
||||
type: str
|
||||
required : true
|
||||
grafana_url:
|
||||
description:
|
||||
- URL of the Grafana instance.
|
||||
type: str
|
||||
required: true
|
||||
state:
|
||||
description:
|
||||
- State for the Grafana Folder.
|
||||
choices: [ present, absent ]
|
||||
default: present
|
||||
type: str
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Create/Update a Folder in Grafana
|
||||
grafana.grafana.folder:
|
||||
title: folder_name
|
||||
uid: folder_name
|
||||
overwrite: true
|
||||
grafana_url: "{{ grafana_url }}"
|
||||
grafana_api_key: "{{ grafana_api_key }}"
|
||||
state: present
|
||||
|
||||
- name: Delete a Folder in Grafana
|
||||
grafana.grafana.folder:
|
||||
uid: folder_name
|
||||
grafana_url: "{{ grafana_url }}"
|
||||
grafana_api_key: "{{ grafana_api_key }}"
|
||||
state: absent
|
||||
'''
|
||||
|
||||
RETURN = r'''
|
||||
output:
|
||||
description: Dict object containing folder information.
|
||||
returned: On success
|
||||
type: dict
|
||||
contains:
|
||||
canAdmin:
|
||||
description: Boolean value specifying if current user can admin in folder.
|
||||
returned: state is present and on success
|
||||
type: bool
|
||||
sample: true
|
||||
canDelete:
|
||||
description: Boolean value specifying if current user can delete the folder.
|
||||
returned: state is present and on success
|
||||
type: bool
|
||||
sample: true
|
||||
canEdit:
|
||||
description: Boolean value specifying if current user can edit in folder.
|
||||
returned: state is present and on success
|
||||
type: bool
|
||||
sample: true
|
||||
canSave:
|
||||
description: Boolean value specifying if current user can save in folder.
|
||||
returned: state is present and on success
|
||||
type: bool
|
||||
sample: true
|
||||
created:
|
||||
description: The date when folder was created.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: "2022-10-20T09:31:53Z"
|
||||
createdBy:
|
||||
description: The name of the user who created the folder.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: "Anonymous"
|
||||
hasAcl:
|
||||
description: Boolean value specifying if folder has acl.
|
||||
returned: state is present and on success
|
||||
type: bool
|
||||
sample: true
|
||||
id:
|
||||
description: The ID for the folder.
|
||||
returned: state is present and on success
|
||||
type: int
|
||||
sample: 18
|
||||
title:
|
||||
description: The name of the folder.
|
||||
returned: on success
|
||||
type: str
|
||||
sample: foldername
|
||||
uid:
|
||||
description: The UID for the folder.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: foldername
|
||||
updated:
|
||||
description: The date when the folder was last updated.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: "2022-10-20T09:31:53Z"
|
||||
updatedBy:
|
||||
description: The name of the user who last updated the folder.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: "Anonymous"
|
||||
url:
|
||||
description: The URl for the folder.
|
||||
returned: state is present and on success
|
||||
type: str
|
||||
sample: "/dashboards/f/foldername/foldername"
|
||||
version:
|
||||
description: The version of the folder.
|
||||
returned: state is present and on success
|
||||
type: int
|
||||
sample: 1
|
||||
message:
|
||||
description: The message returned after the operation on the folder.
|
||||
returned: state is absent and on success
|
||||
type: str
|
||||
sample: "Folder has been succesfuly deleted"
|
||||
'''
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
try:
|
||||
import requests
|
||||
HAS_REQUESTS = True
|
||||
except ImportError:
|
||||
HAS_REQUESTS = False
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
def present_folder(module):
|
||||
if module.params['grafana_url'][-1] == '/':
|
||||
module.params['grafana_url'] = module.params['grafana_url'][:-1]
|
||||
|
||||
body = {
|
||||
'uid': module.params['uid'],
|
||||
'title': module.params['title'],
|
||||
}
|
||||
api_url = module.params['grafana_url'] + '/api/folders'
|
||||
|
||||
headers = {
|
||||
"Authorization": 'Bearer ' + module.params['grafana_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
}
|
||||
|
||||
result = requests.post(api_url, json=body, headers=headers)
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
elif result.status_code == 412:
|
||||
sameConfig = False
|
||||
folderInfo = {}
|
||||
|
||||
api_url = module.params['grafana_url'] + '/api/folders'
|
||||
result = requests.get(api_url, headers=headers)
|
||||
|
||||
for folder in result.json():
|
||||
if folder['uid'] == module.params['uid'] and folder['title'] == module.params['title']:
|
||||
sameConfig = True
|
||||
folderInfo = folder
|
||||
|
||||
if sameConfig:
|
||||
return False, False, folderInfo
|
||||
else:
|
||||
body = {
|
||||
'uid': module.params['uid'],
|
||||
'title': module.params['title'],
|
||||
'overwrite': module.params['overwrite']
|
||||
}
|
||||
api_url = module.params['grafana_url'] + '/api/folders/' + module.params['uid']
|
||||
|
||||
result = requests.put(api_url, json=body, headers=headers)
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def absent_folder(module):
|
||||
if module.params['grafana_url'][-1] == '/':
|
||||
module.params['grafana_url'] = module.params['grafana_url'][:-1]
|
||||
|
||||
sameConfig = False
|
||||
|
||||
api_url = module.params['grafana_url'] + '/api/folders'
|
||||
headers = {
|
||||
"Authorization": 'Bearer ' + module.params['grafana_api_key'],
|
||||
'User-Agent': 'grafana-ansible-collection',
|
||||
}
|
||||
result = requests.get(api_url, headers=headers)
|
||||
|
||||
for folder in result.json():
|
||||
if folder['uid'] == module.params['uid'] and folder['title'] == module.params['title']:
|
||||
sameConfig = True
|
||||
if sameConfig is True:
|
||||
api_url = module.params['grafana_url'] + '/api/folders/' + module.params['uid']
|
||||
|
||||
result = requests.delete(api_url, headers=headers)
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, {"status": result.status_code, 'response': "Folder has been succesfuly deleted"}
|
||||
else:
|
||||
return True, False, {"status": result.status_code, 'response': "Error deleting folder"}
|
||||
else:
|
||||
return False, True, {"status": 200, 'response': "Folder does not exist"}
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
module_args = dict(
|
||||
title=dict(type='str', required=True),
|
||||
uid=dict(type='str', required=True),
|
||||
overwrite=dict(type='bool', required=False, default=True),
|
||||
grafana_url=dict(type='str', required=True),
|
||||
grafana_api_key=dict(type='str', required=True, no_log=True),
|
||||
state=dict(type='str', required=False, default='present', choices=['present', 'absent'])
|
||||
)
|
||||
|
||||
choice_map = {
|
||||
"present": present_folder,
|
||||
"absent": absent_folder,
|
||||
}
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=module_args
|
||||
)
|
||||
|
||||
if not HAS_REQUESTS:
|
||||
module.fail_json(msg=missing_required_lib('requests'))
|
||||
|
||||
is_error, has_changed, result = choice_map.get(
|
||||
module.params['state'])(module)
|
||||
|
||||
if not is_error:
|
||||
module.exit_json(changed=has_changed, output=result)
|
||||
else:
|
||||
module.fail_json(msg=result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
284
ansible_collections/grafana/grafana/plugins/modules/user.py
Normal file
284
ansible_collections/grafana/grafana/plugins/modules/user.py
Normal file
|
|
@ -0,0 +1,284 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2024, téïcée (www.teicee.com)
|
||||
# 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)
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: user
|
||||
author:
|
||||
- Mathieu Valois, téïcée
|
||||
version_added: "0.0.1"
|
||||
short_description: Manage Users in Grafana
|
||||
description:
|
||||
- Create, Update and delete Users using Ansible.
|
||||
requirements: [ "requests >= 1.0.0" ]
|
||||
notes:
|
||||
- Does not support C(check_mode).
|
||||
- Does not support C(Idempotency).
|
||||
options:
|
||||
grafana_url:
|
||||
description:
|
||||
- URL of the Grafana instance.
|
||||
type: str
|
||||
required: true
|
||||
admin_name:
|
||||
description:
|
||||
- Grafana admin username
|
||||
type: str
|
||||
required : true
|
||||
admin_password:
|
||||
description:
|
||||
- Grafana admin password
|
||||
type: str
|
||||
required : true
|
||||
login:
|
||||
description:
|
||||
- Login of the user
|
||||
type: str
|
||||
required : true
|
||||
password:
|
||||
description:
|
||||
- Password of the user. Should be provided if state=present
|
||||
type: str
|
||||
required : false
|
||||
name:
|
||||
description:
|
||||
- Name of the user.
|
||||
type: str
|
||||
required : false
|
||||
email:
|
||||
description:
|
||||
- Email address of the user.
|
||||
type: str
|
||||
required : false
|
||||
state:
|
||||
description:
|
||||
- State for the Grafana User.
|
||||
choices: [ present, absent ]
|
||||
default: present
|
||||
type: str
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Create/Update a user
|
||||
grafana.grafana.user:
|
||||
login: "grafana_user"
|
||||
password: "{{ lookup('ansible.builtin.password') }}"
|
||||
email: "grafana_user@localhost.local
|
||||
name: "grafana user"
|
||||
grafana_url: "{{ grafana_url }}"
|
||||
admin_name: "admin"
|
||||
admin_password: "admin"
|
||||
state: present
|
||||
|
||||
- name: Delete user
|
||||
grafana.grafana.user:
|
||||
login: "grafana_user"
|
||||
grafana_url: "{{ grafana_url }}"
|
||||
admin_name: "admin"
|
||||
admin_password: "admin"
|
||||
state: absent
|
||||
'''
|
||||
|
||||
RETURN = r'''
|
||||
output:
|
||||
description: Dict object containing user information and message.
|
||||
returned: On success
|
||||
type: dict
|
||||
contains:
|
||||
id:
|
||||
description: The ID for the user.
|
||||
returned: on success
|
||||
type: int
|
||||
sample: 17
|
||||
email:
|
||||
description: The email for the user.
|
||||
returned: on success
|
||||
type: str
|
||||
sample: grafana_user@localhost.local
|
||||
name:
|
||||
description: The name for the user.
|
||||
returned: on success
|
||||
type: str
|
||||
sample: grafana user
|
||||
login:
|
||||
description: The login for the user.
|
||||
returned: on success
|
||||
type: str
|
||||
sample: grafana_user
|
||||
'''
|
||||
|
||||
try:
|
||||
import requests
|
||||
HAS_REQUESTS = True
|
||||
except ImportError:
|
||||
HAS_REQUESTS = False
|
||||
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
def _get_user(grafana_url, admin_name, admin_password, login, email=None):
|
||||
get_user_url = grafana_url + '/api/users/lookup?loginOrEmail='
|
||||
|
||||
# check if user exists by login provided login
|
||||
result = requests.get(f"{get_user_url}{login}", auth=requests.auth.HTTPBasicAuth(
|
||||
admin_name, admin_password))
|
||||
# if no user has this login, check the email if provided
|
||||
if result.status_code == 404 and email is not None:
|
||||
result = requests.get(f"{get_user_url}{email}", auth=requests.auth.HTTPBasicAuth(
|
||||
admin_name, admin_password))
|
||||
|
||||
if result.status_code == 404:
|
||||
return None
|
||||
|
||||
return result.json()
|
||||
|
||||
|
||||
def _set_user_password(grafana_url, admin_name, admin_password, user_id, password):
|
||||
""" sets the password for the existing user having user_id.
|
||||
admin_name should be a user having users.password:write permission
|
||||
"""
|
||||
|
||||
set_user_password_url = f"{grafana_url}/api/admin/users/{user_id}/password"
|
||||
|
||||
result = requests.put(set_user_password_url, json={'password': password}, auth=requests.auth.HTTPBasicAuth(
|
||||
admin_name, admin_password))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def present_user(module):
|
||||
|
||||
if module.params['grafana_url'][-1] == '/':
|
||||
module.params['grafana_url'] = module.params['grafana_url'][:-1]
|
||||
|
||||
body = {
|
||||
'login': module.params['login'],
|
||||
'password': module.params['password'],
|
||||
'email': module.params['email'],
|
||||
'name': module.params['name'],
|
||||
'OrgId': module.params['orgid']
|
||||
}
|
||||
|
||||
user = _get_user(module.params['grafana_url'], module.params['admin_name'],
|
||||
module.params['admin_password'], module.params['login'], module.params['email'])
|
||||
|
||||
if user is None:
|
||||
api_url = module.params['grafana_url'] + '/api/admin/users'
|
||||
result = requests.post(api_url, json=body, auth=requests.auth.HTTPBasicAuth(
|
||||
module.params['admin_name'], module.params['admin_password']))
|
||||
else:
|
||||
user_id = user['id']
|
||||
api_url = module.params['grafana_url'] + '/api/users'
|
||||
result = requests.put(f"{api_url}/{user_id}", json=body, auth=requests.auth.HTTPBasicAuth(
|
||||
module.params['admin_name'], module.params['admin_password']))
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def absent_user(module):
|
||||
if module.params['grafana_url'][-1] == '/':
|
||||
module.params['grafana_url'] = module.params['grafana_url'][:-1]
|
||||
|
||||
user = _get_user(module.params['grafana_url'], module.params['admin_name'],
|
||||
module.params['admin_password'], module.params['login'], module.params['email'])
|
||||
|
||||
if user is None:
|
||||
return False, False, "User does not exist"
|
||||
|
||||
user_id = user['id']
|
||||
api_url = f"{module.params['grafana_url']}/api/admin/users/{user_id}"
|
||||
result = requests.delete(api_url, auth=requests.auth.HTTPBasicAuth(
|
||||
module.params['admin_name'], module.params['admin_password']))
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
|
||||
return True, False, {"status": result.status_code, 'response': result.json()['message']}
|
||||
|
||||
|
||||
def password_user(module):
|
||||
if module.params['grafana_url'][-1] == '/':
|
||||
module.params['grafana_url'] = module.params['grafana_url'][:-1]
|
||||
|
||||
# try with new password to check if already changed
|
||||
user = _get_user(module.params['grafana_url'], module.params['login'],
|
||||
module.params['password'], module.params['login'], module.params['email'])
|
||||
|
||||
if 'id' in user:
|
||||
# Auth is OK, password does not need to be changed
|
||||
return False, False, {'message': 'Password has already been changed', 'user': user}
|
||||
|
||||
# from here, we begin password change procedure
|
||||
user = _get_user(module.params['grafana_url'], module.params['admin_name'],
|
||||
module.params['admin_password'], module.params['login'], module.params['email'])
|
||||
|
||||
if user is None:
|
||||
return True, False, "User does not exist"
|
||||
|
||||
if 'id' not in user:
|
||||
return True, False, user
|
||||
|
||||
result = _set_user_password(module.params['grafana_url'], module.params['admin_name'],
|
||||
module.params['admin_password'], user['id'], module.params['password'])
|
||||
|
||||
if result.status_code == 200:
|
||||
return False, True, result.json()
|
||||
|
||||
return True, False, result.json()
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
# Grafana admin API is only accessible with basic auth, not token
|
||||
# So we shall provide admin name and its password
|
||||
module_args = dict(
|
||||
admin_name=dict(type='str', required=True),
|
||||
admin_password=dict(type='str', required=True, no_log=True),
|
||||
login=dict(type='str', required=True),
|
||||
password=dict(type='str', required=False, no_log=True),
|
||||
email=dict(type='str', required=False),
|
||||
name=dict(type='str', required=False),
|
||||
orgid=dict(type='int', required=False),
|
||||
grafana_url=dict(type='str', required=True),
|
||||
state=dict(type='str', required=False, default='present',
|
||||
choices=['present', 'absent', 'update_password'])
|
||||
)
|
||||
|
||||
choice_map = {
|
||||
"present": present_user,
|
||||
"absent": absent_user,
|
||||
"update_password": password_user
|
||||
}
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=module_args
|
||||
)
|
||||
|
||||
if not HAS_REQUESTS:
|
||||
module.fail_json(msg=missing_required_lib('requests'))
|
||||
|
||||
if module.params['state'] in ('present', 'update_password') and 'password' not in module.params:
|
||||
module.fail_json(
|
||||
msg="Want to create or update user but password is missing")
|
||||
|
||||
is_error, has_changed, result = choice_map.get(
|
||||
module.params['state'])(module)
|
||||
|
||||
if not is_error:
|
||||
module.exit_json(changed=has_changed, output=result)
|
||||
else:
|
||||
module.fail_json(msg=result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Loading…
Add table
Add a link
Reference in a new issue