ansible-role-influxdb/library/influxdb_org.py

112 lines
3.2 KiB
Python

#!/usr/bin/python3
from ansible.module_utils.basic import AnsibleModule
import requests
import json
class InfluxdbOrg:
def __init__(self, api_url, api_token, name):
self.api_url = api_url
self.headers = {'Authorization': 'Token {}'.format(api_token)}
self.name = name
def exists(self):
url = '{}/api/v2/orgs'.format(self.api_url)
r = requests.get(url, headers=self.headers, params={'org': self.name})
if r.status_code == 404:
return False
elif r.status_code == 200:
data = json.loads(r.text)
for org in data['orgs']:
if org['name'] == self.name:
self.id = org['id']
self.description = org['description']
return True
return False
raise Exception(
'Influxdb',
'Bad status code {}: {}'.format(r.status_code, r.text)
)
def has_changed(self, description):
if self.description == description:
return False
return True
def create(self, description):
url = '{}/api/v2/orgs'.format(self.api_url)
r = requests.post(
url,
headers=self.headers,
json={'name': self.name, 'description': description}
)
if r.status_code != 201:
raise Exception(
'Influxdb',
'Bad status code {}: {}'.format(r.status_code, r.text)
)
def delete(self):
url = '{}/api/v2/orgs/{}'.format(self.api_url, self.id)
r = requests.delete(url, headers=self.headers)
if r.status_code != 204:
raise Exception(
'Influxdb',
'Bad status code {}: {}'.format(r.status_code, r.text)
)
def update(self, description):
url = '{}/api/v2/orgs/{}'.format(self.api_url, self.id)
r = requests.patch(
url,
headers=self.headers,
json={'name': self.name, 'description': description}
)
if r.status_code != 200:
raise Exception(
'Influxdb',
'Bad status code {}: {}'.format(r.status_code, r.text)
)
def main():
fields = {
'name': {'type': 'str', 'required': True},
'description': {'type': 'str', 'default': ''},
'api_url': {'type': 'str', 'default': 'http://127.0.0.1:8086'},
'api_token': {'type': 'str', 'required': True},
'state': {'type': 'str',
'default': 'present',
'choice': ['present', 'absent']},
}
module = AnsibleModule(argument_spec=fields)
org = InfluxdbOrg(
module.params['api_url'],
module.params['api_token'],
module.params['name'],
)
changed = False
if org.exists():
if module.params['state'] == 'absent':
org.delete()
changed = True
elif org.has_changed(module.params['description']):
org.update(module.params['description'])
changed = True
elif module.params['state'] == 'present':
org.create(module.params['description'])
changed = True
module.exit_json(changed=changed)
if __name__ == '__main__':
main()