add logging; refactoring

This commit is contained in:
Robert Kaussow 2018-06-10 02:26:08 +02:00
parent 34211dec87
commit 3b27cf8fb9

View File

@ -12,17 +12,6 @@ import sys
import logging
def api_auth(user, passwd, host):
data = {}
data["login"] = user
data["password"] = passwd
json_data = json.dumps(data)
url = urlparse.urljoin(host, os.path.join("auth", "token"))
r = requests.post(url, data=json_data)
return r.json()
def setup_logger():
# seup logging
logger = logging.getLogger("certbot_dns_corenetworks")
@ -40,11 +29,7 @@ def setup_logger():
return logger
def main():
"""Main logic entrypoint"""
logger = setup_logger()
def load_config(logger):
try:
config_path = os.path.join(
os.path.expanduser("~"),
@ -54,15 +39,75 @@ def main():
config = configparser.ConfigParser()
config.read(config_path)
API_HOST = config['API']['HOST']
API_USER = config['API']['USER']
PASSWORD = config['API']['PASSWORD']
data = {}
data["API_HOST"] = config['API']['HOST']
data["API_USER"] = config['API']['USER']
data["PASSWORD"] = config['API']['PASSWORD']
data["ZONE"] = config['DNS']['ZONE']
except KeyError, e:
logger.error("Key %s not found in config" % (e))
sys.exit(0)
auth = api_auth(API_USER, PASSWORD, API_HOST)
print auth["token"]
return data
def get_auth_token(user, passwd, host, logger):
data = {}
data["login"] = user
data["password"] = passwd
json_data = json.dumps(data)
url = urlparse.urljoin(host, os.path.join("auth", "token"))
try:
r = requests.post(url, data=json_data)
r.raise_for_status()
except requests.exceptions.HTTPError, e:
logger.error(e)
sys.exit(0)
return r
def get_zone(token, host, zone, logger):
url = urlparse.urljoin(host, os.path.join("dnszones", zone))
headers = {"Authorization": "Bearer %s" % (token)}
try:
r = requests.get(url, headers=headers)
r.raise_for_status()
except requests.exceptions.HTTPError, e:
logger.error(e)
sys.exit(0)
return r
def main():
"""Main logic entrypoint"""
logger = setup_logger()
config = load_config(logger)
# get auth token
logger.info("Try to get auth token")
r_token = get_auth_token(
config["API_USER"], config["PASSWORD"], config["API_HOST"], logger)
auth_token = r_token.json()["token"]
logger.info("Authentication successful")
# verify dns zone
r_zone = get_zone(auth_token, config["API_HOST"], config["ZONE"], logger)
zone_name = r_zone.json()["name"]
zone_active = r_zone.json()["active"]
if zone_active:
logger.info("Zone '%s' verified (active)" % (zone_name))
else:
logger.error(
"Zone '%s' verified (not active)" % (zone_name))
sys.exit(0)
if __name__ == "__main__":