Skip to content

Commit

Permalink
Merge pull request #7 from tbauriedel/enhancement/refacter-lib
Browse files Browse the repository at this point in the history
Make functions more usable
  • Loading branch information
tbauriedel authored Jan 11, 2024
2 parents dd39616 + dbce345 commit 77bb467
Show file tree
Hide file tree
Showing 5 changed files with 100 additions and 80 deletions.
1 change: 0 additions & 1 deletion .github/workflows/yamllint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ jobs:
steps:
- name: Check out the codebase.
uses: actions/checkout@v4

- name: Set up Python 3.
uses: actions/setup-python@v4
with:
Expand Down
134 changes: 76 additions & 58 deletions plugins/module_utils/utils.py
Original file line number Diff line number Diff line change
@@ -1,121 +1,139 @@
"""InfluxDB v2 API utilites"""
#!/usr/bin/python3

import json
import requests

class InfluxApi():
class Influx2Api:
'''
Common api requests to for InfluxDBv2
'''
def get_bucket_status(module):
'''
Get state of single bucket of org from InfluxDB. Returns 'present' if found and 'absent' if not present.
'''
headers = {
'Authorization': 'Token ' + module.params['token']
}

url = module.params['host'] + '/api/v2/buckets?name=' + module.params['name'] + "&orgID=" + InfluxApi.get_orgID_by_name(module)
response = requests.get(url, headers=headers)
json_resp = json.loads(response.content)
api_token: str
endpoint: str
timeout: int

if "code" in json_resp:
if json_resp["code"] == "not found":
return "absent"
def __init__(self, token, host) -> None:
'''
Initialize API class
'''
self.api_token, self.endpoint, self.timeout = token, host, 10

for bucket in json_resp["buckets"]:
if bucket['name'] == module.params['name']:
return 'present'
else:
return 'absent'

# Organizations

def get_all_orgs(module):
def get_all_orgs(self) -> json:
'''
Get all organizations from InfluxDB. Queries.
Returns JSON.
'''

headers = {
'Authorization': 'Token ' + module.params['token']
'Authorization': 'Token ' + self.api_token
}
response = requests.get(module.params['host'] + '/api/v2/orgs', headers=headers)
response = requests.get(self.endpoint + '/api/v2/orgs', headers=headers, timeout=self.timeout)

return json.loads(response.content)


def get_orgID_by_name(module):
def get_orgid_by_name(self, name) -> str:
'''
Get organization ID by name. Returns ID
If no organization is found by name, 'not found' will be returned.
'''

orgs = InfluxApi.get_all_orgs(module)
orgs = self.get_all_orgs()

for org in orgs['orgs']:
if org['name'] == module.params['org']:
if org['name'] == name:
return org['id']

return "not found"


def create_bucket(module):
# Buckets

def get_bucketid_by_name(self, name, org): # pyling
'''
Create bucket
Get bucket ID by name. Returns ID
If no bucket is found by name, 'not found' will be returned
'''

headers = {
'Authorization': 'Token ' + module.params['token'],
'Content-type': 'application/json'
'Authorization': 'Token ' + self.api_token
}

url = module.params['host'] + '/api/v2/buckets'
payload = {
'orgID': InfluxApi.get_orgID_by_name(module),
'name': module.params['name'],
'retentionRules': [
{
'type': module.params['retention']['type'],
'everySeconds': int(module.params['retention']['everySeconds']),
'shardGroupDurationSeconds': int(module.params['retention']['shardGroupDurationSeconds'])
}
]
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
url = self.endpoint + '/api/v2/buckets?name=' + name + "&orgID=" + self.get_orgid_by_name(org)
response = requests.get(url, headers=headers, timeout=self.timeout)
json_resp = json.loads(response.content)

return response.status_code, response.content
for bucket in json_resp['buckets']:
return bucket['id']

return "not found"


def get_bucketID_by_name(module):
def get_bucket_status(self, name, org_id):
'''
Get bucket ID by name. Returns ID
If no bucket is found by name, 'not found' will be returned
Get state of single bucket of org from InfluxDB. Returns 'present' if found and 'absent' if not present.
'''

headers = {
'Authorization': 'Token ' + module.params['token']
'Authorization': 'Token ' + self.api_token
}

url = module.params['host'] + '/api/v2/buckets?name=' + module.params['name'] + "&orgID=" + InfluxApi.get_orgID_by_name(module)
response = requests.get(url, headers=headers)
url = self.endpoint + '/api/v2/buckets?name=' + name + "&orgID=" + org_id
response = requests.get(url, headers=headers, timeout=self.timeout)
json_resp = json.loads(response.content)

for bucket in json_resp['buckets']:
return bucket['id']
if "code" in json_resp:
if json_resp["code"] == "not found":
return "absent"

return "not found"
for bucket in json_resp["buckets"]:
if bucket['name'] == name:
return 'present'

return 'absent'


def delete_bucket(module):
def create_bucket(self, name, org_id, retention):
'''
Create bucket
'''

headers = {
'Authorization': 'Token ' + self.api_token,
'Content-type': 'application/json'
}

url = self.endpoint + '/api/v2/buckets'
payload = {
'orgID': org_id,
'name': name,
'retentionRules': [
{
'type': retention['type'],
'everySeconds': int(retention['everySeconds']),
'shardGroupDurationSeconds': int(retention['shardGroupDurationSeconds'])
}
]
}
response = requests.post(url, headers=headers, data=json.dumps(payload), timeout=self.timeout)

return response.status_code, response.content


def delete_bucket(self, name, org):
'''
Delete bucket
'''

headers = {
'Authorization': 'Token ' + module.params['token']
'Authorization': 'Token ' + self.api_token
}

url = module.params['host'] + '/api/v2/buckets/' + InfluxApi.get_bucketID_by_name(module)
response = requests.delete(url, headers=headers)
url = self.endpoint + '/api/v2/buckets/' + self.get_bucketid_by_name(name, org)
response = requests.delete(url, headers=headers, timeout=self.timeout)

return response.status_code, response.content
return response.status_code, response.content
40 changes: 22 additions & 18 deletions plugins/modules/organize_bucket.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
#!/usr/bin/python3
# pylint: disable=missing-module-docstring

from ansible.module_utils.basic import AnsibleModule
from ansible_collections.tbauriedel.influxdb.plugins.module_utils.utils import (
InfluxApi
)
from ansible_collections.tbauriedel.influxdb.plugins.module_utils.utils import (Influx2Api) # pylint: disable=import-error

def run_module():
'''
Module to manage InfluxDB buckets
'''

# Define new Module with arguments
module = AnsibleModule(
argument_spec=dict(
Expand All @@ -31,36 +34,39 @@ def run_module():
rc=""
)

# Prepare API class
API = Influx2Api(module.params['token'], module.params['host']) # pylint: disable=invalid-name

# Get state of current bucket
orgID = InfluxApi.get_orgID_by_name(module)
if orgID == "not found":
module.exit_json(dict(
org_id = API.get_orgid_by_name(module.params['org'])
if org_id == "not found":
module.exit_json(
failed=True,
stderr="No orgID found for given org name"
))
stderr="No org id found for given org name"
)

# Get state of bucket ('present' or 'absent')
bucketState = InfluxApi.get_bucket_status(module)
bucket_state = API.get_bucket_status(module.params['name'], org_id)

# Create bucket if not 'present' but 'present' in configuration
if module.params['state'] == 'present' and bucketState == 'absent':
if module.params['state'] == 'present' and bucket_state == 'absent':
result['debug'] = "Create bucket"

rc, content = InfluxApi.create_bucket(module)
rc, content = API.create_bucket(module.params['name'], org_id, module.params['retention'])
result['rc'] = rc
if rc != 201:
module.exit_json(
failed=True,
stderr=content
)

result['changed'] = True

# Delete bucket if 'present' but 'absent' in configuration
elif module.params['state'] == 'absent' and bucketState == 'present':
elif module.params['state'] == 'absent' and bucket_state == 'present':
result['debug'] = "Delete bucket"

rc, content = InfluxApi.delete_bucket(module)
rc, content = API.delete_bucket(module.params['name'], module.params['org'])
result['rc'] = rc
if rc != 204:
module.exit_json(
Expand All @@ -74,9 +80,7 @@ def run_module():
result['debug'] = "Keep state of bucket"

module.exit_json(**result)

def main():
run_module()


if __name__ == '__main__':
main()
run_module()
2 changes: 1 addition & 1 deletion requirements-test.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
ansible
ansible-lint
ansible-lint
3 changes: 1 addition & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
# ansible collections
# - community.general
p

0 comments on commit 77bb467

Please sign in to comment.