Example #1
0
def update_dynamic_ip(mail, token, host, domain, address):
    try:
        dns = DNSimple(email=mail, api_token=token)
        results = dns.records(domain)
        response = None
        found = False
        for result in results:
            record = result['record']
            record_name = record['name']
            record_content = record['content'].rstrip()
            record_id = record['id']
            if record_name == host:
                if record_content == address:
                    response = None
                    found = True
                else:
                    record_data = { 'content' : address, 'record_type' : 'A' }
                    dns.update_record(domain, record_id, record_data)
                    response = "Updating host {0}.{1} with id {2} to address '{3}' from address '{4}'".format(record_name, domain, record_id, address, record_content)
                    found = True)
        if not found:
          record = { "name" : host, "record_type" : "A", "content" : address, "ttl" : 900 }
          dns.add_record(domain, record)
          response = "New record created for {0}.{1} with address {2}".format(host, domain, address)
    except DNSimpleException as e:
        response = "Error when updating dynamic address ({0})".format(e)
    return response
Example #2
0
def main():
    dns = DNSimple(username=USERNAME, password=PASSWORD)

    for net in NETWORKS:
        network = IPNetwork(net)
        for ip in network[1:-1]:
            print 'Adding mta{}-{}.{} IN A {}'.format(STARTFROM, ip.words[3], DOMAIN, str(ip))
            dns.add_record(DOMAIN, {'record_type': 'A', 'name': 'mta{}-{}'.format(STARTFROM, ip.words[3]),
                'content': str(ip)})
        STARTFROM += 1
Example #3
0
def add_record(request, subdomain):
    messages.get_messages(request)
    if request.method=='POST':
        content = request.POST.get('content')
        record_type = request.POST.get('record_type')
        try:
            dns = DNSimple(username=settings.DNSIMPLE_USERNAME, password=settings.DNSIMPLE_PASSWORD)
            dns.add_record('raspi.tw', { 'name':subdomain, 
                                         'record_type':record_type,
                                         'content':content})   
            messages.add_message(request, messages.SUCCESS, "添加记录成功!")
        except:
            messages.add_message(request, messages.WARNING, "添加记录失败!")
            pass
    return redirect('/dnsmanager')    
Example #4
0
def add_record(request, subdomain):
    messages.get_messages(request)
    if request.method == 'POST':
        content = request.POST.get('content')
        record_type = request.POST.get('record_type')
        try:
            dns = DNSimple(username=settings.DNSIMPLE_USERNAME,
                           password=settings.DNSIMPLE_PASSWORD)
            dns.add_record('raspi.tw', {
                'name': subdomain,
                'record_type': record_type,
                'content': content
            })
            messages.add_message(request, messages.SUCCESS, "添加记录成功!")
        except:
            messages.add_message(request, messages.WARNING, "添加记录失败!")
            pass
    return redirect('/dnsmanager')
Example #5
0
class DNS:
    def __init__(self, context, domain='telephone.org'):
        self.context = context
        self.domain = domain
        creds = self.context.secrets['dns.dnsimple']

        self.api = DNSimple(
            username=creds['email'],
            password=creds['password']
        )

    def get(self, kind='A', name='', content='', **kwargs):
        recs = self.api.records(self.domain)
        recs = [r['record'] for r in recs]
        if kind:
            recs = [r for r in recs if r['record_type'] == kind.upper()]
        if name:
            recs = [r for r in recs if r['name'].lower() == name.lower()]
        if content:
            recs = [r for r in recs if r['content'] == content]
        return recs


    def add(self, kind='A', name='', content='', **kwargs):
        recs = self.get(kind, name, content, **kwargs)
        if recs:
            print('record exists, do not recreate')
            return False
        if not recs:
            print('record does not exist, creating')
            data = dict(
                record_type=kind.upper(),
                name=name,
                content=content
            )
            data.update(**kwargs)
            return self.api.add_record(self.domain, data)

    def delete(self, kind='A', name='', content='', **kwargs):
        recs = self.get(kind, name, content, **kwargs)
        for record_id in [rec['id'] for rec in recs]:
            self.api.delete_record(self.domain, record_id)
        print('{} records deleted'.format(len(recs)))
Example #6
0
class DNSimpleProvider(object):

    def __init__(self, account_id, api_token):
        self.dnsimple_client = DNSimple(api_token=api_token, account_id=account_id)

    def cname_record_exists(self, domain, name):
        records = self.dnsimple_client.records(domain)
        fqdn = "{}.{}".format(name, domain)
        try:
            def rfilter(x):
                return x.get('record').get('type') == "CNAME" and ("{}.{}".format(x.get('record').get('name'), x.get('record').get('zone_id')) == fqdn)
            record = list(filter(rfilter, records))[0]
            return record
        except DNSimpleException as e:
            return {}
        except IndexError as e:
            return {}

    def cname_record_add(self, domain, name, content):
        try:
            return {'result': True, 'data': self.dnsimple_client.add_record(domain, {'type': 'CNAME', 'name': name, 'content': content})}
        except DNSimpleException as e:
            return {'result': False, 'data': str(e)}

    def cname_record_update(self, domain, name, content):
        records = self.dnsimple_client.records(domain)
        fqdn = "{}.{}".format(name, domain)
        try:
            def rfilter(x):
                return x.get('record').get('type') == "CNAME" and ("{}.{}".format(x.get('record').get('name'), x.get('record').get('zone_id')) == fqdn)
            record_id = list(filter(rfilter, records))[0].get('record').get('id')
            log.error(list(filter(rfilter, records))[0].get('record'))
            return {'result': True, 'data': self.dnsimple_client.update_record(domain, record_id, {'content': content})}
        except DNSimpleException as e:
            return {'result': False, 'data': str(e)}
        except IndexError:
            return {'result': False, 'data': 'record not found'}
Example #7
0
def create_record(data):
    nonexistant = False
    record = {
        'type': data['type'],
        'name': data['name'],
        'content': data['content'],
        'ttl': data['ttl']
    }

    dns = DNSimple(api_token=data['dnsimple_token'],
                   account_id=data['dnsimple_account'])
    if 'present' in data['state']:
        for n in dns.records(data['domain']):
            if record['name'] == n['record']['name']:
                res = dns.update_record(data['domain'], n['record']['id'],
                                        record)
                nonexistant = False
                return (True, res['record']['id'], 'record updated')
            else:
                nonexistant = True
        if nonexistant:
            res = dns.add_record(data['domain'], record)
            return (True, res['record']['id'], 'record added')
    return (False, "{}", 'no record added')
def main():
    module = AnsibleModule(
        argument_spec=dict(
            account_email=dict(required=False),
            account_api_token=dict(required=False, no_log=True),
            domain=dict(required=False),
            record=dict(required=False),
            record_ids=dict(required=False, type='list'),
            type=dict(required=False,
                      choices=[
                          'A', 'ALIAS', 'CNAME', 'MX', 'SPF', 'URL', 'TXT',
                          'NS', 'SRV', 'NAPTR', 'PTR', 'AAAA', 'SSHFP',
                          'HINFO', 'POOL'
                      ]),
            ttl=dict(required=False, default=3600, type='int'),
            value=dict(required=False),
            priority=dict(required=False, type='int'),
            state=dict(required=False, choices=['present', 'absent']),
            solo=dict(required=False, type='bool'),
        ),
        required_together=(['record', 'value']),
        supports_check_mode=True,
    )

    if not HAS_DNSIMPLE:
        module.fail_json(msg="dnsimple required for this module")

    account_email = module.params.get('account_email')
    account_api_token = module.params.get('account_api_token')
    domain = module.params.get('domain')
    record = module.params.get('record')
    record_ids = module.params.get('record_ids')
    record_type = module.params.get('type')
    ttl = module.params.get('ttl')
    value = module.params.get('value')
    priority = module.params.get('priority')
    state = module.params.get('state')
    is_solo = module.params.get('solo')

    if account_email and account_api_token:
        client = DNSimple(email=account_email, api_token=account_api_token)
    elif os.environ.get('DNSIMPLE_EMAIL') and os.environ.get(
            'DNSIMPLE_API_TOKEN'):
        client = DNSimple(email=os.environ.get('DNSIMPLE_EMAIL'),
                          api_token=os.environ.get('DNSIMPLE_API_TOKEN'))
    else:
        client = DNSimple()

    try:
        # Let's figure out what operation we want to do

        # No domain, return a list
        if not domain:
            domains = client.domains()
            module.exit_json(changed=False,
                             result=[d['domain'] for d in domains])

        # Domain & No record
        if domain and record is None and not record_ids:
            domains = [d['domain'] for d in client.domains()]
            if domain.isdigit():
                dr = next((d for d in domains if d['id'] == int(domain)), None)
            else:
                dr = next((d for d in domains if d['name'] == domain), None)
            if state == 'present':
                if dr:
                    module.exit_json(changed=False, result=dr)
                else:
                    if module.check_mode:
                        module.exit_json(changed=True)
                    else:
                        module.exit_json(
                            changed=True,
                            result=client.add_domain(domain)['domain'])
            elif state == 'absent':
                if dr:
                    if not module.check_mode:
                        client.delete(domain)
                    module.exit_json(changed=True)
                else:
                    module.exit_json(changed=False)
            else:
                module.fail_json(
                    msg="'%s' is an unknown value for the state argument" %
                    state)

        # need the not none check since record could be an empty string
        if domain and record is not None:
            records = [r['record'] for r in client.records(str(domain))]

            if not record_type:
                module.fail_json(msg="Missing the record type")

            if not value:
                module.fail_json(msg="Missing the record value")

            rr = next(
                (r for r in records
                 if r['name'] == record and r['record_type'] == record_type
                 and r['content'] == value), None)

            if state == 'present':
                changed = False
                if is_solo:
                    # delete any records that have the same name and record type
                    same_type = [
                        r['id'] for r in records if r['name'] == record
                        and r['record_type'] == record_type
                    ]
                    if rr:
                        same_type = [
                            rid for rid in same_type if rid != rr['id']
                        ]
                    if same_type:
                        if not module.check_mode:
                            for rid in same_type:
                                client.delete_record(str(domain), rid)
                        changed = True
                if rr:
                    # check if we need to update
                    if rr['ttl'] != ttl or rr['prio'] != priority:
                        data = {}
                        if ttl:
                            data['ttl'] = ttl
                        if priority:
                            data['prio'] = priority
                        if module.check_mode:
                            module.exit_json(changed=True)
                        else:
                            module.exit_json(changed=True,
                                             result=client.update_record(
                                                 str(domain), str(rr['id']),
                                                 data)['record'])
                    else:
                        module.exit_json(changed=changed, result=rr)
                else:
                    # create it
                    data = {
                        'name': record,
                        'record_type': record_type,
                        'content': value,
                    }
                    if ttl:
                        data['ttl'] = ttl
                    if priority:
                        data['prio'] = priority
                    if module.check_mode:
                        module.exit_json(changed=True)
                    else:
                        module.exit_json(changed=True,
                                         result=client.add_record(
                                             str(domain), data)['record'])
            elif state == 'absent':
                if rr:
                    if not module.check_mode:
                        client.delete_record(str(domain), rr['id'])
                    module.exit_json(changed=True)
                else:
                    module.exit_json(changed=False)
            else:
                module.fail_json(
                    msg="'%s' is an unknown value for the state argument" %
                    state)

        # Make sure these record_ids either all exist or none
        if domain and record_ids:
            current_records = [
                str(r['record']['id']) for r in client.records(str(domain))
            ]
            wanted_records = [str(r) for r in record_ids]
            if state == 'present':
                difference = list(set(wanted_records) - set(current_records))
                if difference:
                    module.fail_json(msg="Missing the following records: %s" %
                                     difference)
                else:
                    module.exit_json(changed=False)
            elif state == 'absent':
                difference = list(set(wanted_records) & set(current_records))
                if difference:
                    if not module.check_mode:
                        for rid in difference:
                            client.delete_record(str(domain), rid)
                    module.exit_json(changed=True)
                else:
                    module.exit_json(changed=False)
            else:
                module.fail_json(
                    msg="'%s' is an unknown value for the state argument" %
                    state)

    except DNSimpleException as e:
        module.fail_json(msg="Unable to contact DNSimple: %s" % e.message)

    module.fail_json(msg="Unknown what you wanted me to do")
userinfo = pwd.getpwnam(default_user)
uid = userinfo.pw_uid

#check if the desired site exists on this box
if not os.path.exists(site_root):
    os.makedirs(site_root)
    os.chmod(site_root, 0770)
    os.chown(site_root, uid, gid)
    
    os.makedirs(public_html)
    os.chmod(public_html, 0774)
    os.chown(public_html, uid, gid)

    #write the virtual host configuration file
    outfile = open(conf_file, 'w')

    outfile.write("<VirtualHost *:80>\n")
    outfile.write("\tServerName "+fqdn+"\n")
    outfile.write("\tDocumentRoot "+public_html+"\n")
    outfile.write("\tErrorLog /var/log/httpd/"+fqdn+".log\n")
    outfile.write("\tCustomLog /var/log/httpd/"+fqdn+".log combined\n")
    outfile.write("</VirtualHost>")

    outfile.close()
    
    if use_dnsimple == 1:
        #create a dictionary with record data
        new_record = {'record_type' : 'A', 'name' : prefix, 'content' : ip}
        #add the record
        dns.add_record(base, new_record)
Example #10
0
def main():
    module = AnsibleModule(
        argument_spec = dict(
            account_email     = dict(required=False),
            account_api_token = dict(required=False, no_log=True),
            domain            = dict(required=False),
            record            = dict(required=False),
            record_ids        = dict(required=False, type='list'),
            type              = dict(required=False, choices=['A', 'ALIAS', 'CNAME', 'MX', 'SPF', 'URL', 'TXT', 'NS', 'SRV', 'NAPTR', 'PTR', 'AAAA', 'SSHFP', 'HINFO', 'POOL']),
            ttl               = dict(required=False, default=3600, type='int'),
            value             = dict(required=False),
            priority          = dict(required=False, type='int'),
            state             = dict(required=False, choices=['present', 'absent']),
            solo              = dict(required=False, type='bool'),
        ),
        required_together = (
            ['record', 'value']
        ),
        supports_check_mode = True,
    )

    if not HAS_DNSIMPLE:
        module.fail_json(msg="dnsimple required for this module")

    account_email     = module.params.get('account_email')
    account_api_token = module.params.get('account_api_token')
    domain            = module.params.get('domain')
    record            = module.params.get('record')
    record_ids        = module.params.get('record_ids')
    record_type       = module.params.get('type')
    ttl               = module.params.get('ttl')
    value             = module.params.get('value')
    priority          = module.params.get('priority')
    state             = module.params.get('state')
    is_solo           = module.params.get('solo')

    if account_email and account_api_token:
        client = DNSimple(email=account_email, api_token=account_api_token)
    elif os.environ.get('DNSIMPLE_EMAIL') and os.environ.get('DNSIMPLE_API_TOKEN'):
        client = DNSimple(email=os.environ.get('DNSIMPLE_EMAIL'), api_token=os.environ.get('DNSIMPLE_API_TOKEN'))
    else:
        client = DNSimple()

    try:
        # Let's figure out what operation we want to do

        # No domain, return a list
        if not domain:
            domains = client.domains()
            module.exit_json(changed=False, result=[d['domain'] for d in domains])

        # Domain & No record
        if domain and record is None and not record_ids:
            domains = [d['domain'] for d in client.domains()]
            if domain.isdigit():
                dr = next((d for d in domains if d['id'] == int(domain)), None)
            else:
                dr = next((d for d in domains if d['name'] == domain), None)
            if state == 'present':
                if dr:
                    module.exit_json(changed=False, result=dr)
                else:
                    if module.check_mode:
                        module.exit_json(changed=True)
                    else:
                        module.exit_json(changed=True, result=client.add_domain(domain)['domain'])
            elif state == 'absent':
                if dr:
                    if not module.check_mode:
                        client.delete(domain)
                    module.exit_json(changed=True)
                else:
                    module.exit_json(changed=False)
            else:
                module.fail_json(msg="'%s' is an unknown value for the state argument" % state)

        # need the not none check since record could be an empty string
        if domain and record is not None:
            records = [r['record'] for r in client.records(str(domain))]

            if not record_type:
                module.fail_json(msg="Missing the record type")

            if not value:
                module.fail_json(msg="Missing the record value")

            rr = next((r for r in records if r['name'] == record and r['record_type'] == record_type and r['content'] == value), None)

            if state == 'present':
                changed = False
                if is_solo:
                    # delete any records that have the same name and record type
                    same_type = [r['id'] for r in records if r['name'] == record and r['record_type'] == record_type]
                    if rr:
                        same_type = [rid for rid in same_type if rid != rr['id']]
                    if same_type:
                        if not module.check_mode:
                            for rid in same_type:
                                client.delete_record(str(domain), rid)
                        changed = True
                if rr:
                    # check if we need to update
                    if rr['ttl'] != ttl or rr['prio'] != priority:
                        data = {}
                        if ttl:      data['ttl']  = ttl
                        if priority: data['prio'] = priority
                        if module.check_mode:
                            module.exit_json(changed=True)
                        else:
                            module.exit_json(changed=True, result=client.update_record(str(domain), str(rr['id']), data)['record'])
                    else:
                        module.exit_json(changed=changed, result=rr)
                else:
                    # create it
                    data = {
                        'name':        record,
                        'record_type': record_type,
                        'content':     value,
                    }
                    if ttl:      data['ttl']  = ttl
                    if priority: data['prio'] = priority
                    if module.check_mode:
                        module.exit_json(changed=True)
                    else:
                        module.exit_json(changed=True, result=client.add_record(str(domain), data)['record'])
            elif state == 'absent':
                if rr:
                    if not module.check_mode:
                        client.delete_record(str(domain), rr['id'])
                    module.exit_json(changed=True)
                else:
                    module.exit_json(changed=False)
            else:
                module.fail_json(msg="'%s' is an unknown value for the state argument" % state)

        # Make sure these record_ids either all exist or none
        if domain and record_ids:
            current_records = [str(r['record']['id']) for r in client.records(str(domain))]
            wanted_records  = [str(r) for r in record_ids]
            if state == 'present':
                difference = list(set(wanted_records) - set(current_records))
                if difference:
                    module.fail_json(msg="Missing the following records: %s" % difference)
                else:
                    module.exit_json(changed=False)
            elif state == 'absent':
                difference = list(set(wanted_records) & set(current_records))
                if difference:
                    if not module.check_mode:
                        for rid in difference:
                            client.delete_record(str(domain), rid)
                    module.exit_json(changed=True)
                else:
                    module.exit_json(changed=False)
            else:
                module.fail_json(msg="'%s' is an unknown value for the state argument" % state)

    except DNSimpleException:
        e = get_exception()
        module.fail_json(msg="Unable to contact DNSimple: %s" % e.message)

    module.fail_json(msg="Unknown what you wanted me to do")
Example #11
0
class DNSimpleV1():
    """class which uses dnsimple-python < 2"""

    def __init__(self, account_email, account_api_token, sandbox, module):
        """init"""
        self.module = module
        self.account_email = account_email
        self.account_api_token = account_api_token
        self.sandbox = sandbox
        self.dnsimple_client()

    def dnsimple_client(self):
        """creates a dnsimple client object"""
        if self.account_email and self.account_api_token:
            self.client = DNSimple(sandbox=self.sandbox, email=self.account_email, api_token=self.account_api_token)
        else:
            self.client = DNSimple(sandbox=self.sandbox)

    def get_all_domains(self):
        """returns a list of all domains"""
        domain_list = self.client.domains()
        return [d['domain'] for d in domain_list]

    def get_domain(self, domain):
        """returns a single domain by name or id"""
        try:
            dr = self.client.domain(domain)['domain']
        except DNSimpleException as e:
            exception_string = str(e.args[0]['message'])
            if re.match(r"^Domain .+ not found$", exception_string):
                dr = None
            else:
                raise
        return dr

    def create_domain(self, domain):
        """create a single domain"""
        return self.client.add_domain(domain)['domain']

    def delete_domain(self, domain):
        """delete a single domain"""
        self.client.delete(domain)

    def get_records(self, domain, dnsimple_filter=None):
        """return dns ressource records which match a specified filter"""
        return [r['record'] for r in self.client.records(str(domain), params=dnsimple_filter)]

    def delete_record(self, domain, rid):
        """delete a single dns ressource record"""
        self.client.delete_record(str(domain), rid)

    def update_record(self, domain, rid, ttl=None, priority=None):
        """update a single dns ressource record"""
        data = {}
        if ttl:
            data['ttl'] = ttl
        if priority:
            data['priority'] = priority
        return self.client.update_record(str(domain), str(rid), data)['record']

    def create_record(self, domain, name, record_type, content, ttl=None, priority=None):
        """create a single dns ressource record"""
        data = {
            'name': name,
            'type': record_type,
            'content': content,
        }
        if ttl:
            data['ttl'] = ttl
        if priority:
            data['priority'] = priority
        return self.client.add_record(str(domain), data)['record']
Example #12
0
uid = userinfo.pw_uid

#check if the desired site exists on this box
if not os.path.exists(site_root):
    os.makedirs(site_root)
    os.chmod(site_root, 0770)
    os.chown(site_root, uid, gid)

    os.makedirs(public_html)
    os.chmod(public_html, 0774)
    os.chown(public_html, uid, gid)

    #write the virtual host configuration file
    outfile = open(conf_file, 'w')

    outfile.write("<VirtualHost *:80>\n")
    outfile.write("\tServerName " + fqdn + "\n")
    outfile.write("\tDocumentRoot " + public_html + "\n")
    outfile.write("\tErrorLog /var/log/httpd/" + fqdn + ".log\n")
    outfile.write("\tCustomLog /var/log/httpd/" + fqdn + ".log combined\n")
    outfile.write("</VirtualHost>")

    outfile.close()

    #create DNSimple object
    dns = DNSimple(email=dnsimple_email_address, api_token=dnsimple_api_token)
    #create a dictionary with record data
    new_record = {'record_type': 'A', 'name': prefix, 'content': ip}
    #add the record
    dns.add_record(base, new_record)