使用 .NET SDK 创建 DNS 区域和记录集Create DNS zones and record sets using the .NET SDK

可以通过结合使用 DNS SDK 与 .NET DNS 管理库自动执行创建、删除或更新 DNS 区域、记录集和记录的操作。You can automate operations to create, delete, or update DNS zones, record sets, and records by using the DNS SDK with the .NET DNS Management library. 此处提供了完整的 Visual Studio 项目。A full Visual Studio project is available here.

创建服务主体帐户Create a service principal account

通常情况下,通过专用帐户(而不是自己的用户凭据)授予对 Azure 资源的编程访问权限。Typically, programmatic access to Azure resources is granted via a dedicated account rather than your own user credentials. 将这些专用帐户称为“服务主体”帐户。These dedicated accounts are called 'service principal' accounts. 若要使用 Azure DNS SDK 示例项目,首先需要创建一个服务主体帐户并为其分配正确的权限。To use the Azure DNS SDK sample project, you first need to create a service principal account and assign it the correct permissions.

  1. 请按照这些说明创建服务主体帐户(Azure DNS SDK 示例项目采用基于密码的身份验证。)Follow these instructions to create a service principal account (the Azure DNS SDK sample project assumes password-based authentication.)

  2. 创建资源组(此处提供了方法)。Create a resource group (here's how).

  3. 使用 Azure RBAC 将服务主体帐户的“DNS 区域参与者”权限授予资源组(此处提供了方法)。Use Azure RBAC to grant the service principal account 'DNS Zone Contributor' permissions to the resource group (here's how.)

  4. 如果使用 Azure DNS SDK 示例项目,请如下所示编辑 program.cs 文件:If using the Azure DNS SDK sample project, edit the 'program.cs' file as follows:

    • 请插入在步骤 1 中使用的 tenantIdclientId(也称为帐户 ID)、secret(服务主体帐户密码)和 subscriptionId 的正确值。Insert the correct values for the tenantId, clientId (also known as account ID), secret (service principal account password) and subscriptionId as used in step 1.
    • 输入在步骤 2 中选择的资源组名称。Enter the resource group name chosen in step 2.
    • 输入所选的 DNS 区域名称。Enter a DNS zone name of your choice.

NuGet 包和命名空间声明NuGet packages and namespace declarations

若要使用 Azure DNS .NET SDK,需要安装 Azure DNS 管理库 NuGet 包和其他所需的 Azure 包。To use the Azure DNS .NET SDK, you need to install the Azure DNS Management Library NuGet package and other required Azure packages.

  1. Visual Studio 中,打开项目或新的项目。In Visual Studio, open a project or new project.
  2. 转到“工具” > “NuGet 包管理器” > “管理解决方案的 NuGet 包...” 。Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution....
  3. 单击“浏览” ,启用“包括预发行版” 复选框,并在搜索框中键入 Microsoft.Azure.Management.DnsClick Browse, enable the Include prerelease checkbox, and type Microsoft.Azure.Management.Dns into the search box.
  4. 选择此包,然后单击“安装”将其添加到 Visual Studio 项目中。Select the package and click Install to add it to your Visual Studio project.
  5. 重复以上过程,还能安装以下包:Microsoft.Rest.ClientRuntime.Azure.AuthenticationMicrosoft.Azure.Management.ResourceManagerRepeat the process above to also install the following packages: Microsoft.Rest.ClientRuntime.Azure.Authentication and Microsoft.Azure.Management.ResourceManager.

添加命名空间声明Add namespace declarations

添加以下命名空间声明Add the following namespace declarations

using Microsoft.Rest.Azure.Authentication;
using Microsoft.Azure.Management.Dns;
using Microsoft.Azure.Management.Dns.Models;

初始化 DNS 管理客户端Initialize the DNS management client

DnsManagementClient 包含管理 DNS 区域和记录集所必需的方法和属性。The DnsManagementClient contains the methods and properties necessary for managing DNS zones and record sets. 以下代码登录到服务主体帐户并创建一个 DnsManagementClient 对象。The following code logs into the service principal account and creates a DnsManagementClient object.

// Build the service credentials and DNS management client
var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret, ActiveDirectoryServiceSettings.AzureChina);
var dnsClient = new DnsManagementClient(serviceCreds);
dnsClient.SubscriptionId = subscriptionId;
dnsClient.BaseUri= new System.Uri("https://management.chinacloudapi.cn");

创建或更新 DNS 区域Create or update a DNS zone

若要创建 DNS 区域,首先创建一个 "Zone" 对象来包含 DNS 区域参数。To create a DNS zone, first a "Zone" object is created to contain the DNS zone parameters. 因为 DNS 区域未链接到某一特定区域,此位置会被设置为 'global'。Because DNS zones are not linked to a specific region, the location is set to 'global'. 在此示例中,还会将 Azure 资源管理器“标记”添加到此区域。In this example, an Azure Resource Manager 'tag' is also added to the zone.

要实际创建或更新 Azure DNS 中的区域,会将包含区域参数的区域对象传递给 DnsManagementClient.Zones.CreateOrUpdateAsyc 方法。To actually create or update the zone in Azure DNS, the zone object containing the zone parameters is passed to the DnsManagementClient.Zones.CreateOrUpdateAsyc method.

备注

DnsManagementClient 支持三种操作模式:同步 ('CreateOrUpdate')、异步 ('CreateOrUpdateAsync') 或异步但可以访问 HTTP 响应 ('CreateOrUpdateWithHttpMessagesAsync')。DnsManagementClient supports three modes of operation: synchronous ('CreateOrUpdate'), asynchronous ('CreateOrUpdateAsync'), or asynchronous with access to the HTTP response ('CreateOrUpdateWithHttpMessagesAsync'). 可以选择上述任何一种模式,具体取决于应用程序的需要。You can choose any of these modes, depending on your application needs.

Azure DNS 支持乐观并发,称为 EtagAzure DNS supports optimistic concurrency, called Etags. 在此示例中,为“If-None-Match”标头指定 "*",通知 Azure DNS 创建一个 DNS 区域(如果尚不存在)。In this example, specifying "*" for the 'If-None-Match' header tells Azure DNS to create a DNS zone if one does not already exist. 如果指定的资源组内已存在具有特定名称的区域,此调用失败。The call fails if a zone with the given name already exists in the given resource group.

// Create zone parameters
var dnsZoneParams = new Zone("global"); // All DNS zones must have location = "global"

// Create an Azure Resource Manager 'tag'.  This is optional.  You can add multiple tags
dnsZoneParams.Tags = new Dictionary<string, string>();
dnsZoneParams.Tags.Add("dept", "finance");

// Create the actual zone.
// Note: Uses 'If-None-Match *' ETAG check, so will fail if the zone exists already.
// Note: For non-async usage, call dnsClient.Zones.CreateOrUpdate(resourceGroupName, zoneName, dnsZoneParams, null, "*")
// Note: For getting the http response, call dnsClient.Zones.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, zoneName, dnsZoneParams, null, "*")
var dnsZone = await dnsClient.Zones.CreateOrUpdateAsync(resourceGroupName, zoneName, dnsZoneParams, null, "*");

创建 DNS 记录集和记录Create DNS record sets and records

DNS 记录是作为记录集管理的。DNS records are managed as a record set. 记录集是区域内一组名称和记录类型都相同的记录。A record set is a set of records with the same name and record type within a zone. 记录集的名称相对于区域名称,而不是完全限定的 DNS 名称。The record set name is relative to the zone name, not the fully qualified DNS name.

若要创建或更新记录集,请创建“RecordSet”参数对象并将其传递到 DnsManagementClient.RecordSets.CreateOrUpdateAsyncTo create or update a record set, a "RecordSet" parameters object is created and passed to DnsManagementClient.RecordSets.CreateOrUpdateAsync. 和 DNS 区域一样,也有三种操作模式:同步 ('CreateOrUpdate')、异步 ('CreateOrUpdateAsync') 或异步但可以访问 HTTP 响应 ('CreateOrUpdateWithHttpMessagesAsync')。As with DNS zones, there are three modes of operation: synchronous ('CreateOrUpdate'), asynchronous ('CreateOrUpdateAsync'), or asynchronous with access to the HTTP response ('CreateOrUpdateWithHttpMessagesAsync').

和 DNS 区域一样,记录集的操作包括对乐观并发的支持。As with DNS zones, operations on record sets include support for optimistic concurrency. 在此示例中,由于既未指定 If-match 也未指定 If-None-Match,始终都会创建记录集。In this example, since neither 'If-Match' nor 'If-None-Match' are specified, the record set is always created. 此调用将覆盖 DNS 区域中任何现有的名称和记录类型都相同的记录。This call overwrites any existing record set with the same name and record type in this DNS zone.

// Create record set parameters
var recordSetParams = new RecordSet();
recordSetParams.TTL = 3600;

// Add records to the record set parameter object.  In this case, we'll add a record of type 'A'
recordSetParams.ARecords = new List<ARecord>();
recordSetParams.ARecords.Add(new ARecord("1.2.3.4"));

// Add metadata to the record set.  Similar to Azure Resource Manager tags, this is optional and you can add multiple metadata name/value pairs
recordSetParams.Metadata = new Dictionary<string, string>();
recordSetParams.Metadata.Add("user", "Mary");

// Create the actual record set in Azure DNS
// Note: no ETAG checks specified, will overwrite existing record set if one exists
var recordSet = await dnsClient.RecordSets.CreateOrUpdateAsync(resourceGroupName, zoneName, recordSetName, RecordType.A, recordSetParams);

获取区域和记录集Get zones and record sets

DnsManagementClient.Zones.GetDnsManagementClient.RecordSets.Get 方法分别检索单个区域和单个记录集。The DnsManagementClient.Zones.Get and DnsManagementClient.RecordSets.Get methods retrieve individual zones and record sets, respectively. RecordSets 按它们的类型、名称以及所在的区域和资源组进行标识。RecordSets are identified by their type, name, and the zone and resource group they exist in. 区域按它们的名称以及所在的资源组进行标识。Zones are identified by their name and the resource group they exist in.

var recordSet = dnsClient.RecordSets.Get(resourceGroupName, zoneName, recordSetName, RecordType.A);

更新现有的记录集Update an existing record set

要更新现有的 DNS 记录集,首先检索记录集,再更新记录集的内容,然后提交更改。To update an existing DNS record set, first retrieve the record set, then update the record set contents, then submit the change. 在此示例中,我们从 If-match 参数检索到的记录集内指定 Etag。In this example, we specify the 'Etag' from the retrieved record set in the 'If-Match' parameter. 如果在此期间并发操作修改了记录集,调用会失败。The call fails if a concurrent operation has modified the record set in the meantime.

var recordSet = dnsClient.RecordSets.Get(resourceGroupName, zoneName, recordSetName, RecordType.A);

// Add a new record to the local object.  Note that records in a record set must be unique/distinct
recordSet.ARecords.Add(new ARecord("5.6.7.8"));

// Update the record set in Azure DNS
// Note: ETAG check specified, update will be rejected if the record set has changed in the meantime
recordSet = await dnsClient.RecordSets.CreateOrUpdateAsync(resourceGroupName, zoneName, recordSetName, RecordType.A, recordSet, recordSet.Etag);

列出区域和记录集List zones and record sets

若要列出区域,请使用 DnsManagementClient.Zones.List... 方法,它支持列出给定资源组中的所有区域或给定 Azure 订阅中的所有区域(跨资源组)。若要列出记录集,请使用 DnsManagementClient.RecordSets.List... 方法,它支持列出给定区域中的所有记录集或仅列出特定类型的记录集。To list zones, use the DnsManagementClient.Zones.List... methods, which support listing either all zones in a given resource group or all zones in a given Azure subscription (across resource groups.) To list record sets, use DnsManagementClient.RecordSets.List... methods, which support either listing all record sets in a given zone or only those record sets of a specific type.

请注意,列出区域和记录集时,可能会对结果进行分页。Note when listing zones and record sets that results may be paginated. 下面的示例演示如何循环访问各页结果。The following example shows how to iterate through the pages of results. (人为减小的‘2’页面大小用于强制分页;在实践中,应省略此参数并使用默认页面大小。)(An artificially small page size of '2' is used to force paging; in practice this parameter should be omitted and the default page size used.)

// Note: in this demo, we'll use a very small page size (2 record sets) to demonstrate paging
// In practice, to improve performance you would use a large page size or just use the system default
int recordSets = 0;
var page = await dnsClient.RecordSets.ListAllInResourceGroupAsync(resourceGroupName, zoneName, "2");
recordSets += page.Count();

while (page.NextPageLink != null)
{
    page = await dnsClient.RecordSets.ListAllInResourceGroupNextAsync(page.NextPageLink);
    recordSets += page.Count();
}

后续步骤Next steps

下载 Azure DNS .NET SDK 示例项目,其中包括有关如何使用 Azure DNS .NET SDK 的更多示例,包括其他 DNS 记录类型的示例。Download the Azure DNS .NET SDK sample project, which includes further examples on how to use the Azure DNS .NET SDK, including examples for other DNS record types.