From 3db698db570c4b7bbea89427cd6b13016a109875 Mon Sep 17 00:00:00 2001 From: Paul Lecuq Date: Sun, 17 Jan 2021 17:43:56 +0100 Subject: [PATCH] updated ovhapi modules and states --- states/_modules/custom.py | 2 + states/_modules/dkron.py | 2 + states/_modules/ovhapi.py | 98 ++++++++++++++++++++++++++++-------- states/_modules/syncthing.py | 10 ++++ states/_states/custom.py | 2 + states/_states/dkron.py | 2 +- states/_states/ovhapi.py | 47 ++++++++++------- states/_states/syncthing.py | 2 +- 8 files changed, 124 insertions(+), 41 deletions(-) diff --git a/states/_modules/custom.py b/states/_modules/custom.py index db9af76..d231a50 100644 --- a/states/_modules/custom.py +++ b/states/_modules/custom.py @@ -2,6 +2,7 @@ import salt.exceptions + def current_state(name): ret = dict() @@ -10,6 +11,7 @@ def current_state(name): return ret + def change_state(name, foo): ret = dict() diff --git a/states/_modules/dkron.py b/states/_modules/dkron.py index 986732d..9a4c9c8 100644 --- a/states/_modules/dkron.py +++ b/states/_modules/dkron.py @@ -2,6 +2,7 @@ import requests + def get_jobs(url="http://localhost:8898", verify=False): """get_jobs fetch jobs from dkron""" fullurl = f"{url}/v1/jobs" @@ -15,6 +16,7 @@ def get_jobs(url="http://localhost:8898", verify=False): return ret return None + def set_jobs(url="http://localhost:8898", verify=False, job=None): """set_jobs set jobs on dkron""" fullurl = f"{url}/v1/jobs" diff --git a/states/_modules/ovhapi.py b/states/_modules/ovhapi.py index f677bee..2c8aae1 100644 --- a/states/_modules/ovhapi.py +++ b/states/_modules/ovhapi.py @@ -1,7 +1,5 @@ #!/usr/bin/python3 -from __future__ import absolute_import, unicode_literals, print_function - import salt import ovh @@ -10,14 +8,17 @@ from ovh.exceptions import ResourceNotFoundError, APIError def __virtual__(): + return True + def _config(): config = __salt__['config.get']('ovh') if not config: raise CommandExecutionError( 'OVH execution module configuration could not be found' ) + return config @@ -29,6 +30,7 @@ def _auth(): application_secret=cfg['application_secret'], consumer_key=cfg['consumer_key'], ) + return client @@ -43,13 +45,17 @@ def domain_get_zone(zone=""): if zone == "": raise ArgumentValueError("Zone is not defined") client = _auth() - results = client.get(f'/domain/zone/{zone}/export') + try: + results = client.get(f'/domain/zone/{zone}/export') + except APIError: + return "Query failed in OVH API" + return results def domain_get_record(zone="", fieldType="", subDomain=""): ''' - Records of the zone + Record of the zone zone Zone name to fetch @@ -61,24 +67,25 @@ def domain_get_record(zone="", fieldType="", subDomain=""): if zone == "": raise ArgumentValueError("Zone is not defined") - results = [] + res = None client = _auth() try: - records = client.get(f'/domain/zone/{zone}/record', + record = client.get(f'/domain/zone/{zone}/record', fieldType=fieldType, subDomain=subDomain) + if len(record) > 0: + req = client.get(f'/domain/zone/{zone}/record/{record}') + return req except APIError: return "Query failed in OVH API" - for record in records: - try: - req = client.get(f'/domain/zone/{zone}/record/{record}') - results.append(req) - except APIError: - return "Query failed in OVH API" - return results + return None -def domain_post_record(zone="", fieldType="", subDomain="", target="", ttl=0): +def domain_post_record(zone="", + fieldType="", + subDomain="", + target="", + ttl=0): ''' Create a new DNS record @@ -97,14 +104,60 @@ def domain_post_record(zone="", fieldType="", subDomain="", target="", ttl=0): if zone == "": raise ArgumentValueError("Zone is not defined") client = _auth() - req = client.post(f'/domain/zone/{zone}/record', - fieldType=fieldType, - subDomain=subDomain, - target=target, - ttl=ttl) + try: + req = client.post(f'/domain/zone/{zone}/record', + fieldType=fieldType, + subDomain=subDomain, + target=target, + ttl=ttl) + except APIError: + return "Query failed in OVH API" + return req +def domain_put_record(zone="", + fieldType="", + subDomain="", + target="", + ttl=0): + ''' + Update a DNS record + + zone + The internal name of your zone + fieldType + Filter the value of fieldType property (like) + subDomain + Filter the value of subDomain property (like) + target + Resource record target + ttl + Resource record ttl + ''' + + if zone == "": + raise ArgumentValueError("Zone is not defined") + client = _auth() + try: + records = client.get(f'/domain/zone/{zone}/record', + fieldType=fieldType, + subDomain=subDomain) + if len(records) > 0: + record = client.get(f'/domain/zone/{zone}/record/{records[0]}') + req = client.put(f'/domain/zone/{zone}/record/{records[0]["id"]}', + subDomain=subDomain, + target=target, + ttl=ttl) + return req + else: + return "Error updating record" + except APIError: + return "Query failed in OVH API" + + return None + + def domain_delete_record(zone="", fieldType="", subDomain=""): ''' Delete a DNS record (Don't forget to refresh the zone) @@ -133,6 +186,7 @@ def domain_delete_record(zone="", fieldType="", subDomain=""): results.append(req) except ResourceNotFoundError: return "Resource not found in OVH API" + return results @@ -147,5 +201,9 @@ def domain_refresh_zone(zone=""): if zone == "": raise ArgumentValueError("Zone is not defined") client = _auth() - req = client.post(f'/domain/zone/{zone}/refresh') + try: + req = client.post(f'/domain/zone/{zone}/refresh') + except APIError: + return "Query failed in OVH API" + return req diff --git a/states/_modules/syncthing.py b/states/_modules/syncthing.py index ae79dfc..21a2acd 100644 --- a/states/_modules/syncthing.py +++ b/states/_modules/syncthing.py @@ -3,6 +3,7 @@ import xml.etree.ElementTree as ET import requests + def get_apikey(configfile="/root/.config/syncthing/config.xml"): try: tree = ET.parse(configfile) @@ -11,8 +12,10 @@ def get_apikey(configfile="/root/.config/syncthing/config.xml"): return apikey except (FileNotFoundError, ET.ParseError, AttributeError) as exc: raise f"Exception {exc} occured" + return "" + def get_config(url, verify, apikey): fullurl = "{0}/rest/system/config".format(url) ret = dict() @@ -26,8 +29,10 @@ def get_config(url, verify, apikey): ret = req.json() if req.status_code == 200: return ret + return None + def set_config(url, verify, apikey, config): fullurl = "{0}/rest/system/config".format(url) try: @@ -40,8 +45,10 @@ def set_config(url, verify, apikey, config): raise f"Exception {exc} occured" if req.status_code == 200: return True + return None + def insync(url, verify, apikey): fullurl = "{0}/rest/system/config/insync".format(url) try: @@ -54,8 +61,10 @@ def insync(url, verify, apikey): ret = req.json() if req.status_code == 200: return ret + return None + def restart(url, verify, apikey): fullurl = "{0}/rest/system/restart".format(url) try: @@ -66,4 +75,5 @@ def restart(url, verify, apikey): raise f"Exception {exc} occured" if req.status_code == 200: return {} + return None diff --git a/states/_states/custom.py b/states/_states/custom.py index 4824f50..91d754e 100644 --- a/states/_states/custom.py +++ b/states/_states/custom.py @@ -2,6 +2,7 @@ import salt.exceptions + def current_state(name): ret = dict() @@ -9,6 +10,7 @@ def current_state(name): return ret + def enforce_custom_thing(name, foo, bar=True): ''' Enforce the state of a custom thing diff --git a/states/_states/dkron.py b/states/_states/dkron.py index 31b0148..ef11852 100644 --- a/states/_states/dkron.py +++ b/states/_states/dkron.py @@ -1,9 +1,9 @@ #!/usr/bin/python3 -from __future__ import absolute_import, print_function, unicode_literals import salt.utils.dictupdate import salt.utils.dictdiffer + def jobs(name, url="http://localhost:8080", verify=False, jobs_list=[]): ret = {'name': name, 'changes': {}, diff --git a/states/_states/ovhapi.py b/states/_states/ovhapi.py index 80f2dbc..1198837 100644 --- a/states/_states/ovhapi.py +++ b/states/_states/ovhapi.py @@ -1,25 +1,30 @@ #!/usr/bin/python3 -from __future__ import absolute_import, print_function, unicode_literals - import salt.utils.dictupdate import salt.utils.dictdiffer + def _error(ret, err_msg): ret['result'] = False ret['comment'] = err_msg + return ret + def _str_split(string): delim = "\n" + return [e + delim for e in string.split(delim) if e] + def domain_record_present(name, zone=None, recordname=None, recordtype=None, target=None, ttl=0): + + res_output = "" ret = { 'name': name, 'changes': {}, @@ -27,7 +32,6 @@ def domain_record_present(name, 'comment': 'Config is up to date' } - if name is None: return _error(ret, 'Must provide name to ovhapi.domain_record_present') if zone is None: @@ -39,29 +43,34 @@ def domain_record_present(name, if target is None: return _error(ret, 'Must provide target to ovhapi.domain_record_present') - # check if record exists - if len(__salt__['ovhapi.domain_get_record'](zone=zone, - fieldType=recordtype, - subDomain=recordname)): - ret['comment'] = f"Record on {zone} named {recordname} with type {recordtype} already exists" - return ret - cur_zone_state = __salt__['ovhapi.domain_get_zone'](zone=zone) - cur_zone_refresh = __salt__['ovhapi.domain_refresh_zone'](zone=zone) + # check if record exists + cur_record = __salt__['ovhapi.domain_get_record'](zone=zone, + fieldType=recordtype, + subDomain=recordname) + if cur_record is not None: + res = __salt__['ovhapi.domain_put_record'](zone=zone, + fieldType=recordtype, + subDomain=recordname) + res_output = f"Updated record {recordname}, output: {res_output}" - res = __salt__['ovhapi.domain_post_record']( - zone=zone, - subDomain=recordname, - fieldType=recordtype, - target=target, - ttl=ttl) + else: + res = __salt__['ovhapi.domain_post_record'](zone=zone, + subDomain=recordname, + fieldType=recordtype, + target=target, + ttl=ttl) + res_output = f"Updated record {recordname}, output: {res_output}" new_zone_state = __salt__['ovhapi.domain_get_zone'](zone=zone) + cur_zone_refresh = __salt__['ovhapi.domain_refresh_zone'](zone=zone) + ret['changes'] = { - "diff": salt.utils.stringutils.get_diff(_str_split(cur_zone_state), _str_split(new_zone_state)) + "diff": salt.utils.stringutils.get_diff(_str_split(cur_zone_state), + _str_split(new_zone_state)) } - ret['comment'] = f'Result is {res}' + ret['comment'] = f'Result is {res_output}, refresh {cur_zone_refresh}' return ret diff --git a/states/_states/syncthing.py b/states/_states/syncthing.py index e0944dd..9661193 100644 --- a/states/_states/syncthing.py +++ b/states/_states/syncthing.py @@ -1,9 +1,9 @@ #!/usr/bin/python3 -from __future__ import absolute_import, print_function, unicode_literals import salt.utils.dictupdate import salt.utils.dictdiffer + def config(name, verify, url, cfg): ret = {'name': name, 'changes': {},