Adding first 8 modules

This commit is contained in:
Ishan Jain 2022-08-09 12:07:47 +05:30
parent 627c22b9fd
commit f71f99f999
9 changed files with 1344 additions and 1 deletions

View File

@ -1 +0,0 @@
# ansible-collection

View File

@ -0,0 +1,199 @@
#!/usr/bin/python
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.
options:
name:
description:
- Name of the contact point
type: str
required: true
uid:
description:
- Sets the UID of the Contact point.
type: str
required: true
type:
description:
- Contact point type
type: str
required: true
settings:
description:
- Contact point settings
type: dict
required: true
DisableResolveMessage:
description:
- When set to True, Disables the resolve message [OK] that is sent when alerting state returns to false
type: bool
default: false
grafana_api_key:
description:
- Grafana API Key used to authenticate with Grafana.
type: str
required : true
state:
description:
- State for the Grafana CLoud stack.
choices: [ present, absent ]
type: str
default: present
'''
EXAMPLES = '''
- name: Create/Update Alerting contact point
alert_contact_point:
name: ops-email
uid: opsemail
type: email
settings: {
addresses: "ops@mydomain.com,devs@mydomain.com"
}
stack_slug: "{{ stack_slug }}"
grafana_api_key: "{{ grafana_api_key }}"
state: present
- name: Delete Alerting contact point
alert_contact_point:
name: ops-email
uid: opsemail
type: email
settings: {
addresses: "ops@mydomain.com,devs@mydomain.com"
}
stack_slug: "{{ stack_slug }}"
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
name:
description: The name for the contact point
returned: state is present and on success
type: str
settings:
description: Contains contact point settings
returned: state is present and on success
type: dict
uid:
description: The UID for the contact point
returned: state is present and on success
type: str
type:
description: The type of contact point
returned: state is present and on success
type: str
'''
from ansible.module_utils.basic import AnsibleModule
import requests
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']
}
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/v1/provisioning/contact-points'
result = requests.post(api_url, json=body, headers={"Authorization": 'Bearer ' + module.params['grafana_api_key']})
if result.status_code == 202:
return False, True, result.json()
elif result.status_code == 500:
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/v1/provisioning/contact-points/' + \
module.params['uid']
result = requests.put(api_url, json=body, headers={"Authorization": 'Bearer ' + module.params['grafana_api_key']})
if result.status_code == 202:
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/v1/provisioning/contact-points'
result = requests.get(api_url, headers={"Authorization": 'Bearer ' + module.params['grafana_api_key']})
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
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/v1/provisioning/contact-points'
result = requests.get(api_url, headers={"Authorization": 'Bearer ' + module.params['grafana_api_key']})
for contact_points in result.json():
if contact_points['uid'] == module.params['uid']:
already_exists = True
if already_exists:
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/v1/provisioning/contact-points/' + \
module.params['uid']
result = requests.delete(api_url, 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']}
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),
stack_slug=dict(type='str', required=True),
grafana_api_key=dict(type='str', required=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,
supports_check_mode=True
)
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()

View File

@ -0,0 +1,188 @@
#!/usr/bin/python
DOCUMENTATION = '''
---
module: alert_notification_policy
author:
- Ishan Jain (@ishanjainn)
version_added: "0.0.1"
short_description: Sets the notification policy tree in Grafana Alerting
description:
- Set the notification policy tree using Ansible
options:
Continue:
description:
- Continue matching subsequent sibling nodes if set to `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: []
MuteTimeIntervals:
description:
- List of string.
- Add mute timing to policy
type: list
default: []
root_policy_receiver:
description:
- Name of the contact point to set as the default receiver
type: str
default: grafana-default-email
Routes:
description:
- List of objects
- A Route is a node that contains definitions of how to handle alerts.
type: list
required: true
groupInterval:
description:
- The waiting time to send a batch of new alerts for that group after the first notification was sent. If empty it will be inherited from the parent policy.
type: str
default: 5m
groupWait:
description:
- The waiting time until the initial notification is sent for a new group created by an incoming alert. If empty it will be inherited from the parent policy.
type: str
default: 30s
objectMatchers:
description:
- State for the Grafana CLoud stack.
type: str
default: present
choices: [ present, absent ]
repeatInterval:
description:
- The waiting time to resend an alert after they have successfully been sent.
type: str
default: 4h
stack_slug:
description:
- Name of the Grafana Cloud stack to which the notification policies will be added
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
alert_notification_policy:
stack_slug: "{{ stack_slug }}"
grafana_api_key: "{{ grafana_api_key }}"
routes: [
{
receiver: myReceiver,
object_matchers: [["env", "=", "Production"]],
}
]
- name: Set nested Notification policies
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"]]
}
]
stack_slug: "{{ stack_slug }}"
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
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
provenance:
description:
returned: on success
type: str
receiver:
description: The name of the default contact point
returned: state is present and on success
type: str
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
routes:
description: The entire notification tree returned as a list
returned: on success
type: list
'''
from ansible.module_utils.basic import AnsibleModule
import requests
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['root_policy_receiver'], 'group_interval': module.params['groupInterval'],
'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.put(api_url, json=body, headers={"Authorization": 'Bearer ' + module.params['grafana_api_key']})
if result.status_code == 202:
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']})
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=[]),
muteTimeIntervals=dict(type='list', required=False, default=[]),
root_policy_receiver=dict(type='str', required=False, default='grafana-default-email'),
routes=dict(type='list', required=True),
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=[]),
stack_slug=dict(type='str', required=True),
grafana_api_key=dict(type='str', required=True), )
module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
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()

View File

@ -0,0 +1,128 @@
#!/usr/bin/python
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.
options:
name:
description:
- Name of the Grafana Cloud API key.
type: str
required: true
role:
description:
- Role to be associated with the CLoud API key.
type: str
required: true
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 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 stack.
type: str
default: present
choices: [ present, absent ]
'''
EXAMPLES = '''
- name: Create Grafana Cloud API key
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
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
import requests
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']})
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']})
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),
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,
supports_check_mode=True
)
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()

View File

@ -0,0 +1,148 @@
#!/usr/bin/python
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 stacks using Ansible.
options:
name:
description:
- Name of the plugin, e.g. grafana-github-datasource .
type: str
required: true
version:
description:
- Version of the plugin to install. Defaults to latest.
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 stack.
type: str
default: present
choices: [ present, absent ]
'''
EXAMPLES = '''
- name: Create/Update a plugin
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
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
latest_version:
description: Latest version available for the plugin
returned: On success
type: str
pluginId:
description: Id for the Plugin
returned: On success
type: int
pluginName:
description: Name of the plugin
returned: On success
type: str
pluginSlug:
description: Slug for the Plugin
returned: On success
type: str
'''
from ansible.module_utils.basic import AnsibleModule
import requests
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'
result = requests.post(api_url, json=body, headers={"Authorization": 'Bearer ' + module.params['cloud_api_key']})
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.post(api_url, json={'version': module.params['version']},
headers={"Authorization": 'Bearer ' + module.params['cloud_api_key']})
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']})
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),
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,
supports_check_mode=True
)
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()

View File

@ -0,0 +1,186 @@
#!/usr/bin/python
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.
options:
name:
description:
- Name of stack. Conventionally matches the URL of the instance. For example, "<stack_slug>.grafana.net".
type: str
required: true
stack_slug:
description:
- Subdomain that the Grafana instance will be available at. For example, if you set the slug to <stack_slug>, the instance will be available at https://<stack_slug>.grafana.net
type: str
required: true
cloud_api_key:
description:
- CLoud API Key to authenticate with Grafana Cloud.
type: str
required : true
region:
description:
- Choose a region for your 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. For example, https://grafana.yourdoman.io.
type: str
default: https://<stack_slug>.grafana.net
org_slug:
description:
- Name of the organization under which Cloud stack is created.
type: str
required: false
state:
description:
- State for the Grafana CLoud stack.
type: str
default: present
choices: [ present, absent ]
'''
EXAMPLES = '''
- name: Create a Grafana Cloud stack
cloud_stack:
name: company_name
slug: company_name
cloud_api_key: "{{ grafana_cloud_api_key }}"
region: eu
url: https://grafana.company_name.com
state: present
- name: Delete a Grafana Cloud stack
cloud_stack:
name: company_name
slug: company_name
cloud_api_key: "{{ grafana_cloud_api_key }}"
state: absent
'''
RETURN = r'''
alertmanager_name:
description: Name of the alertmanager instance
returned: always
type: str
alertmanager_url:
description: URL of the alertmanager instance
returned: always
type: str
cluster_slug:
description: Slug for the cluster where the Grafana stack is deployed
returned: always
type: str
id:
description: ID of the Grafana Cloud stack
returned: always
type: int
loki_url:
description: URl for the Loki instance
returned: always
type: str
orgID:
description: ID of the Grafana Cloud organization
returned: always
type: int
prometheus_url:
description: URl for the Prometheus instance
returned: always
type: url
tempo_url:
description: URl for the Tempo instance
returned: always
type: url
url:
description: URL of the Grafana Cloud stack
returned: always
type: str
'''
from ansible.module_utils.basic import AnsibleModule
import requests
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']
}
api_url = 'https://grafana.com/api/instances'
result = requests.post(api_url, json=body, headers={"Authorization": 'Bearer ' + module.params['cloud_api_key']})
if result.status_code == 200:
return False, True, result.json()
elif (result.status_code == 409 and result.json()['message'] == "That url is not available") or (result.status_code == 403 and result.json()['message'] == "Hosted instance limit reached"):
api_url = 'https://grafana.com/api/orgs/' + module.params['org_slug'] + '/instances'
result = requests.get(api_url, headers={"Authorization": 'Bearer ' + module.params['cloud_api_key']})
for stack in result.json()['items']:
if stack['slug'] == module.params['stack_slug']:
return False, False, stack
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']})
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),
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'])
)
choice_map = {
"present": present_cloud_stack,
"absent": absent_cloud_stack,
}
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
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'])
else:
module.fail_json(msg=result)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,150 @@
#!/usr/bin/python
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.
options:
dashboard:
description:
- JSON source code for dashboard
type: dict
required: true
stack_slug:
description:
- Name of the Grafana Cloud stack to which the notification policies 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 stack.
choices: [ present, absent ]
default: present
type: str
'''
EXAMPLES = '''
- name: Create/Update a dashboard
dashboard:
datasource: "{{ lookup('file', 'dashboard.json') }}"
stack_slug: "{{ stack_slug }}"
cloud_api_key: "{{ grafana_cloud_api_key }}"
state: present
- name: Delete dashboard
dashboard:
datasource: "{{ lookup('file', 'dashboard.json') }}"
stack_slug: "{{ stack_slug }}"
cloud_api_key: "{{ grafana_cloud_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
slug:
description: The slug for the dashboard
returned: state is present and on success
type: str
status:
description: The status of the dashboard
returned: state is present and on success
type: str
uid:
description: The UID for the dashboard
returned: state is present and on success
type: str
url:
description: The endpoint for the dashboard
returned: state is present and on success
type: str
version:
description: The version of the dashboard
returned: state is present and on success
type: int
message:
description: The message returned after the operation on the dashboard
returned: state is absent and on success
type: str
title:
description: The name of the dashboard
returned: state is absent and on success
type: str
'''
from ansible.module_utils.basic import AnsibleModule
import requests
def present_dashboard(module):
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/dashboards/db'
result = requests.post(api_url, json=module.params['dashboard'], headers={"Authorization": 'Bearer ' + module.params['cloud_api_key']})
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 'uid' not in module.params['dashboard']['dashboard']:
return True, False, "UID is not defined in the the Dashboard configuration"
api_url = api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/dashboards/uid/' + module.params['dashboard']['dashboard']['uid']
result = requests.delete(api_url, headers={"Authorization": 'Bearer ' + module.params['cloud_api_key']})
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),
stack_slug=dict(type='str', required=True),
cloud_api_key=dict(type='str', required=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,
supports_check_mode=True
)
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()

View File

@ -0,0 +1,142 @@
#!/usr/bin/python
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.
options:
datasource:
description:
- JSON source code for the Data source
type: dict
required: true
stack_slug:
description:
- Name of the Grafana Cloud stack to which the notification policies 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 stack.
choices: [ present, absent ]
default: present
type: str
'''
EXAMPLES = '''
- name: Create/Update Data sources
datasource:
datasource: "{{ lookup('file', 'datasource.json') }}"
stack_slug: "{{ stack_slug }}"
cloud_api_key: "{{ grafana_cloud_api_key }}"
state: present
- name: Delete Data sources
datasource:
datasource: "{{ lookup('file', 'datasource.json') }}"
stack_slug: "{{ stack_slug }}"
cloud_api_key: "{{ grafana_cloud_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
id:
description: The ID assigned to the data source
returned: on success
type: int
name:
description: The name of the data source defined in the JSON source code
returned: state is present and on success
type: str
message:
description: The message returned after the operation on the Data source
returned: on success
type: str
'''
from ansible.module_utils.basic import AnsibleModule
import requests
def present_datasource(module):
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/datasources'
result = requests.post(api_url, json=module.params['datasource'], headers={"Authorization": 'Bearer ' + module.params['cloud_api_key']})
if result.status_code == 200:
return False, True, result.json()
elif result.status_code == 409:
get_id_url = requests.get('https://' + module.params['stack_slug'] + '.grafana.net/api/datasources/id/' + module.params['datasource']['name'], headers={"Authorization": 'Bearer ' + module.params['cloud_api_key']})
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/datasources/' + str(get_id_url.json()['id'])
result = requests.put(api_url, json=module.params['datasource'], headers={"Authorization": 'Bearer ' + module.params['cloud_api_key']})
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):
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/datasources/' + module.params['datasource']['name']
result = requests.delete(api_url, headers={"Authorization": 'Bearer ' + module.params['cloud_api_key']})
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(
datasource=dict(type='dict', required=True),
stack_slug=dict(type='str', required=True),
cloud_api_key=dict(type='str', required=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,
supports_check_mode=True
)
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()

203
plugins/modules/folder.py Normal file
View File

@ -0,0 +1,203 @@
#!/usr/bin/python
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.
options:
title:
description:
- The title of the folder.
type: str
required: true
uid:
description:
- unique identifier for your folder.
type: str
required: true
overwrite:
description:
- Set to false if you dont want to overwrite existing folder with newer version.
type: str
required: false
default: true
cloud_api_key:
description:
- CLoud API Key to authenticate with Grafana Cloud.
type: str
required : true
state:
description:
- State for the Grafana CLoud stack.
choices: [ present, absent ]
default: present
type: str
'''
EXAMPLES = '''
- name: Create/Update a Folder in Grafana
folder:
title: folder_name
uid: folder_name
overwrite: true
stack_slug: "{{ stack_slug }}"
cloud_api_key: "{{ grafana_cloud_api_key }}"
state: present
- name: Delete a Folder in Grafana
folder:
uid: folder_name
stack_slug: "{{ stack_slug }}"
cloud_api_key: "{{ grafana_cloud_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
canDelete:
description: Boolean value specifying if current user can delete the folder
returned: state is present and on success
type: bool
canEdit:
description: Boolean value specifying if current user can edit in folder
returned: state is present and on success
type: bool
canSave:
description: Boolean value specifying if current user can save in folder
returned: state is present and on success
type: bool
created:
description: The date when folder was created
returned: state is present and on success
type: str
createdBy:
description: The name of the user who created the folder
returned: state is present and on success
type: str
hasAcl:
description: Boolean value specifying if folder has acl
returned: state is present and on success
type: bool
id:
description: The ID for the folder
returned: on success
type: int
title:
description: The name of the folder
returned: on success
type: str
uid:
description: The UID for the folder
returned: state is present and on success
type: str
updated:
description: The date when the folder was last updated
returned: state is present and on success
type: str
updatedBy:
description: The name of the user who last updated the folder
returned: state is present and on success
type: str
url:
description: The URl for the folder
returned: state is present and on success
type: str
version:
description: The version of the folder
returned: state is present and on success
type: int
message:
description: The message returned after the operation on the folder
returned: state is absent and on success
type: str
'''
from ansible.module_utils.basic import AnsibleModule
import requests
def present_folder(module):
body = {
'uid': module.params['uid'],
'title': module.params['title'],
}
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/folders'
result = requests.post(api_url, json=body, headers={"Authorization": 'Bearer ' + module.params['cloud_api_key']})
if result.status_code == 200:
return False, True, result.json()
elif result.status_code == 412:
body = {
'uid': module.params['uid'],
'title': module.params['title'],
'overwrite': module.params['overwrite']
}
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/folders/' + module.params['uid']
result = requests.put(api_url, json=body, headers={"Authorization": 'Bearer ' + module.params['cloud_api_key']})
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):
api_url = 'https://' + module.params['stack_slug'] + '.grafana.net/api/folders/' + module.params['uid']
result = requests.delete(api_url, headers={"Authorization": 'Bearer ' + module.params['cloud_api_key']})
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(
title=dict(type='str', required=True),
uid=dict(type='str', required=True),
overwrite=dict(type='bool', required=False, default=True),
stack_slug=dict(type='str', required=True),
cloud_api_key=dict(type='str', required=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,
supports_check_mode=True
)
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()