Cleanup AD principal resources (#5481)

This commit is contained in:
Aleksandr Chebotov
2022-05-10 10:26:57 +02:00
committed by GitHub
parent 3caf4a3e5c
commit f2c7e4b929

View File

@@ -132,6 +132,7 @@ Function GenerateResourcesAndImage {
[bool] $EnableHttpsTrafficOnly = $False
)
try {
$builderScriptPath = Get-PackerTemplatePath -RepositoryRoot $ImageGenerationRepositoryRoot -ImageType $ImageType
$ServicePrincipalClientSecret = $env:UserName + [System.GUID]::NewGuid().ToString().ToUpper()
$InstallPassword = $env:UserName + [System.GUID]::NewGuid().ToString().ToUpper()
@@ -245,7 +246,9 @@ Function GenerateResourcesAndImage {
Start-Sleep -Seconds $SecondsToWaitForServicePrincipalSetup
$sub = Get-AzSubscription -SubscriptionId $SubscriptionId
$tenantId = $sub.TenantId
# "", "Note this variable-setting script for running Packer with these Azure resources in the future:", "==============================================================================================", "`$spClientId = `"$spClientId`"", "`$ServicePrincipalClientSecret = `"$ServicePrincipalClientSecret`"", "`$SubscriptionId = `"$SubscriptionId`"", "`$tenantId = `"$tenantId`"", "`$spObjectId = `"$spObjectId`"", "`$AzureLocation = `"$AzureLocation`"", "`$ResourceGroupName = `"$ResourceGroupName`"", "`$storageAccountName = `"$storageAccountName`"", "`$install_password = `"$install_password`"", ""
# Remove ADPrincipal after the script completed
$isCleanupADPrincipal = $true
} else {
# Parametrized Authentication via given service principal: The service principal with the data provided via the command line
# is used for all authentication purposes.
@@ -278,4 +281,23 @@ Function GenerateResourcesAndImage {
-var "install_password=$($InstallPassword)" `
-var "allowed_inbound_ip_addresses=$($AgentIp)" `
$builderScriptPath
}
catch {
Write-Error $_
}
finally {
# Remove ADServicePrincipal and ADApplication
if ($isCleanupADPrincipal) {
Write-Host "`nRemoving ${spDisplayName}/${spClientId}:"
if (Get-AzADServicePrincipal -DisplayName $spDisplayName) {
Write-Host " [+] ADServicePrincipal"
Remove-AzADServicePrincipal -DisplayName $spDisplayName -Confirm:$false
}
if (Get-AzADApplication -DisplayName $spDisplayName) {
Write-Host " [+] ADApplication"
Remove-AzADApplication -DisplayName $spDisplayName -Confirm:$false
}
}
}
}