Ejemplo n.º 1
0
def obtain_domain_record(requested_domain, seed_profile=None):
    dns_driver = get_dns_driver(DNSProvider.ROUTE53)(settings.AWS_ACCESS,
                                                     settings.AWS_SECRET)
    record_types = {}
    [
        record_types.update({value: key})
        for key, value in RecordType.__dict__.copy().iteritems()
        if not key.startswith('_') and value.__class__ == int
    ]

    record_names = []

    for zone in dns_driver.list_zones():
        if zone.domain.lower() == requested_domain.lower():
            return zone

        for record in zone.list_records():
            if record_types.get(record.type) == 'CNAME' or record_types.get(
                    record.type) == 'A':
                # Because route53 is special, it encodes all * to \\052 ( utf-8 )
                if record.name == '\\052':
                    record_domain = '*.%s' % zone.domain
                else:
                    record_domain = '.'.join(
                        [record.name.encode('utf-8'), zone.domain])

                if record_domain == requested_domain.lower().encode('utf-8'):
                    return record

    return None
Ejemplo n.º 2
0
    def get_dns_driver(self, auth_data):
        """
        Get the DNS driver from the auth data

        Arguments:
            - auth(Authentication): parsed authentication tokens.

        Returns: a :py:class:`libcloud.dns.base.DNSDriver` or None in case of error
        """
        auths = auth_data.getAuthInfo(self.type)
        if not auths:
            raise Exception("No auth data has been specified to GCE.")
        else:
            auth = auths[0]

        if self.dns_driver and self.auth.compare(auth_data, self.type):
            return self.dns_driver
        else:
            self.auth = auth_data

            if 'username' in auth and 'password' in auth and 'project' in auth:
                cls = get_dns_driver(DNSProvider.GOOGLE)
                # Patch to solve some client problems with \\n
                auth['password'] = auth['password'].replace('\\n', '\n')
                lines = len(auth['password'].replace(" ", "").split())
                if lines < 2:
                    raise Exception(
                        "The certificate provided to the GCE plugin has an incorrect format."
                        " Check that it has more than one line.")

                driver = cls(auth['username'],
                             auth['password'],
                             project=auth['project'])

                self.dns_driver = driver
                return driver
            else:
                self.log_error(
                    "No correct auth data has been specified to GCE: username, password and project"
                )
                self.log_debug(auth)
                raise Exception(
                    "No correct auth data has been specified to GCE: username, password and project"
                )
Ejemplo n.º 3
0
def obtain_domain_record(requested_domain, seed_profile=None):
    dns_driver = get_dns_driver(DNSProvider.ROUTE53)(settings.AWS_ACCESS, settings.AWS_SECRET)
    record_types = {}
    [record_types.update({value:key}) for key,value in RecordType.__dict__.copy().iteritems() if not key.startswith('_') and value.__class__ == int]

    record_names = []

    for zone in dns_driver.list_zones():
        if zone.domain.lower() == requested_domain.lower():
            return zone

        for record in zone.list_records():
            if record_types.get(record.type) == 'CNAME' or record_types.get(record.type) == 'A':
                # Because route53 is special, it encodes all * to \\052 ( utf-8 )
                if record.name == '\\052':
                    record_domain = '*.%s' % zone.domain
                else:
                    record_domain = '.'.join([record.name.encode('utf-8'), zone.domain])

                if record_domain == requested_domain.lower().encode('utf-8'):
                    return record

    return None
Ejemplo n.º 4
0
from pprint import pprint

from libcloud.compute.providers import get_driver as get_compute_driver
from libcloud.compute.types import Provider as ComputeProvider
from libcloud.dns.providers import get_driver as get_dns_driver
from libcloud.dns.types import Provider as DNSProvider, RecordType

CREDENTIALS_RACKSPACE = ('username', 'api key')
CREDENTIALS_ZERIGO = ('email', 'api key')

Cls = get_compute_driver(ComputeProvider.RACKSPACE)
compute_driver = Cls(*CREDENTIALS_RACKSPACE)

Cls = get_dns_driver(DNSProvider.ZERIGO)
dns_driver = Cls(*CREDENTIALS_ZERIGO)

# Retrieve all the nodes
nodes = compute_driver.list_nodes()

# Create a new zone
zone = dns_driver.create_zone(domain='mydomain2.com')

created = []
for node in nodes:
    name = node.name

    ips = node.public_ip

    if not ips:
        continue
Ejemplo n.º 5
0
Archivo: dns.py Proyecto: flug/gonzo
 def __init__(self, aws_access_id, aws_secret_key):
     R53Driver = get_dns_driver(DNSProvider.ROUTE53)
     self.dns_session = R53Driver(aws_access_id, aws_secret_key)
Ejemplo n.º 6
0
parser.add_argument("--email")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--export", action="store_true")
group.add_argument("--import", action="store_true")

args = parser.parse_args()

try:
    provider_user = cfg.get(args.provider, "user")
    provider_apikey = cfg.get(args.provider, "apikey")
except (NoSectionError, NoOptionError):
    print "Wrong configuration. Create the file ~/.libcloud.conf with:"
    print config_example
    sys.exit(-1)

Cls = get_dns_driver(DNSProvider.RACKSPACE)
dns_driver = Cls(provider_user, provider_apikey)

rr_type_map = {}
for t in dns_driver.list_record_types():
    rr_type_map[t] = getattr(RecordType, t)


def export_zone(zone):
    for record in zone.list_records():
        print "%s;%s;%s;%s" % (record.name, record.type, record.data, json.dumps(record.extra))


def import_zone(zone):
    if zone:
        dns_driver.delete_zone(zone)
Ejemplo n.º 7
0
def drivers(config_map):
    for provider in config_map:
        cls = get_dns_driver(getattr(DNSProvider, provider))
        yield cls(*config_map[provider])
Ejemplo n.º 8
0
 def __init__(self, aws_access_id, aws_secret_key):
     R53Driver = get_dns_driver(DNSProvider.ROUTE53)
     self.dns_session = R53Driver(aws_access_id, aws_secret_key)
Ejemplo n.º 9
0
parser.add_argument("--email")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--export", action="store_true")
group.add_argument("--import", action="store_true")

args = parser.parse_args()

try:
    provider_user = cfg.get(args.provider, "user")
    provider_apikey = cfg.get(args.provider, "apikey")
except (NoSectionError, NoOptionError):
    print "Wrong configuration. Create the file ~/.libcloud.conf with:"
    print config_example
    sys.exit(-1)

Cls = get_dns_driver(DNSProvider.RACKSPACE)
dns_driver = Cls(provider_user, provider_apikey)

rr_type_map = {}
for t in dns_driver.list_record_types():
    rr_type_map[t] = getattr(RecordType, t)


def export_zone(zone):
    for record in zone.list_records():
        print '%s;%s;%s;%s' % \
                (record.name, record.type, record.data,
                        json.dumps(record.extra))


def import_zone(zone):
Ejemplo n.º 10
0
def create_dns_a_record(owner, domain_name, ip_addr):
    """Will try to create DNS A record for specified domain name and IP addr.

    All clouds for which there is DNS support will be tried to see if the
    relevant zone exists.

    """

    # split domain_name in dot separated parts
    parts = [part for part in domain_name.split('.') if part]
    # find all possible domains for this domain name, longest first
    all_domains = {}
    for i in range(1, len(parts) - 1):
        host = '.'.join(parts[:i])
        domain = '.'.join(parts[i:]) + '.'
        all_domains[domain] = host
    if not all_domains:
        raise MistError("Couldn't extract a valid domain from '%s'." %
                        domain_name)

    # iterate over all clouds that can also be used as DNS providers
    providers = {}
    clouds = Cloud.objects(owner=owner)
    for cloud in clouds:
        if isinstance(cloud, cloud_models.AmazonCloud):
            provider = DnsProvider.ROUTE53
            creds = cloud.apikey, cloud.apisecret
        # TODO: add support for more providers
        # elif cloud.provider == Provider.LINODE:
        #    pass
        # elif cloud.provider == Provider.RACKSPACE:
        #    pass
        else:
            # no DNS support for this provider, skip
            continue
        if (provider, creds) in providers:
            # we have already checked this provider with these creds, skip
            continue

        try:
            conn = get_dns_driver(provider)(*creds)
            zones = conn.list_zones()
        except InvalidCredsError:
            log.error("Invalid creds for DNS provider %s.", provider)
            continue
        except Exception as exc:
            log.error("Error listing zones for DNS provider %s: %r", provider,
                      exc)
            continue

        # for each possible domain, starting with the longest match
        best_zone = None
        for domain in all_domains:
            for zone in zones:
                if zone.domain == domain:
                    log.info("Found zone '%s' in provider '%s'.", domain,
                             provider)
                    best_zone = zone
                    break
            if best_zone:
                break

        # add provider/creds combination to checked list, in case multiple
        # clouds for same provider with same creds exist
        providers[(provider, creds)] = best_zone

    best = None
    for provider, creds in providers:
        zone = providers[(provider, creds)]
        if zone is None:
            continue
        if best is None or len(zone.domain) > len(best[2].domain):
            best = provider, creds, zone

    if not best:
        raise MistError("No DNS zone matches specified domain name.")

    provider, creds, zone = best
    name = all_domains[zone.domain]
    log.info("Will use name %s and zone %s in provider %s.", name, zone.domain,
             provider)

    # debug
    # log.debug("Will print all existing A records for zone '%s'.", zone.domain)
    # for record in zone.list_records():
    #    if record.type == 'A':
    #        log.info("%s -> %s", record.name, record.data)

    msg = ("Creating A record with name %s for %s in zone %s in %s" %
           (name, ip_addr, zone.domain, provider))
    try:
        record = zone.create_record(name, RecordType.A, ip_addr)
    except Exception as exc:
        raise MistError(msg + " failed: %r" % repr(exc))
    log.info(msg + " succeeded.")
    return record
from pprint import pprint

from libcloud.compute.providers import get_driver as get_compute_driver
from libcloud.compute.types import Provider as ComputeProvider
from libcloud.dns.providers import get_driver as get_dns_driver
from libcloud.dns.types import Provider as DNSProvider
from libcloud.dns.types import RecordType

CREDENTIALS_RACKSPACE = ("username", "api key")
CREDENTIALS_ZERIGO = ("email", "api key")

cls = get_compute_driver(ComputeProvider.RACKSPACE)
compute_driver = cls(*CREDENTIALS_RACKSPACE)

cls = get_dns_driver(DNSProvider.ZERIGO)
dns_driver = cls(*CREDENTIALS_ZERIGO)

# Retrieve all the nodes
nodes = compute_driver.list_nodes()

# Create a new zone
zone = dns_driver.create_zone(domain="mydomain2.com")

created = []

for node in nodes:
    name = node.name

    ip = node.public_ips[0] if node.public_ips else None

    if not ip: