Erstellen Sie eine benutzerdefinierte Domain mit Azure SDK mithilfe von ResourceManager (DNS und App -Dienst)
Posted: 03 Apr 2025, 10:14
Ich möchte die Erstellung benutzerdefinierter Domänen automatisieren. So erstellen Sie das Hostnamebinding. Welche Werte brauche ich wirklich und wie kann ich sie von Azure (Domainid, Thumbprintstring) bekommen?
Es funktioniert jetzt. Dies ist meine Lösung.
Code: Select all
public class AzureService : IAzureService
{
private readonly ArmClient _client;
private readonly SubscriptionResource _subscription;
private readonly ResourceGroupResource _resourceGroup;
public AzureService(string resourceGroupName)
{
_client = new ArmClient(new DefaultAzureCredential());
_subscription = _client.GetDefaultSubscription();
_resourceGroup = _subscription.GetResourceGroup(resourceGroupName);
}
public async Task AddSubdomainAsync(string appServiceName, string subdomain)
{
var appService = await GetAppServiceAsync(appServiceName);
var subdomainParts = subdomain.Split('.');
var subdomainName = string.Join('.', subdomainParts.Take(subdomainParts.Length - 2));
var txtRecordName = $"asuid.{subdomainName}";
var hostNameBindingData = new HostNameBindingData
{
SslState = HostNameBindingSslState.SniEnabled
};
var operation = await appService.GetSiteHostNameBindings().CreateOrUpdateAsync(WaitUntil.Completed, subdomain, hostNameBindingData);
// Add CNAME record
await AddCNameRecordAsync("pit-services.one", subdomainName, $"{appServiceName}.azurewebsites.net");
// Add TXT record for domain verification
await AddTxtRecordAsync("pit-services.one", txtRecordName, appService.Data.CustomDomainVerificationId);
}
public async Task AddCNameRecordAsync(string dnsZoneName, string recordSetName, string alias)
{
var dnsZone = await GetDnsZoneAsync(dnsZoneName);
var cnameRecordSetData = new DnsCnameRecordData
{
TtlInSeconds = 3600,
Cname = alias
};
var cnameRecordSet = await dnsZone.GetDnsCnameRecords().CreateOrUpdateAsync(WaitUntil.Completed, recordSetName, cnameRecordSetData);
}
public async Task AddTxtRecordAsync(string dnsZoneName, string recordSetName, string value)
{
var dnsZone = await GetDnsZoneAsync(dnsZoneName);
var txtRecordSetData = new DnsTxtRecordData
{
TtlInSeconds = 3600,
DnsTxtRecords = { new DnsTxtRecordInfo { Values = { value } } }
};
var txtRecordSet = await dnsZone.GetDnsTxtRecords().CreateOrUpdateAsync(WaitUntil.Completed, recordSetName, txtRecordSetData);
}
private async Task GetDnsZoneAsync(string dnsZoneName)
{
return await _resourceGroup.GetDnsZoneAsync(dnsZoneName);
}
public async Task GetAppServiceAsync(string appServiceName)
{
return await _resourceGroup.GetWebSiteAsync(appServiceName);
}
}