def init_api(): """ Inititialize NS1 SDK :return: Configured NS1 API object """ config = Config() config.createFromAPIKey(ns1_apikey) config["endpoint"] = ns1_endpoint return NS1(config=config)
class NS1ModuleBase(object): def __init__( self, derived_arg_spec, supports_check_mode=False, mutually_exclusive=None, ): merged_arg_spec = dict() merged_arg_spec.update(NS1_COMMON_ARGS) if derived_arg_spec: merged_arg_spec.update(derived_arg_spec) self.module = AnsibleModule( argument_spec=merged_arg_spec, supports_check_mode=supports_check_mode, mutually_exclusive=mutually_exclusive, ) if not HAS_NS1: self.module.fail_json(msg=missing_required_lib("ns1-python")) self._build_ns1() self._strip_common_params() def errback_generator(self): def errback(args): self.module.fail_json(msg="%s - %s" % (args[0], args[1])) return errback def _build_ns1(self): self.config = Config() self.config.createFromAPIKey(self.module.params["apiKey"]) self.config["transport"] = "basic" if self.module.params["endpoint"]: self.config["endpoint"] = self.module.params["endpoint"] if self.module.params["ignore_ssl"]: self.config["ignore-ssl-errors"] = self.module.params["ignore_ssl"] self.ns1 = NS1(config=self.config) def _strip_common_params(self): """Remove the params we've handled, so the rest of the module doesn't have to worry about them. """ for key in NS1_COMMON_ARGS: del self.module.params[key]
def main(): if os.path.isfile('/config.yml') is not True: print('/config.yml does not exist or is not a file, exiting.') exit(1) config_file = yaml.load(open('/config.yml', 'r')) for domain in config_file: nsone_config = Config() nsone_config.createFromAPIKey(config_file[domain]['api-key']) nsone_config["transport"] = "requests" client = NS1(config=nsone_config) zone = client.loadZone(domain) for record in config_file[domain]['records-to-update']: record = zone.loadRecord(record, 'A') result = check_ip(record) if result['matches'] is False: set_ip(record, result['my_ip'])
def main(): if os.path.isfile('/app/config/config.yml') is not True: print( '/app/config/config.yml does not exist or is not a file, exiting.') exit(1) config_file = yaml.safe_load(open('/app/config/config.yml', 'r')) for domain in config_file: nsone_config = Config() nsone_config.createFromAPIKey(config_file[domain]['api-key']) nsone_config["transport"] = "requests" client = NS1(config=nsone_config) zone = client.loadZone(domain) for host in config_file[domain]['hosts']: for x in host["subdomains"]: try: if x == "@": host["record"] = zone.loadRecord(domain, 'A') else: host["record"] = zone.loadRecord(x, 'A') my_ip = get_ip(host) result = check_ip(my_ip, host["record"]) if result['matches'] is False: if not config_file[domain]["test"]: set_ip(host["record"], result['my_ip']) except rest.errors.ResourceException: full_domain = domain if x != "@": full_domain = "{0}.{1}".format(x, domain) if not config_file[domain]["test"]: if "allowed_countries" not in config_file[domain]: config_file[domain]["allowed_countries"] = [ 'US', 'CA' ] create_record(zone, full_domain, my_ip, config_file[domain]["allowed_countries"])
# # Copyright (c) 2014 NSONE, Inc. # # License under The MIT License (MIT). See LICENSE in project root. # import logging from ns1 import NS1, Config # to enable verbose logging, set 'verbosity' in the config and use # the standard python logging system config = Config() config.createFromAPIKey("qACMD09OJXBxT7XOwv9v") config["verbosity"] = 5 logging.basicConfig(level=logging.DEBUG) print(config) api = NS1(config=config) # now all requests will show up in the logging system # exception handling: # the follow exceptions may be thrown # from ns1.rest.errors import ResourceException, \ # RateLimitException, AuthException # ResourceException is the base exception (Auth and RateLimit extend it) # it (and therefore they) have the properties message, response, body # AuthException is raised when apikey is incorrect or the key doesn't # have permission to the requested resource
# to specify an apikey here instead, use: api = NS1(apiKey='qACMD09OJXBxT7XOuRs8') # to load an alternate configuration file: api = NS1(configFile='/etc/ns1/api.json') # to load a specific keyID inside of your config file (see config format # in docs), use this. this only makes sense for config file loads, not # apiKey loads: api = NS1(keyID='all-access') # if you have special needs, build your own Config object and pass it to # NS1: config = Config() config.createFromAPIKey('qACMD09OJXBxT7XOwv9v') config['verbosity'] = 5 config['transport'] = 'twisted' api = NS1(config=config) # you can get the current config object NS1 is using via config = api.config # change config variables config['verbosity'] = 5 # write out new config files config.write('/tmp/newconfig.json') # the config file format supports different apiKeys (see docs) using keyID
''' dns-importer: read in csv file and upload ''' import csv import os import sys from ns1 import NS1, Config from twisted.internet import defer, reactor # Increase timeout if too many twisted ConnectionLost REACTOR_TIMEOUT = 5 # load default config from ~/.nsone (see nsone.sample) config = Config() config.loadFromFile(Config.DEFAULT_CONFIG_FILE) ''' # OR generate default with api key AND adjust config config.createFromAPIKey('AbCdEfGhiJKlMnOpQrSt') config['transport'] = 'twisted' config['verbosity'] = 5 ''' api = NS1(config=config) def fix_data(r): ''' fix_data is used to reshape the data according to the type ''' if r['Type'] == 'MX': data = r['Data'].split(' ') return [[int(data[0]), ' '.join(data[1:])]] else:
dns-importer: read in csv file and upload ''' import csv import os import sys from ns1 import NS1, Config from twisted.internet import defer, reactor # Increase timeout if too many twisted ConnectionLost REACTOR_TIMEOUT = 5 # load default config from ~/.nsone (see nsone.sample) config = Config() config.loadFromFile(Config.DEFAULT_CONFIG_FILE) ''' # OR generate default with api key AND adjust config config.createFromAPIKey('AbCdEfGhiJKlMnOpQrSt') config['transport'] = 'twisted' config['verbosity'] = 5 ''' api = NS1(config=config) def fix_data(r): ''' fix_data is used to reshape the data according to the type ''' if r['Type'] == 'MX': data = r['Data'].split(' ') return [[ int(data[0]), ' '.join(data[1:]) ]] else:
#if __name__ == "__main__": parser = argparse.ArgumentParser( description='Update CDN records in NS1 to migrate from CloudFront to CloudFlare') parser.add_argument("-k", "--key", type=str, help='NS1 API key', required=True) parser.add_argument("-c", "--cname", type=str, help='Source CNAME record', required=True) parser.add_argument("-v", "--verbosity", type=int, default=0, help='verbosity level (0-5)', required=False) parser.print_usage args = parser.parse_args() cname = args.cname.lower() if re.match(r'^[a-z0-9\-]+\.tango\.me$', args.cname, re.IGNORECASE) else parser.exit(message="Error! Wrong CNAME value!\n", status=1) config = Config() config.createFromAPIKey(args.key) config['verbosity'] = args.verbosity if config['verbosity'] > 0: logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%H:%M:%S',) print(config) api = NS1(config=config) rec = api.loadRecord(cname, 'CNAME') print(rec, file=sys.stderr) # you can access all the record information via the data property # pprint.pprint(rec.data) answers = rec.data["answers"]