diff --git a/authenticator.py b/authenticator.py index 765cf5b..d40dec2 100755 --- a/authenticator.py +++ b/authenticator.py @@ -20,8 +20,7 @@ def setup_logger(): ch = logging.StreamHandler() ch.setLevel(logging.INFO) - formatter = logging.Formatter( - '%(asctime)s - %(name)s- %(levelname)s - %(message)s') + formatter = logging.Formatter('%(asctime)s - %(name)s- %(levelname)s - %(message)s') ch.setFormatter(formatter) # add handler to logger logger.addHandler(ch) @@ -32,10 +31,7 @@ def setup_logger(): def load_config(logger): try: config_path = os.path.join( - os.path.expanduser("~"), - ".certbot_dns_corenetworks", - "config.ini" - ) + os.path.expanduser("~"), ".certbot_dns_corenetworks", "config.ini") config = configparser.ConfigParser() config.read(config_path) @@ -47,7 +43,7 @@ def load_config(logger): data["ZONE"] = config['DNS']['ZONE'] except KeyError, e: logger.error("Key %s not found in config" % (e)) - sys.exit(0) + sys.exit(1) return data @@ -65,7 +61,7 @@ def get_auth_token(user, passwd, host, logger): r.raise_for_status() except requests.exceptions.HTTPError, e: logger.error(e) - sys.exit(0) + sys.exit(1) return r @@ -79,7 +75,35 @@ def get_zone(token, host, zone, logger): r.raise_for_status() except requests.exceptions.HTTPError, e: logger.error(e) - sys.exit(0) + sys.exit(1) + + return r + + +def set_record(token, host, zone, logger): + url = urlparse.urljoin(host, os.path.join("dnszones", zone, "records/")) + headers = {"Authorization": "Bearer %s" % (token)} + + try: + certbot_domain = "_acme-challenge.%s" % (os.environ['CERTBOT_DOMAIN']) + certbot_validation = os.environ['CERTBOT_VALIDATION'] + except KeyError, e: + logger.error("Environment Variable %s not set" % (e)) + sys.exit(1) + + data = {} + data["name"] = certbot_domain + data["ttl"] = 120 + data["type"] = "TXT" + data["data"] = certbot_validation + json_data = json.dumps(data) + + try: + r = requests.post(url, headers=headers, data=json_data) + r.raise_for_status() + except requests.exceptions.HTTPError, e: + logger.error(e) + sys.exit(1) return r @@ -92,8 +116,7 @@ def main(): # get auth token logger.info("Try to get auth token") - r_token = get_auth_token( - config["API_USER"], config["PASSWORD"], config["API_HOST"], logger) + r_token = get_auth_token(config["API_USER"], config["PASSWORD"], config["API_HOST"], logger) auth_token = r_token.json()["token"] logger.info("Authentication successful") @@ -105,9 +128,12 @@ def main(): if zone_active: logger.info("Zone '%s' verified (active)" % (zone_name)) else: - logger.error( - "Zone '%s' verified (not active)" % (zone_name)) - sys.exit(0) + logger.error("Zone '%s' verified (not active)" % (zone_name)) + sys.exit(1) + + # add txt record + z_record = set_record(auth_token, config["API_HOST"], zone_name, logger) + print z_record if __name__ == "__main__":