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
def current_state(name):
ret = dict()
@ -10,6 +11,7 @@ def current_state(name):
return ret
def change_state(name, foo):
ret = dict()

View File

@ -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"

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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': {},

View File

@ -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

View File

@ -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': {},