2022-02-23

在 Microsoft DNS Server 上用 DNS Record 來驗證 Let's Encrypt 的 PowerShell Script

在 DNS Server 上透過 PowerShell Script 自動建立/刪除驗證用 Record 的方式來取得 Let's Encrypt 憑證


Updated: 2023.06.09 更新如果不是 A Record 而是 CNAME 時的處理
Updated: 2023.08.23 更新 Create Record 前先檢查,如果 Record 存在就刪除再建立

採用工具: 
https://www.win-acme.com/


DNSVerification.ps1

# -Step "create" -Identifier "{Identifier}" -RecordName "{RecordName}" -Token "{Token}"
# -Step "delete" -Identifier "{Identifier}" -RecordName "{RecordName}" -Token "{Token}"

param (
[string]$Step,
[string]$Identifier,
[string]$RecordName,
[string]$Token
);

if ( ($Step.ToLower() -ne 'create') -and ($Step.ToLower() -ne 'delete') ) {
write-host "No Correct Step.";
exit;
};

foreach ($Zone in (Get-DnsServerZone | where {$_.ZoneType -eq 'Primary'}).ZoneName) {
if ($Identifier -like ('*' + $Zone)) {
$Domain = $Zone;
$Record = $Identifier -Replace ('.' + $Zone),'';
$VerificationRecord = $RecordName -Replace ('.' + $Zone),'';
if (((Get-DnsServerResourceRecord -ZoneName $Domain -Nameacs $Record).RecordType) -eq 'A') {

if (((Get-DnsServerResourceRecord -ZoneName $Domain -Name $Record).RecordType) -eq 'A') {

$RecordIP = (Get-DnsServerResourceRecord -ZoneName $Domain -Name $Record).RecordData.IPv4Address.IPAddressToString

} elseif (((Get-DnsServerResourceRecord -ZoneName $Domain -Name $Record).RecordType) -eq 'CNAME') {

$RecordIP = ((Get-DnsServerResourceRecord -ZoneName $Domain -Name ([String](((Get-DnsServerResourceRecord -ZoneName $Domain -Name $Record).RecordData.HostNameAlias) -Replace ('.' + $Zone + '.'),'') -Replace ' ','')).RecordData.IPv4Address)[0].IPAddressToString;

};
break;
};
};

if ($Domain -eq $Null) {
write-host "No Correct Zone Found.";
exit;
};

if ($RecordIP -eq $Null) {
write-host "No Correct A Record Found.";
exit;
};

if ($Step.ToLower() -eq 'create') {
if ((Get-DnsServerResourceRecord -ZoneName "contoso.com" | where {$_.HostName -eq '_acme-challenge'}) -ne $Null) {
Remove-DnsServerResourceRecord -Name $VerificationRecord -ZoneName $Domain -RRType TXT -Force;
};
Add-DnsServerResourceRecord -DescriptiveText $Token -Name $VerificationRecord -TXT -ZoneName $Domain;
} else {
Remove-DnsServerResourceRecord -Name $VerificationRecord -ZoneName $Domain -RRType TXT -Force;
};


沒有留言:

張貼留言