C#/.NET:如何使用新的 ARM SDK 在 Azure DNS 区域中创建 DNS 记录?

问题描述 投票:0回答:1

我需要以编程方式在 Azure DNS 区域中创建 TXT DNS 记录。使用

Azure.Management.Dns
包,可以这样实现:

using Azure.Identity;
using Azure.Management.Dns;

var dnsClient = new DnsManagementClient(new DefaultAzureCredential()){SubscriptionId="mySubscriptionId"};
...
await dnsClient.RecordSets.CreateOrUpdateAsync(resourceGroupName, zoneName, recordSetName, RecordType.TXT, recordSet);

现在 MS 已将

Azure.Management.Dns
软件包标记为已弃用,并建议改用
Azure.ResourceManager.Dns
软件包。 Microsoft 自己的文档 但是仍然使用已弃用的包,包括示例。

不幸的是,我并没有真正看到相应新ARM模型的文档在哪里解释了如何创建新的TXT记录,遗憾的是MS没有提供任何相关示例。

有人可以指出我正确的方向吗?

编辑:最初声称 ARM 软件包将处于测试阶段,但事实证明并非如此。

.net azure dns azure-resource-manager azure-sdk
1个回答
0
投票

新的(2019 年后)

Azure.ResourceManager.*
NuGet 包库采用了较新的 C# 功能,例如
IAsyncEnumerable
,这使得一些操作对于那些期望更传统的 API 设计的人(比如我们)来说并不明显(所以实际上花了我花点时间弄清楚如何回答你的问题)。

但是你会想要这样的东西:

第 1 步:获取经过身份验证的
ArmClient
实例和您的目标
SubscriptionResource
:

这在 Linqpad 和控制台程序中适用于我,但显然您会想在部署的代码中使用

DefaultAzureCredential

const String TENANT_ID       = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
const String SUBSCRIPTION_ID = "ffffffff-1111-2222-3333-444444444444";

// Uncomment this if you're having AAD/Entra authX problems:
//using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger();

InteractiveBrowserCredentialOptions credsOpts = new InteractiveBrowserCredentialOptions()
{
    DisableAutomaticAuthentication = true,
    TenantId = TENANT_ID
};

// Uncomment this if you're having AAD/Entra authX problems:
//redsOpts.Diagnostics.IsAccountIdentifierLoggingEnabled = true;

InteractiveBrowserCredential creds = new InteractiveBrowserCredential( credsOpts );
AuthenticationRecord authRecord = await creds.AuthenticateAsync();

ArmClient armClient = new ArmClient( creds );

//

SubscriptionResource sub = await armClient.GetDefaultSubscriptionAsync();
if( sub.Id.SubscriptionId != SUBSCRIPTION_ID ) throw new InvalidOperationException( "Unexpected default Subscription." );

第2步:获取Zone,添加记录,提交:

  • 我们从步骤 1 中得到了
    ArmClient armClient
    SubscriptionResource sub
  • 您需要为 System.Linq.Async
     添加 
    ToListAsync()
  • .
    Dump()
    方法适用于 Linqpad。
List<DnsZoneResource> dnsZones = await sub.GetDnsZonesAsync().ToListAsync();
DnsZoneResource zone0 = dnsZones.First().Dump();

DnsTxtRecordCollection txtRecords = zone0.GetDnsTxtRecords();

DnsTxtRecordData newTxtRecordValues = new DnsTxtRecordData()
{
    TtlInSeconds = 300,
    DnsTxtRecords = 
    {
        new DnsTxtRecordInfo()
        {
            Values = 
            {
                "foo",
                "bar"
            }
        }
    }
};

ArmOperation<DnsTxtRecordResource> newResourceOp = await txtRecords.CreateOrUpdateAsync( WaitUntil.Completed, txtRecordName: "baz", data: newTxtRecordValues );
DnsTxtRecordResource newResource = newResourceOp.Value;

newResource.Dump();

截图证明:

© www.soinside.com 2019 - 2024. All rights reserved.