# Define your environment variables
$resourceGroupName = “MyUniqueResourceGroup”
$location = “EastUS”
$containerRegistryName = “myacrregistry” + [guid]::NewGuid().ToString().Substring(0,8)
$aksClusterName = “MyAKSCluster”
$nodeCount = 3
$kubernetesVersion = “1.25.0”
# Step 1: Create a Resource Group
Write-Host “Step 1: Creating Resource Group ‘$resourceGroupName’ in location ‘$location’…”
if (-not (Get-AzResourceGroup -Name $resourceGroupName -ErrorAction SilentlyContinue)) {
New-AzResourceGroup -Name $resourceGroupName -Location $location
} else {
Write-Host “Resource group ‘$resourceGroupName’ already exists.”
}
Start-Sleep -Seconds 5
# Function to check ACR name availability
function Check-AcrNameAvailability($name) {
$result = Test-AzContainerRegistryNameAvailability -Name $name
return $result.NameAvailable
}
# Ensure a unique ACR name
while (-not (Check-AcrNameAvailability -name $containerRegistryName)) {
Write-Host “The ACR name ‘$containerRegistryName’ is already in use.”
$containerRegistryName = “myacrregistry” + [guid]::NewGuid().ToString().Substring(0,8)
Write-Host “Trying a new ACR name: $containerRegistryName”
Start-Sleep -Seconds 5
}
Start-Sleep -Seconds 5
# Step 2: Create an Azure Container Registry (ACR)
Write-Host “Step 2: Creating Azure Container Registry ‘$containerRegistryName’…”
New-AzContainerRegistry -ResourceGroupName $resourceGroupName `
-RegistryName $containerRegistryName `
-Sku Basic `
-Location $location
Start-Sleep -Seconds 5
# Step 3: Retrieve the ACR Login Server URL
Write-Host “Step 3: Retrieving the ACR Login Server URL…”
Start-Sleep -Seconds 10 # Wait for ACR provisioning
$acr = Get-AzContainerRegistry -ResourceGroupName $resourceGroupName -RegistryName $containerRegistryName
$acrLoginServer = $acr.LoginServer
Start-Sleep -Seconds 5
# Step 4: Skip Service Principal creation (using Managed Identity instead)
# Step 5: Generate SSH Key for AKS Cluster if it doesn’t exist
$sshKeyPath = “$HOME\.ssh\id_rsa.pub”
if (-Not (Test-Path $sshKeyPath)) {
Write-Host “Step 5: SSH key not found. Generating a new SSH key…”
if (-Not (Get-Command ssh-keygen -ErrorAction SilentlyContinue)) {
Write-Host “Installing OpenSSH client…”
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
}
ssh-keygen -t rsa -b 4096 -f “$HOME\.ssh\id_rsa” -N “”
}
$sshPublicKey = Get-Content -Path $sshKeyPath -Raw
Start-Sleep -Seconds 5
# Step 6: Create the AKS Cluster using Managed Identity
Write-Host “Step 6: Creating AKS Cluster ‘$aksClusterName’ using Managed Identity…”
New-AzAksCluster -ResourceGroupName $resourceGroupName `
-Name $aksClusterName `
-NodeCount $nodeCount `
-KubernetesVersion $kubernetesVersion `
-SshKeyValue $sshPublicKey `
-Location $location
Start-Sleep -Seconds 5
# Step 7: Output the environment details
Write-Host “Environment setup complete!”
Write-Host “ACR Login Server: $acrLoginServer”
Write-Host “AKS Cluster Name: $aksClusterName”
Read-Host “Script execution complete. Press Enter to exit.”