Exemplo n.º 1
0
    def add_dns_entries(self, vm, credentials, subscription_id):
        """
        Add the required entries in the Azure DNS service

        Arguments:
           - vm(:py:class:`IM.VirtualMachine`): VM information.
           - credentials, subscription_id: Authentication data to access cloud provider.
        """
        try:
            group_name = vm.id.split('/')[0]
            dns_client = DnsManagementClient(credentials, subscription_id)
            system = vm.info.systems[0]
            for net_name in system.getNetworkIDs():
                num_conn = system.getNumNetworkWithConnection(net_name)
                ip = system.getIfaceIP(num_conn)
                (hostname, domain) = vm.getRequestedNameIface(
                    num_conn,
                    default_hostname=Config.DEFAULT_VM_NAME,
                    default_domain=Config.DEFAULT_DOMAIN)
                if domain != "localdomain" and ip:
                    zone = None
                    try:
                        zone = dns_client.zones.get(group_name, domain)
                    except Exception:
                        pass
                    if not zone:
                        self.log_info("Creating DNS zone %s" % domain)
                        zone = dns_client.zones.create_or_update(
                            group_name, domain, {'location': 'global'})
                    else:
                        self.log_info("DNS zone %s exists. Do not create." %
                                      domain)

                    if zone:
                        record = None
                        try:
                            record = dns_client.record_sets.get(
                                group_name, domain, hostname, 'A')
                        except Exception:
                            pass
                        if not record:
                            self.log_info("Creating DNS record %s." % hostname)
                            record_data = {
                                "ttl": 300,
                                "arecords": [{
                                    "ipv4_address": ip
                                }]
                            }
                            dns_client.record_sets.create_or_update(
                                group_name, domain, hostname, 'A', record_data)
                        else:
                            self.log_info(
                                "DNS record %s exists. Do not create." %
                                hostname)

            return True
        except Exception:
            self.log_exception("Error creating DNS entries")
            return False
Exemplo n.º 2
0
 def __init__(self, cfg):
     if cfg:
         self.credentials = ServicePrincipalCredentials(
             client_id=cfg['client_id'],
             secret=cfg['client_secret'],
             tenant=cfg['tenant_id'])
     self.dnsClient = DnsManagementClient(self.credentials,
                                          cfg['subscription_id'])
Exemplo n.º 3
0
 def _dns_client(self):
     if self.__dns_client is None:
         credentials = ServicePrincipalCredentials(
             self._dns_client_client_id,
             secret=self._dns_client_key,
             tenant=self._dns_client_directory_id)
         self.__dns_client = DnsManagementClient(
             credentials, self._dns_client_subscription_id)
     return self.__dns_client
Exemplo n.º 4
0
Arquivo: app.py Projeto: yolocs/prompt
def get_dns_client():
    from azure.common.credentials import ServicePrincipalCredentials
    from azure.mgmt.dns import DnsManagementClient
    credentials = ServicePrincipalCredentials(
        client_id = AUTH_CLIENTID,
        secret = AUTH_CLIENTSECRET,
        tenant = AUTH_TENANT
    )
    return DnsManagementClient(credentials, SUBSCRIPTION_ID)
 def __init__(self, credential: ChainedTokenCredential, options: Options):
     self.options = options
     self._cert_client = CertificateClient(options.azure_keyvault_uri,
                                           credential)
     self._dns_client = DnsManagementClient(credential,
                                            options.azure_subscription_id)
     blob_svc_client = BlobServiceClient.from_connection_string(
         options.cert_request_connection_str, )
     self._container_client = blob_svc_client.get_container_client(
         options.cert_request_container)
Exemplo n.º 6
0
    def _get_azure_client(self, subscription_id):
        """
        Gets azure DNS client

        :param subscription_id: Azure subscription ID
        :type subscription_id: str
        :return: Azure DNS client
        :rtype: DnsManagementClient
        """
        return DnsManagementClient(self.credential, subscription_id)
Exemplo n.º 7
0
 def dns_client(self):
     self.log('Getting dns client')
     if not self._dns_client:
         self.check_client_version('dns', dns_client_version, AZURE_EXPECTED_VERSIONS['dns_client_version'])
         self._dns_client = DnsManagementClient(
             self.azure_credentials,
             self.subscription_id,
             base_url=self.base_url
         )
         self._register('Microsoft.Dns')
     return self._dns_client
Exemplo n.º 8
0
 def _dns_client(self):
     if self.__dns_client is None:
         credential = ClientSecretCredential(
             client_id=self._dns_client_client_id,
             client_secret=self._dns_client_key,
             tenant_id=self._dns_client_directory_id
         )
         self.__dns_client = DnsManagementClient(
             credential=credential,
             subscription_id=self._dns_client_subscription_id
         )
     return self.__dns_client
Exemplo n.º 9
0
 def dns_client(self):
     self.log('Getting dns client')
     if not self._dns_client:
         self.check_client_version(
             'dns', dns_client_version,
             AZURE_EXPECTED_VERSIONS['dns_client_version'])
         self._dns_client = DnsManagementClient(
             self.azure_credentials,
             self.subscription_id,
             base_url=self._cloud_environment.endpoints.resource_manager,
         )
     return self._dns_client
Exemplo n.º 10
0
    def __init__(self, id, client_id, key, directory_id, sub_id,
                 resource_group, *args, **kwargs):
        self.log = logging.getLogger('AzureProvider[{}]'.format(id))
        self.log.debug('__init__: id=%s, client_id=%s, '
                       'key=***, directory_id:%s', id, client_id, directory_id)
        super(AzureProvider, self).__init__(id, *args, **kwargs)

        credentials = ServicePrincipalCredentials(
            client_id, secret=key, tenant=directory_id
        )
        self._dns_client = DnsManagementClient(credentials, sub_id)
        self._resource_group = resource_group
        self._azure_zones = set()
Exemplo n.º 11
0
    def authenticate(self, api_creds):
        """
        See: https://docs.microsoft.com/en-us/python/azure/python-sdk-azure-authenticate?view=azure-python
        :param api_creds: tuple of access credentials, see _read_credentials_file()
        :return:
        """
        credentials = ServicePrincipalCredentials(client_id=api_creds[2],
                                                  secret=api_creds[3],
                                                  tenant=api_creds[0])

        self.dns_client = DnsManagementClient(credentials, api_creds[1])

        # Sanity: See that an access token exists.
        if not self.dns_client._client.config.credentials.token['is_mrrt']:
            raise RuntimeError("Could not login!")
Exemplo n.º 12
0
    def __init__(self, resource_group, auth_path=None):
        self.resource_group = resource_group

        with open(auth_path, 'r') as f:
            account_json = json.load(f)

        self.dns_client = DnsManagementClient(
            ClientSecretCredential(
                tenant_id=account_json['tenantId'],
                client_id=account_json['clientId'],
                client_secret=account_json['clientSecret'],
                authority=account_json['activeDirectoryEndpointUrl']
            ),
            account_json['subscriptionId'],
            base_url=account_json['resourceManagerEndpointUrl'],
            credential_scopes=['{}/.default'.format(account_json['resourceManagerEndpointUrl'])]
        )
Exemplo n.º 13
0
def dns_challenge_handler(
    credential, subscription_id: str, dns_zone_resource_group: str,
    dns_zone_name: str,
    authorizations: List[acme.messages.AuthorizationResource],
    account_key: josepy.JWKRSA
) -> Generator[acme.messages.ChallengeResource, None, None]:
    """Extract DNS challenges and ensure they're created in Azure DNS"""
    def _get_dns_challenge(
        authzr: acme.messages.AuthorizationResource
    ) -> Tuple[acme.challenges.DNS01, str]:
        """Find DNS challenge from authorization challenge options"""
        challenge = next(c for c in authzr.body.challenges
                         if type(c.chall) == acme.challenges.DNS01)
        return challenge, authzr.body.identifier.value

    # Select DNS-01 within offered challenges by the CA server
    dns_challenges = (_get_dns_challenge(auth_resource)
                      for auth_resource in authorizations)

    #%%
    dns_auth = CredentialWrapper(credential)
    # dns_auth, subscription_id = get_azure_cli_credentials()
    dns_client = DnsManagementClient(dns_auth, subscription_id)

    #%%
    # Create the DNS records used for the challenge
    for dns_challenge, url in dns_challenges:
        # Drop the top level domain from the record value
        domain_prefix = '.'.join(url.split('.')[:-2])
        record_set_name = dns_challenge.chall.validation_domain_name(
            domain_prefix)
        record_set_value = dns_challenge.chall.validation(account_key)

        dns_client.record_sets.create_or_update(
            resource_group_name=dns_zone_resource_group,
            zone_name=dns_zone_name,
            relative_record_set_name=record_set_name,
            record_type='TXT',
            parameters={
                'ttl': 3600,
                'txtrecords': [{
                    'value': [record_set_value]
                }]
            })

        yield dns_challenge
Exemplo n.º 14
0
    def get_dns_client(self):
        """
        Get a connection to the Azure DNS service
        """
        if self.FILE_PATH is not None and self.FILE_PATH != "":
            from azure.common.client_factory import get_client_from_auth_file
            return get_client_from_auth_file(DnsManagementClient)

        elif self.KEY is not None and self.KEY != "":
            from azure.common.credentials import ServicePrincipalCredentials

            credentials = ServicePrincipalCredentials(client_id=self.CLIENT_ID,
                                                      secret=self.KEY,
                                                      tenant=self.TENANT_ID)

            dns_client = DnsManagementClient(credentials, self.SUBSCRIPTION_ID)

            return dns_client
Exemplo n.º 15
0
    def getCredential(self):
        self.credentials = ServicePrincipalCredentials(
            client_id=self.client_id,
            secret=self.secret,
            tenant=self.tenant_id)

        self.compute_client = ComputeManagementClient(self.credentials,
                                                      self.subscription_id)
        self.network_client = NetworkManagementClient(self.credentials,
                                                      self.subscription_id)
        self.storage_client = StorageManagementClient(self.credentials,
                                                      self.subscription_id)
        self.container_regisry_client = ContainerRegistryManagementClient(
            self.credentials, self.subscription_id)
        self.sql_client = SqlManagementClient(self.credentials,
                                              self.subscription_id)
        self.dns_client = DnsManagementClient(self.credentials,
                                              self.subscription_id)
Exemplo n.º 16
0
 def _dns_client(self):
     if self.__dns_client is None:
         # Azure's logger spits out a lot of debug messages at 'INFO'
         # level, override it by re-assigning `info` method to `debug`
         # (ugly hack until I find a better way)
         logger_name = 'azure.core.pipeline.policies.http_logging_policy'
         logger = logging.getLogger(logger_name)
         logger.info = logger.debug
         self.__dns_client = DnsManagementClient(
             credential=ClientSecretCredential(
                 client_id=self._dns_client_client_id,
                 client_secret=self._dns_client_key,
                 tenant_id=self._dns_client_directory_id,
                 logger=logger,
             ),
             subscription_id=self._dns_client_subscription_id,
         )
     return self.__dns_client
 def __init__(
     self,
     options: Options,
     credentials: ChainedTokenCredential,
     network: typing.Optional[NetworkManagementClient] = None,
     dns: typing.Optional[DnsManagementClient] = None,
     traffic_manager: typing.Optional[TrafficManagerManagementClient] = None,
 ):
     self.options = options
     self.credentials = credentials
     self.network = network or NetworkManagementClient(
         self.credentials, self.options.azure_subscription_id
     )
     self.dns = dns or DnsManagementClient(
         self.credentials, self.options.azure_subscription_id
     )
     self.traffic_manager = traffic_manager or TrafficManagerManagementClient(
         CredentialWrapper(self.credentials), self.options.azure_subscription_id
     )
async def _update_azuredns(config, credentials):
    """Update the Azure DNS Record with the external IP address."""
    # Get the external IP address of the Home Assistant instance.
    aiotimeout = aiohttp.ClientTimeout(total=config[DOMAIN][CONF_TIMEOUT])

    async with aiohttp.ClientSession(timeout=aiotimeout) as aiosession:
        async with aiosession.get('https://api.ipify.org') as aioresp:
            ipv4address = (await aioresp.text())

    if not ipv4address:
        _LOGGER.error("Failed to get external IP address from ipify API")
    else:
        _LOGGER.debug("External IP address is: %s", ipv4address)

    # Create the request.
    dns_client = DnsManagementClient(credentials,
                                     config[DOMAIN][CONF_SUBSCRIPTIONID])

    try:
        dns_client.record_sets.create_or_update(
            config[DOMAIN][CONF_RESOURCEGROUPNAME],
            config[DOMAIN][CONF_DOMAIN], config[DOMAIN][CONF_HOST], RECORDTYPE,
            {
                "metadata": {
                    "Last_changed_by_Home_Assistant": str(datetime.now())
                },
                "ttl": config[DOMAIN][CONF_TTL],
                "arecords": [{
                    "ipv4_address": ipv4address
                }]
            })
    except CloudError as error:
        _LOGGER.error("Failed to create or update DNS record: %s", error)
        return False

    return True
Exemplo n.º 19
0
def main():
    # Parse arguments
    parser = argparse.ArgumentParser(description="Tool to upload DNS records to Azure DNS zones.", add_help=True)
    parser.add_argument("--tenant-id", type=str, required=False, help="Azure tenant ID.")
    parser.add_argument("--subscription-id", type=str, required=False, help="Azure subscription ID.")
    parser.add_argument("--resource-group", type=str, required=True, help="Azure resource group of the DNS zone.")
    parser.add_argument("--client-id", type=str, required=False, help="Client ID of service principal.")
    parser.add_argument("--zone", type=str, required=True, help="Name of the DNS zone to create records in.")
    parser.add_argument("--csv-file", type=str, required=True, help="CSV file with DNS records to be created.")
    args = parser.parse_args()

    if "AZURE_SUBSCRIPTION_ID" in os.environ:
        subscription_id = os.environ['AZURE_SUBSCRIPTION_ID']
    elif args.subscription_id is not None:
        subscription_id = args.subscription_id
    else:
        print_error("AZURE_SUBSCRIPTION_ID is a required parameter.")
        sys.exit(1)

    if "AZURE_CLIENT_ID" in os.environ:
        client_id = os.environ['AZURE_CLIENT_ID']
    elif args.client_id is not None:
        client_id = args.client_id
    else:
        print_error("AZURE_CLIENT_ID is a required parameter.")
        sys.exit(1)

    if "AZURE_CLIENT_SECRET" in os.environ:
        client_secret = os.environ['AZURE_CLIENT_SECRET']
    else:
        client_secret = getpass.getpass("client-secret: ")

    if "AZURE_TENANT_ID" in os.environ:
        tenant_id = os.environ['AZURE_TENANT_ID']
    elif args.tenant_id is not None:
        tenant_id = args.tenant_id
    else:
        print_error("AZURE_TENANT_ID is a required parameter.")
        sys.exit(1)

    # Make sure that zone name does not start with "." nor ends with "."
    zone_name = args.zone
    if zone_name.startswith("."):
        zone_name = re.sub(r"^\.", r"", zone_name)
    
    if zone_name.endswith("."):
        zone_name = re.sub(r"\.$", r"", zone_name)

    warnings = []
    errors = []
    records_created = []


    credentials = ServicePrincipalCredentials(client_id=client_id, secret=client_secret, tenant=tenant_id)
    dns_client = DnsManagementClient(credentials, subscription_id)

    # Check if zone exists
    try:
        dns_client.zones.get(args.resource_group, zone_name)
    except CloudError as e:
        print(e)
        sys.exit(1)
    
    # Read zone from CSV file and create dict
    zone_dict = create_zone_dict_from_csv_file(args.csv_file)

    dns_names_sorted = zone_dict.keys()

    # Filter records in CSV file. Keep only those matching zone postfix.
    dns_names_filtered = []
    for dns_name in dns_names_sorted:
        m = re.search(r"(^|\.)%s$" % zone_name, dns_name)
        if m is not None:
            dns_names_filtered.append(dns_name)
    dns_names_sorted = dns_names_filtered

    # Sort names
    dns_names_sorted.sort()

    # Check record types in CSV file
    record_types_in_zone = set([])
    for dns_name in dns_names_sorted:
        records = zone_dict[dns_name]
        for record in records:
            record_types_in_zone.add(record["type"])
    
    record_types_supported = [ "A", "AAAA", "CNAME" ]

    for record_type in record_types_in_zone:
        if record_type not in record_types_supported:
            warnings.append("Record(s) of type %s in CSV file which is currently not supported by the tool. Please handle records manually." % record_type)

    # Update Azure zone
    for dns_name in dns_names_sorted:
        name = re.sub(r"(^|\.)%s$" % zone_name, r"", dns_name)
        if name == "":
            name = "@"

        a_record_set = { "ttl": 0, "data": [] }
        aaaa_record_set = { "ttl": 0, "data": [] }
        cname_record_set = { "ttl": 0, "data": [] }

        records = zone_dict[dns_name]
        for record in records:
            if record["type"] == "A":
                # Assumption: TTL is the same for each entry of a DNS record set.
                # Thus, we take the last occurence.
                a_record_set["ttl"] = record["ttl"]
                a_record_set["data"].append(record["data"])

            elif record["type"] == "AAAA":
                # Assumption: TTL is the same for each entry of a DNS record set.
                # Thus, we take the last occurence.
                aaaa_record_set["ttl"] = record["ttl"]
                aaaa_record_set["data"].append(record["data"])

            elif record["type"] == "CNAME":
                # Assumption: TTL is the same for each entry of a DNS record set.
                # Thus, we take the last occurence.
                cname_record_set["ttl"] = record["ttl"]

                ref_name = record["data"]
                # Azure DNS seems to not support relative names
                if not ref_name.endswith("."):
                    ref_name_old = ref_name
                    ref_name = "%s.%s." % (ref_name, zone_name)
                    warnings.append("Name %s referenced by CNAME record %s is not terminated with a dot (\".\"). This might cause unexpected behavior in Azure DNS. Hence, zone name was added to the name: %s" % (ref_name_old, name, ref_name))
                
                cname_record_set["data"].append(ref_name)
            
        if a_record_set["data"] != []:
            data = [ { "ipv4_address": x } for x in a_record_set["data"] ]

            record_set = {
                "ttl": a_record_set["ttl"],
                "arecords": data
            }

            # Get record to check if it is already existing
            record_exists = False
            try:
                dns_client.record_sets.get(args.resource_group, zone_name, name, "A")
                record_exists = True
            except CloudError as e:
                pass
            
            # Create record
            if record_exists == False:
                try:
                    dns_client.record_sets.create_or_update(args.resource_group, zone_name, name, "A", record_set)
                except CloudError as e:
                    errors.append("Error while creating record set A for name %s." % name)

                for x in a_record_set["data"]:
                    records_created.append("%s;%s;A;%s" % (name, a_record_set["ttl"], x))
            else:
                warnings.append("Record set A for name %s already exists. Skipping record set." % name)
        

        if aaaa_record_set["data"] != []:
            data = [ { "ipv6_address": x } for x in aaaa_record_set["data"] ]

            record_set = {
                "ttl": aaaa_record_set["ttl"],
                "aaaarecords": data
            }

            # Get record to check if it is already existing
            record_exists = False
            try:
                dns_client.record_sets.get(args.resource_group, zone_name, name, "AAAA")
                record_exists = True
            except CloudError as e:
                pass
            
            # Create record
            if record_exists == False:
                try:
                    dns_client.record_sets.create_or_update(args.resource_group, zone_name, name, "AAAA", record_set)
                except CloudError as e:
                    errors.append("Error while creating record set AAAA for name %s." % name)

                for x in aaaa_record_set["data"]:
                    records_created.append("%s;%s;AAAA;%s" % (name, aaaa_record_set["ttl"], x))
            else:
                warnings.append("Record set AAAA for name %s already exists. Skipping record set." % name)
        

        if cname_record_set["data"] != []:
            if len(cname_record_set["data"]) > 1:
                errors.append("More than one alias in CNAME record set for name %s. This is not valid! Record set skipped." % name)
            else:
                record_set = {
                    "ttl": cname_record_set["ttl"],
                    "cname_record": {
                        "cname": cname_record_set["data"][0]
                    }
                }

                # Get record to check if it is already existing
                record_exists = False
                try:
                    dns_client.record_sets.get(args.resource_group, zone_name, name, "CNAME")
                    record_exists = True
                except CloudError as e:
                    pass
                
                # Create record
                if record_exists == False:
                    try:
                        dns_client.record_sets.create_or_update(args.resource_group, zone_name, name, "CNAME", record_set)
                    except CloudError as e:
                        errors.append("Error while creating record set CNAME for name %s." % name)

                    records_created.append("%s;%s;CNAME;%s" % (name, cname_record_set["ttl"], cname_record_set["data"][0]))
                else:
                    warnings.append("Record set CNAME for name %s already exists. Skipping record set." % name)

    # Output
    if len(records_created) > 0:
        print("")
        print(bcolors.OKGREEN + bcolors.BOLD + "Record sets successfully created:" + bcolors.ENDC)
        for line in records_created:
            print(line)

    if len(warnings) > 0:
        print("")
        print(bcolors.WARNING + bcolors.BOLD + "Warnings:" + bcolors.ENDC)
        for line in warnings:
            print(line)
    
    if len(errors) > 0:
        print("")
        print(bcolors.FAIL + bcolors.BOLD + "Errors:" + bcolors.ENDC)
        for line in errors:
            print(line)
Exemplo n.º 20
0
def main():
    # Parse arguments
    parser = argparse.ArgumentParser(
        description="Tool to download DNS zones from Azure.", add_help=True)
    parser.add_argument("--tenant-id",
                        type=str,
                        required=False,
                        help="Azure tenant ID.")
    parser.add_argument("--subscription-id",
                        type=str,
                        required=False,
                        help="Azure subscription ID.")
    parser.add_argument("--resource-group",
                        type=str,
                        required=True,
                        help="Azure resource group of the DNS zone.")
    parser.add_argument("--client-id",
                        type=str,
                        required=False,
                        help="Client ID of service principal.")
    parser.add_argument("--zone",
                        type=str,
                        required=True,
                        help="Name of the DNS zone to dump.")
    parser.add_argument("--csv-file",
                        type=str,
                        required=True,
                        help="CSV file name to write the records to.")
    args = parser.parse_args()

    if "AZURE_SUBSCRIPTION_ID" in os.environ:
        subscription_id = os.environ['AZURE_SUBSCRIPTION_ID']
    elif args.subscription_id is not None:
        subscription_id = args.subscription_id
    else:
        print_error("AZURE_SUBSCRIPTION_ID is a required parameter.")
        sys.exit(1)

    if "AZURE_CLIENT_ID" in os.environ:
        client_id = os.environ['AZURE_CLIENT_ID']
    elif args.client_id is not None:
        client_id = args.client_id
    else:
        print_error("AZURE_CLIENT_ID is a required parameter.")
        sys.exit(1)

    if "AZURE_CLIENT_SECRET" in os.environ:
        client_secret = os.environ['AZURE_CLIENT_SECRET']
    else:
        client_secret = getpass.getpass("client-secret: ")

    if "AZURE_TENANT_ID" in os.environ:
        tenant_id = os.environ['AZURE_TENANT_ID']
    elif args.tenant_id is not None:
        tenant_id = args.tenant_id
    else:
        print_error("AZURE_TENANT_ID is a required parameter.")
        sys.exit(1)

    # Make sure that zone name does not start with "." nor ends with "."
    zone_name = args.zone
    if zone_name.startswith("."):
        zone_name = re.sub(r"^\.", r"", zone_name)

    if zone_name.endswith("."):
        zone_name = re.sub(r"\.$", r"", zone_name)

    warnings = []

    credentials = ServicePrincipalCredentials(client_id=client_id,
                                              secret=client_secret,
                                              tenant=tenant_id)
    dns_client = DnsManagementClient(credentials, subscription_id)

    # Check if zone exists
    try:
        zone = dns_client.zones.get(args.resource_group, zone_name)
    except CloudError as e:
        print(e)
        sys.exit(1)

    try:
        record_sets = dns_client.record_sets.list_all_by_dns_zone(
            args.resource_group, zone_name)
    except CloudError as e:
        print(e)
        sys.exit(1)

    f = open(args.csv_file, "w")

    for record_set in record_sets:
        if record_set.name == "@":
            dns_name = zone_name
        else:
            dns_name = "%s.%s" % (record_set.name, zone_name)

        if record_set.arecords is not None:
            for arecord in record_set.arecords:
                csv_row = "%s;%s;A;%s\n" % (dns_name, record_set.ttl,
                                            arecord.ipv4_address)
                f.write(csv_row)

        if record_set.aaaa_records is not None:
            for aaaa_record in record_set.aaaa_records:
                csv_row = "%s;%s;AAAA;%s\n" % (dns_name, record_set.ttl,
                                               aaaa_record.ipv6_address)
                f.write(csv_row)

        if record_set.mx_records is not None:
            warnings.append(
                "MX records exist in the zone but MX records are not supported by this tool. Hence this record types are missing in the CSV file."
            )

        if record_set.ns_records is not None:
            for ns_record in record_set.ns_records:
                ref_name = ns_record.nsdname
                if not ref_name.endswith("."):
                    warnings.append(
                        "Name %s referenced by NS record %s is not terminated with a dot (\".\"). This might cause unexpected behavior in Azure DNS."
                        % (ref_name, dns_name))
                    ref_name = "%s.%s." % (ref_name, zone_name)

                csv_row = "%s;%s;NS;%s\n" % (dns_name, record_set.ttl,
                                             ref_name)
                f.write(csv_row)

        if record_set.ptr_records is not None:
            warnings.append(
                "PTR records exist in the zone but PTR records are not supported by this tool. Hence this record types are missing in the CSV file."
            )

        if record_set.srv_records is not None:
            warnings.append(
                "SRV records exist in the zone but SRV records are not supported by this tool. Hence this record types are missing in the CSV file."
            )

        if record_set.txt_records is not None:
            warnings.append(
                "TXT records exist in the zone but TXT records are not supported by this tool. Hence this record types are missing in the CSV file."
            )

        if record_set.cname_record is not None:
            ref_name = record_set.cname_record.cname
            if not ref_name.endswith("."):
                warnings.append(
                    "Name %s referenced by CNAME record %s is not terminated with a dot (\".\"). This might cause unexpected behavior in Azure DNS."
                    % (ref_name, dns_name))
                ref_name = "%s.%s." % (ref_name, zone_name)

            csv_row = "%s;%s;CNAME;%s\n" % (dns_name, record_set.ttl, ref_name)
            f.write(csv_row)

        if record_set.soa_record is not None:
            host = record_set.soa_record.host
            email = record_set.soa_record.email
            serial_number = record_set.soa_record.serial_number
            refresh_time = record_set.soa_record.refresh_time
            retry_time = record_set.soa_record.retry_time
            expire_time = record_set.soa_record.expire_time
            minimum_ttl = record_set.soa_record.minimum_ttl

            if not host.endswith("."):
                warnings.append(
                    "Name %s referenced by SOA record %s is not terminated with a dot (\".\"). This might cause unexpected behavior in Azure DNS."
                    % (host, dns_name))
                host = "%s.%s." % (host, zone_name)

            data = "%s %s %d %d %d %d %d" % (host, email, serial_number,
                                             refresh_time, retry_time,
                                             expire_time, minimum_ttl)
            csv_row = "%s;%s;SOA;%s\n" % (dns_name, record_set.ttl, data)
            f.write(csv_row)

        if record_set.caa_records is not None:
            warnings.append(
                "CAA records exist in the zone but CAA records are not supported by this tool. Hence this record types are missing in the CSV file."
            )

    f.close()

    if len(warnings) > 0:
        print("")
        print(bcolors.WARNING + bcolors.BOLD + "Warnings:" + bcolors.ENDC)
        for line in warnings:
            print(line)
AZ_CLIENT_ID = os.environ.get('AZ_CLIENT_ID')
AZ_CLIENT_SECRET = os.environ.get('AZ_CLIENT_SECRET')
AZ_SUBSCRIPTION_ID = os.environ.get('AZ_SUBSCRIPTION_ID')

CERTBOT_VALIDATION = os.environ.get('CERTBOT_VALIDATION')
record_name = os.environ.get('CERTBOT_DOMAIN')
record_name = record_name[:record_name.index(DNS_ZONE)]
record_name = record_name.rstrip('.')

if len(record_name) == 0:
  record_name = "_acme-challenge"
else:
  record_name = "_acme-challenge." + record_name

credentials = ServicePrincipalCredentials(
  tenant = AZ_TENANT,
  client_id = AZ_CLIENT_ID,
  secret = AZ_CLIENT_SECRET)

dns_client = DnsManagementClient(
  credentials,
  AZ_SUBSCRIPTION_ID
)

dns_client.record_sets.delete(
  AZ_RESOURCE_GROUP,
  DNS_ZONE,
  record_name,
  'TXT',
)
from azure.common.credentials import ServicePrincipalCredentials

from config import Config

r = resolver.Resolver(configure=False)
# OpenDNS Servers (needed to determine current ip address)
r.nameservers = ['208.67.222.222', '208.67.220.220']
ips = r.query(Config['host'])
ips2 = r.query('myip.opendns.com')

record = ips[0].address
current = ips2[0].address

if record != current:
    credentials = ServicePrincipalCredentials(client_id=Config['clientId'],
                                              secret=Config['secret'],
                                              tenant=Config['tenant'])

    dns_client = DnsManagementClient(credentials, Config['subscriptionId'])

    dns_client.record_sets.create_or_update(
        Config['resourceGroup'], Config['zoneName'], Config['recordSetName'],
        'A', {
            'ttl': 60,
            'arecords': [{
                "ipv4_address": current
            }]
        })

    ts = strftime('%Y-%m-%d %H:%M:%S', gmtime())
    print(ts + ' Record updated to: ' + current)
Exemplo n.º 23
0
def az_client(appConfig: AppConfig):
    return DnsManagementClient(az_credentials(appConfig),
                               appConfig.az_subscription)
Exemplo n.º 24
0
from dotenv import load_dotenv
load_dotenv()
import os

subscription_id = os.getenv("SUBSCRIPTION_ID")

AAD_USER = os.getenv("AAD_DNS_USER")
AAD_PWD = os.getenv("AAD_DNS_PWD")

credentials = UserPassCredentials(
        AAD_USER,
        AAD_PWD,
)

dns_client = DnsManagementClient(
        credentials,
        subscription_id
)

def create_dns(name):
    dns_client.record_sets.create_or_update(
            "ifiduk-dns",
            "onifiduk.com",
            name,
            "CNAME",
            {
                "ttl": 300,
                "cname_record": {
                    "cname": "ifiduk-ch-01.australiasoutheast.cloudapp.azure.com"
                }
            }
    )