#!/usr/bin/python3 from ansible.module_utils.basic import AnsibleModule import requests import json class InfluxdbSetup: def __init__(self, api_url): self.api_url = api_url def already(self): url = '{}/api/v2/setup'.format(self.api_url) r = requests.get(url) if r.status_code != 200: raise Exception( 'Influxdb', 'Bad status code {}: {}'.format(r.status_code, r.text) ) data = json.loads(r.text) if 'allowed' not in data or data['allowed'] is True: return False return True def run(self, username, org, bucket, token): url = '{}/api/v2/setup'.format(self.api_url) r = requests.post(url, json={ 'username': username, 'org': org, 'bucket': bucket, 'token': token, }) if r.status_code != 201: raise Exception( 'Influxdb', 'Bad status code {}: {}'.format(r.status_code, r.text) ) def main(): fields = { 'username': {'type': 'str', 'required': True}, 'org': {'type': 'str', 'required': True}, 'bucket': {'type': 'str', 'required': True}, 'token': {'type': 'str', 'required': True}, 'api_url': {'type': 'str', 'default': 'http://127.0.0.1:8086'}, } module = AnsibleModule(argument_spec=fields) setup = InfluxdbSetup( module.params['api_url'], ) if setup.already() is True: module.exit_json(changed=False) setup.run( module.params['username'], module.params['org'], module.params['bucket'], module.params['token'], ) module.exit_json(changed=True) if __name__ == '__main__': main()