updated ovhapi modules and states

This commit is contained in:
Paul 2021-01-17 17:43:56 +01:00
parent 67ce37a53f
commit 3db698db57
8 changed files with 124 additions and 41 deletions

View File

@ -2,6 +2,7 @@
import salt.exceptions import salt.exceptions
def current_state(name): def current_state(name):
ret = dict() ret = dict()
@ -10,6 +11,7 @@ def current_state(name):
return ret return ret
def change_state(name, foo): def change_state(name, foo):
ret = dict() ret = dict()

View File

@ -2,6 +2,7 @@
import requests import requests
def get_jobs(url="http://localhost:8898", verify=False): def get_jobs(url="http://localhost:8898", verify=False):
"""get_jobs fetch jobs from dkron""" """get_jobs fetch jobs from dkron"""
fullurl = f"{url}/v1/jobs" fullurl = f"{url}/v1/jobs"
@ -15,6 +16,7 @@ def get_jobs(url="http://localhost:8898", verify=False):
return ret return ret
return None return None
def set_jobs(url="http://localhost:8898", verify=False, job=None): def set_jobs(url="http://localhost:8898", verify=False, job=None):
"""set_jobs set jobs on dkron""" """set_jobs set jobs on dkron"""
fullurl = f"{url}/v1/jobs" fullurl = f"{url}/v1/jobs"

View File

@ -1,7 +1,5 @@
#!/usr/bin/python3 #!/usr/bin/python3
from __future__ import absolute_import, unicode_literals, print_function
import salt import salt
import ovh import ovh
@ -10,14 +8,17 @@ from ovh.exceptions import ResourceNotFoundError, APIError
def __virtual__(): def __virtual__():
return True return True
def _config(): def _config():
config = __salt__['config.get']('ovh') config = __salt__['config.get']('ovh')
if not config: if not config:
raise CommandExecutionError( raise CommandExecutionError(
'OVH execution module configuration could not be found' 'OVH execution module configuration could not be found'
) )
return config return config
@ -29,6 +30,7 @@ def _auth():
application_secret=cfg['application_secret'], application_secret=cfg['application_secret'],
consumer_key=cfg['consumer_key'], consumer_key=cfg['consumer_key'],
) )
return client return client
@ -43,13 +45,17 @@ def domain_get_zone(zone=""):
if zone == "": if zone == "":
raise ArgumentValueError("Zone is not defined") raise ArgumentValueError("Zone is not defined")
client = _auth() 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 return results
def domain_get_record(zone="", fieldType="", subDomain=""): def domain_get_record(zone="", fieldType="", subDomain=""):
''' '''
Records of the zone Record of the zone
zone zone
Zone name to fetch Zone name to fetch
@ -61,24 +67,25 @@ def domain_get_record(zone="", fieldType="", subDomain=""):
if zone == "": if zone == "":
raise ArgumentValueError("Zone is not defined") raise ArgumentValueError("Zone is not defined")
results = [] res = None
client = _auth() client = _auth()
try: try:
records = client.get(f'/domain/zone/{zone}/record', record = client.get(f'/domain/zone/{zone}/record',
fieldType=fieldType, fieldType=fieldType,
subDomain=subDomain) subDomain=subDomain)
if len(record) > 0:
req = client.get(f'/domain/zone/{zone}/record/{record}')
return req
except APIError: except APIError:
return "Query failed in OVH API" return "Query failed in OVH API"
for record in records: return None
try:
req = client.get(f'/domain/zone/{zone}/record/{record}')
results.append(req)
except APIError:
return "Query failed in OVH API"
return results
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 Create a new DNS record
@ -97,14 +104,60 @@ def domain_post_record(zone="", fieldType="", subDomain="", target="", ttl=0):
if zone == "": if zone == "":
raise ArgumentValueError("Zone is not defined") raise ArgumentValueError("Zone is not defined")
client = _auth() client = _auth()
req = client.post(f'/domain/zone/{zone}/record', try:
fieldType=fieldType, req = client.post(f'/domain/zone/{zone}/record',
subDomain=subDomain, fieldType=fieldType,
target=target, subDomain=subDomain,
ttl=ttl) target=target,
ttl=ttl)
except APIError:
return "Query failed in OVH API"
return req 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=""): def domain_delete_record(zone="", fieldType="", subDomain=""):
''' '''
Delete a DNS record (Don't forget to refresh the zone) 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) results.append(req)
except ResourceNotFoundError: except ResourceNotFoundError:
return "Resource not found in OVH API" return "Resource not found in OVH API"
return results return results
@ -147,5 +201,9 @@ def domain_refresh_zone(zone=""):
if zone == "": if zone == "":
raise ArgumentValueError("Zone is not defined") raise ArgumentValueError("Zone is not defined")
client = _auth() 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 return req

View File

@ -3,6 +3,7 @@
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
import requests import requests
def get_apikey(configfile="/root/.config/syncthing/config.xml"): def get_apikey(configfile="/root/.config/syncthing/config.xml"):
try: try:
tree = ET.parse(configfile) tree = ET.parse(configfile)
@ -11,8 +12,10 @@ def get_apikey(configfile="/root/.config/syncthing/config.xml"):
return apikey return apikey
except (FileNotFoundError, ET.ParseError, AttributeError) as exc: except (FileNotFoundError, ET.ParseError, AttributeError) as exc:
raise f"Exception {exc} occured" raise f"Exception {exc} occured"
return "" return ""
def get_config(url, verify, apikey): def get_config(url, verify, apikey):
fullurl = "{0}/rest/system/config".format(url) fullurl = "{0}/rest/system/config".format(url)
ret = dict() ret = dict()
@ -26,8 +29,10 @@ def get_config(url, verify, apikey):
ret = req.json() ret = req.json()
if req.status_code == 200: if req.status_code == 200:
return ret return ret
return None return None
def set_config(url, verify, apikey, config): def set_config(url, verify, apikey, config):
fullurl = "{0}/rest/system/config".format(url) fullurl = "{0}/rest/system/config".format(url)
try: try:
@ -40,8 +45,10 @@ def set_config(url, verify, apikey, config):
raise f"Exception {exc} occured" raise f"Exception {exc} occured"
if req.status_code == 200: if req.status_code == 200:
return True return True
return None return None
def insync(url, verify, apikey): def insync(url, verify, apikey):
fullurl = "{0}/rest/system/config/insync".format(url) fullurl = "{0}/rest/system/config/insync".format(url)
try: try:
@ -54,8 +61,10 @@ def insync(url, verify, apikey):
ret = req.json() ret = req.json()
if req.status_code == 200: if req.status_code == 200:
return ret return ret
return None return None
def restart(url, verify, apikey): def restart(url, verify, apikey):
fullurl = "{0}/rest/system/restart".format(url) fullurl = "{0}/rest/system/restart".format(url)
try: try:
@ -66,4 +75,5 @@ def restart(url, verify, apikey):
raise f"Exception {exc} occured" raise f"Exception {exc} occured"
if req.status_code == 200: if req.status_code == 200:
return {} return {}
return None return None

View File

@ -2,6 +2,7 @@
import salt.exceptions import salt.exceptions
def current_state(name): def current_state(name):
ret = dict() ret = dict()
@ -9,6 +10,7 @@ def current_state(name):
return ret return ret
def enforce_custom_thing(name, foo, bar=True): def enforce_custom_thing(name, foo, bar=True):
''' '''
Enforce the state of a custom thing Enforce the state of a custom thing

View File

@ -1,9 +1,9 @@
#!/usr/bin/python3 #!/usr/bin/python3
from __future__ import absolute_import, print_function, unicode_literals
import salt.utils.dictupdate import salt.utils.dictupdate
import salt.utils.dictdiffer import salt.utils.dictdiffer
def jobs(name, url="http://localhost:8080", verify=False, jobs_list=[]): def jobs(name, url="http://localhost:8080", verify=False, jobs_list=[]):
ret = {'name': name, ret = {'name': name,
'changes': {}, 'changes': {},

View File

@ -1,25 +1,30 @@
#!/usr/bin/python3 #!/usr/bin/python3
from __future__ import absolute_import, print_function, unicode_literals
import salt.utils.dictupdate import salt.utils.dictupdate
import salt.utils.dictdiffer import salt.utils.dictdiffer
def _error(ret, err_msg): def _error(ret, err_msg):
ret['result'] = False ret['result'] = False
ret['comment'] = err_msg ret['comment'] = err_msg
return ret return ret
def _str_split(string): def _str_split(string):
delim = "\n" delim = "\n"
return [e + delim for e in string.split(delim) if e] return [e + delim for e in string.split(delim) if e]
def domain_record_present(name, def domain_record_present(name,
zone=None, zone=None,
recordname=None, recordname=None,
recordtype=None, recordtype=None,
target=None, target=None,
ttl=0): ttl=0):
res_output = ""
ret = { ret = {
'name': name, 'name': name,
'changes': {}, 'changes': {},
@ -27,7 +32,6 @@ def domain_record_present(name,
'comment': 'Config is up to date' 'comment': 'Config is up to date'
} }
if name is None: if name is None:
return _error(ret, 'Must provide name to ovhapi.domain_record_present') return _error(ret, 'Must provide name to ovhapi.domain_record_present')
if zone is None: if zone is None:
@ -39,29 +43,34 @@ def domain_record_present(name,
if target is None: if target is None:
return _error(ret, 'Must provide target to ovhapi.domain_record_present') 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_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']( else:
zone=zone, res = __salt__['ovhapi.domain_post_record'](zone=zone,
subDomain=recordname, subDomain=recordname,
fieldType=recordtype, fieldType=recordtype,
target=target, target=target,
ttl=ttl) ttl=ttl)
res_output = f"Updated record {recordname}, output: {res_output}"
new_zone_state = __salt__['ovhapi.domain_get_zone'](zone=zone) new_zone_state = __salt__['ovhapi.domain_get_zone'](zone=zone)
cur_zone_refresh = __salt__['ovhapi.domain_refresh_zone'](zone=zone)
ret['changes'] = { 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 return ret

View File

@ -1,9 +1,9 @@
#!/usr/bin/python3 #!/usr/bin/python3
from __future__ import absolute_import, print_function, unicode_literals
import salt.utils.dictupdate import salt.utils.dictupdate
import salt.utils.dictdiffer import salt.utils.dictdiffer
def config(name, verify, url, cfg): def config(name, verify, url, cfg):
ret = {'name': name, ret = {'name': name,
'changes': {}, 'changes': {},