목록으로

Programming Notes

# Azure Managed Redis 배포 자동화

때때로 Azure Managed Redis(AMR)를 배포할 때 특정 Azure 지역에 임시 용량 제한이 발생할 수 있습니다.
이런 경우 일반적인 권장 사항은 다른 Azure 지역, 다른 AMR SKU, 혹은 비피크 시간대(주말 등)로 재시도하는 것입니다.

다른 지역에서 용량 제한이 없는 경우 캐시를 바로 만들 수 있지만, 비즈니스 요구사항이나 회사 정책으로 다른 지역을 사용할 수 없는 경우에는 같은 지역에서 다른 시간대나 다음 날에 다시 시도하거나 다른 AMR SKU를 사용해야 할 수 있습니다.

이러한 상황을 돕기 위해 PowerShell 스크립트를 만들었습니다.

※ 이 스크립트가 도움이 되셨다면, 페이지 하단에 의견을 남겨 주세요.
감사합니다.


목차


개요

이 스크립트는 하나의 Azure Managed Redis를 여러 시간대에 걸쳐 재시도하면서 SKUs 리스트에 정의된 순서대로 생성을 시도합니다.

  • 시도 간 간격은 MinDelayMinutes와 MaxDelayMinutes 사이에서 무작위로 선택됩니다.
  • 캐시 생성에 실패하면 실패한 리소스를 삭제한 뒤 같은 이름으로 다시 시도합니다.
  • 용량 제한으로 인한 실패인 경우에만 재시도하고, 다른 오류가 발생하면 스크립트가 종료됩니다.

지원하는 구성 옵션:

  • Geo‑Replication(새 그룹 또는 기존 그룹)
  • High Availability(HA)(활성/비활성)
  • Eviction Policy
  • Clustering Policy
  • 최대 재시도 횟수와 재시도 간 최소·최대 대기 시간

필수 조건

  • PowerShell 7.6.5 이상
  • Az.Accounts 와 Az.Resources 모듈 (대부분 환경에 기본 설치)

실행 방법

스크립트는 세 가지 모드로 실행할 수 있습니다.

  1. 기본값 사용 – 스크립트 파일에 정의된 기본값을 그대로 사용

    ./AMR_AutomatedCreation.ps1
    
  2. 명령줄 매개변수 지정 – 필요한 매개변수를 직접 전달 (기본값을 덮어씀)

    ./AMR_AutomatedCreation.ps1 -CacheName "MyAMRCache" -HighAvailability "Enabled"
    
  3. 대화형 입력 – 기본값도 없고 명령줄 매개변수도 제공되지 않으면, 실행 시 사용자에게 차례대로 입력을 요청합니다.

우선 순위 : 기본값 → 명령줄 매개변수 → 대화형 입력


스크립트 매개변수

각 매개변수는 기본값, 명령줄, 대화형 순으로 적용됩니다.
스크립트는 모든 값을 검증하며, 필요 시 추가로 대화형 입력을 요청합니다.

매개변수 설명
CacheName 생성할 캐시 이름
Location 배포할 Azure 지역 (소문자 자동 변환)
ResourceGroup 캐시를 배포할 기존 리소스 그룹
Skus 사용할 AMR SKU 목록 (쉼표 구분). 순서대로 시도하며, 리스트가 끝나면 처음부터 반복
HighAvailability "Enabled" 또는 "Disabled"
ClusteringPolicy "OSSCluster", "EnterpriseCluster", "NoCluster"
EvictionPolicy "NoEviction", "AllKeysLRU", "AllKeysLFU", "AllKeysRandom", "VolatileLRU", "VolatileLFU", "VolatileRandom", "VolatileTTL"
GeoReplicationEnabled $true / $false
GeoReplicationGroupNickname Geo‑Replication 그룹 이름 (활성화 시 필수). 새 그룹이든 기존 그룹이든 사용
ExistingLinkedCacheNames 기존 그룹에 포함된 캐시 이름(쉼표 구분)
ExistingLinkedResourceGroupNames 위 캐시들이 속한 리소스 그룹(쉼표 구분)
MaxRetries 최대 재시도 횟수 (1 이상)
MinDelayMinutes 재시도 간 최소 대기 시간 (15 ~ 1440분)
MaxDelayMinutes 재시도 간 최대 대기 시간 (MinDelayMinutes 이상)

주의

  • 매개변수 값에 포함된 공백은 자동 제거됩니다.
  • ResourceGroup은 사전에 생성돼 있어야 합니다. (실수로 비용이 많이 드는 리소스를 무작위 RG에 만들지 않기 위함)
  • CacheName, ResourceGroup, GeoReplicationGroupNickname은 입력한 대소문자를 유지하지만 형식 검증을 수행합니다.

예시

1. 기본값만 사용

./AMR_AutomatedCreation.ps1

2. 캐시 이름과 지역만 지정

./AMR_AutomatedCreation.ps1 -CacheName "MyAMRCache" -Location "centralus"

3. 상세 옵션 지정 (HA 비활성, OSSCluster, AllKeysLRU, Geo‑Replication 비활성, 15회 시도, Balanced_B0 ↔ MemoryOptimized_M10 교대로 시도)

./AMR_AutomatedCreation.ps1 `
  -CacheName "MyAMRCache" `
  -Location "centralus" `
  -ResourceGroup "MyResourceGroup" `
  -Skus "Balanced_B0,MemoryOptimized_M10" `
  -HighAvailability "Disabled" `
  -ClusteringPolicy "OSSCluster" `
  -EvictionPolicy "AllKeysLRU" `
  -GeoReplicationEnabled $false `
  -MaxRetries 15

4. HA 활성화 + 새 Geo‑Replication 그룹 생성

./AMR_AutomatedCreation.ps1 `
  -CacheName "MyAMRCache" `
  -Location "centralus" `
  -ResourceGroup "MyResourceGroup" `
  -Skus "Balanced_B0,MemoryOptimized_M10" `
  -HighAvailability "Enabled" `
  -ClusteringPolicy "OSSCluster" `
  -EvictionPolicy "AllKeysLRU" `
  -GeoReplicationEnabled $true `
  -MaxRetries 15 `
  -GeoReplicationGroupNickname "MyGeoGroup"

5. 기존 Geo‑Replication 그룹에 캐시 추가 (Balanced_B5 사용, 기존 그룹에 MyCache1, MyCache2가 이미 존재)

./AMR_AutomatedCreation.ps1 `
  -CacheName "MyAMRCache" `
  -Location "centralus" `
  -ResourceGroup "MyResourceGroup" `
  -Skus "Balanced_B5" `
  -HighAvailability "Enabled" `
  -ClusteringPolicy "OSSCluster" `
  -EvictionPolicy "AllKeysLRU" `
  -GeoReplicationEnabled $true `
  -MaxRetries 15 `
  -GeoReplicationGroupNickname "MyGeoGroup" `
  -ExistingLinkedCacheNames "MyCache1,MyCache2" `
  -ExistingLinkedResourceGroupNames "ResourcegroupCache1,ResourcegroupCache2"

인증

Azure에 Owner, Contributor, 혹은 Azure Managed Redis Contributor 역할이 부여된 계정이 필요합니다.

  • 이미 인증된 경우 : 스크립트가 현재 Azure 컨텍스트를 그대로 사용합니다.

    Connect-AzAccount   # 한 번만 실행
    ./AMR_AutomatedCreation.ps1
    
  • 인증되지 않은 경우 : 스크립트 실행 시 대화형 로그온이 요구됩니다.

Tip : 장시간 실행(몇 시간·몇 일)하려면 VM에 스크립트를 띄워두세요.
MSAL 기반 토큰은 자동으로 리프레시되므로, 최초 인증 후 별도 재인증이 필요 없습니다.

※ Managed Identity를 활용한 자동화도 가능합니다(스크립트에 직접 구현되지 않았음).


로그 기록

스크립트는 화면 출력과 동시에 동일한 내용을 파일에 저장합니다.

  • 파일명 : AMR-YYYYMMDD-HHmmss.log (스크립트와 같은 폴더)

로그 예시

**********************
PowerShell transcript start
Start time: 20260818182212
...
2026-08-18 18:22:31 - Cache: AMRCache1-B0
2026-08-18 18:22:31 - Resource Group: resource-group1 (existent)
2026-08-18 18:22:31 - Region: francecentral
2026-08-18 18:22:31 - SKU: Balanced_B0
...
2026-08-18 18:22:32 - Deployment succeeded using SKU Balanced_B0.
**********************
PowerShell transcript end
End time: 20260818182232
**********************

지원

이 스크립트는 Microsoft 지원 범위 외이며, Microsoft 혹은 저자는 지원 서비스를 제공하지 않습니다.
오류나 예기치 않은 동작은 직접 디버깅하고 수정해야 합니다.


면책 조항

본 스크립트는 “있는 그대로” 제공되며

  • 정상 동작을 보장하지 않으며
  • 테스트 후 프로덕션 환경에 적용하시기 바랍니다.

가격주의 : AMR SKU는 비용이 크게 달라질 수 있습니다. 자세한 가격 정보는 아래 링크를 참고하세요.

🔗 Azure Managed Redis 가격 페이지


스크립트 전체

아래 내용을 AMR_AutomatedCreation.ps1 파일에 복사·붙여넣기 하세요.

# ============================================================================
# AMR_AutomatedCreation - v1.0
# ============================================================================
# Azure Managed Redis 자동 생성, 용량 제한 상황을 처리합니다.
# 동일 지역에서 용량 제한이 해소될 때까지 지정한 SKU 목록을 순차·무작위
# 시간 간격으로 재시도합니다. 용량 제한 오류인 경우에만 재시도하고,
# 그 외 오류는 즉시 스크립트를 종료합니다.
#
# 주요 기능
#   • Geo‑Replication (신규 또는 기존 그룹)
#   • HA (Enabled / Disabled)
#   • Eviction Policy
#   • Clustering Policy
#   • 최대 재시도 횟수, 최소/최대 지연 시간 지정
#
# ---------------------------------------------------------------------------
# 경고
# ---------------------------------------------------------------------------
# • 본 스크립트는 자체 책임하에 사용하십시오.
# • 비용이 많이 발생할 수 있는 SKU를 사용하기 전에 반드시 가격을 확인하십시오.
#   https://azure.microsoft.com/en-us/pricing/details/managed-redis/
# ---------------------------------------------------------------------------

# ============================================================================
# 매개변수 (기본값은 필요에 따라 수정)
# ============================================================================
param(
    [string]$CacheName = "CacheName",
    [string]$Location = "CacheRegion",
    [string]$ResourceGroup = "ResourceGroup",
    [string[]]$Skus = @(
        "Balanced_B0",
        "Balanced_B3",
        "Balanced_B5",
        "MemoryOptimized_M10",
        "ComputeOptimized_X3"
    ),
    [string]$HighAvailability = "Enabled",
    [string]$ClusteringPolicy = "OSSCluster",
    [string]$EvictionPolicy = "NoEviction",
    [bool]$GeoReplicationEnabled = $false,
    [string]$GeoReplicationGroupNickname = "",
    [string[]]$ExistingLinkedCacheNames = "",
    [string[]]$ExistingLinkedResourceGroupNames = ""
)

$MaxRetries = 15         # 기본값: 15 회
$MinDelayMinutes = 120   # 기본값: 120 분 (2시간)
$MaxDelayMinutes = 300   # 기본값: 300 분 (5시간)

# ---------------------------------------------------------------------------
# 삭제 대기 시간 설정 (변경 금지)
# ---------------------------------------------------------------------------
$DeletionTimeoutMinutes = 20
$DeletionCheckIntervalSeconds = 15

# ---------------------------------------------------------------------------
# 출력 옵션
# ---------------------------------------------------------------------------
$ProgressPreference = "SilentlyContinue"
$WarningPreference  = "SilentlyContinue"
$InformationPreference = "SilentlyContinue"
$ConfirmPreference = "None"

# ======================================================================
# 로그 기록 시작
# ======================================================================
Start-Transcript -Path ".\AMR-$((Get-Date).ToString('yyyyMMdd-HHmmss')).log"

# ======================================================================
# 용량 관련 오류 패턴
# ======================================================================
$CapacityErrorPatterns = @(
    "AllocationFailed","SkuNotAvailable","InsufficientCapacity",
    "insufficient capacity","not enough capacity","out of capacity",
    "capacity constraints","capacity constraint","capacity restriction",
    "capacity is currently unavailable"
)

function Write-ScriptMessage {
    param([string]$Message)
    $ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    Write-Host "$ts - $Message"
}

function ConvertTo-SearchableText {
    param([object]$InputObject)
    if (-not $InputObject) { return "" }
    if ($InputObject -is [string]) { return $InputObject }
    try {
        $InputObject | ConvertTo-Json -Depth 100 -Compress -ErrorAction Stop
    } catch {
        $InputObject | Out-String
    }
}

function Test-CapacityError {
    param([string]$ErrorText)
    if ([string]::IsNullOrWhiteSpace($ErrorText)) { return $false }
    foreach ($p in $CapacityErrorPatterns) {
        if ($ErrorText.IndexOf($p,[System.StringComparison]::OrdinalIgnoreCase) -ge 0) {
            return $true
        }
    }
    return $false
}

function Validate-RetryValues {
    param(
        [string]$ParameterName,
        [string]$Value,
        [int]$MinValue = 0,
        [int]$MaxValue = -1
    )
    do {
        if ([string]::IsNullOrWhiteSpace($Value)) { $Value = Read-Host $ParameterName }
        $parsed = 0
        $isValid = [int]::TryParse($Value,[ref]$parsed) -and $parsed -ge $MinValue -and ($MaxValue -eq -1 -or $parsed -le $MaxValue)
        if (-not $isValid) {
            if ($MaxValue -eq -1) {
                Write-Host "$ParameterName must be an integer >= $MinValue."
            } else {
                Write-Host "$ParameterName must be an integer between $MinValue and $MaxValue."
            }
            $Value = $null
        }
    } while (-not $isValid)
    return $parsed
}

function Validate-CacheName {
    param([string]$CacheName)
    while ([string]::IsNullOrWhiteSpace($CacheName)) {
        $CacheName = (Read-Host "Enter Cache name").Trim() -replace '\s',''
    }
    $CacheName = $CacheName.Trim() -replace '\s',''
    while ($CacheName -notmatch '^(?!.*--)[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]$') {
        throw "Invalid Cache Name '$CacheName'. Only letters, numbers, and single hyphens are allowed. The first and last character must be a letter or number."
    }
    $existing = Get-AzResource -ResourceType "Microsoft.Cache/redisEnterprise" -ResourceName $CacheName -ErrorAction SilentlyContinue
    if ($existing) {
        throw "Cache '$CacheName' already exists in resource group '$($existing.ResourceGroupName)' and '$($existing.Location)'."
    }
    return $CacheName
}

function Validate-Location {
    param([string]$Location)
    while ([string]::IsNullOrWhiteSpace($Location)) {
        $Location = (Read-Host "Enter Azure Location for the cache").Trim().ToLower() -replace '\s',''
    }
    $Location = $Location.Trim().ToLower() -replace '\s',''
    $locs = (Invoke-AzRestMethod -Path "/subscriptions/$((Get-AzContext).Subscription.Id)/providers/Microsoft.Cache/skus?api-version=2025-04-01" -Method GET).Content |
            ConvertFrom-Json
    $supported = $locs.value | Select-Object -ExpandProperty locations | Sort-Object -Unique
    while ($Location -notin $supported) {
        throw "Invalid Location '$Location' - Supported Locations are: $($supported -join ', ')"
    }
    return $Location
}

function Validate-ResourceGroup {
    param([string]$ResourceGroup)
    while ([string]::IsNullOrWhiteSpace($ResourceGroup)) {
        $ResourceGroup = (Read-Host "Enter Resource Group for the cache").Trim() -replace '\s',''
    }
    $ResourceGroup = $ResourceGroup.Trim() -replace '\s',''
    while ($ResourceGroup -notmatch '^[\p{L}\p{N}_()\-\.]*[\p{L}\p{N}_()\-]$') {
        throw "Invalid Resource Group Name '$ResourceGroup'."
    }
    try {
        $rgObj = Get-AzResourceGroup -Name $ResourceGroup -ErrorAction Stop
    } catch {
        throw "Resource group '$ResourceGroup' could not be found or accessed."
    }
    return $rgObj.ResourceGroupName
}

function Validate-Skus {
    param([string[]]$Skus)
    $Skus = $Skus.Trim() -replace '\s',''
    $Skus = @($Skus | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
    $result = Invoke-AzRestMethod -Path "/subscriptions/$((Get-AzContext).Subscription.Id)/providers/Microsoft.Cache/skus?api-version=2025-04-01" -Method GET
    $valid = ($result.Content | ConvertFrom-Json).value | Select-Object -ExpandProperty name | Sort-Object -Unique
    if (-not $Skus) {
        $Skus = Select-MultipleOptions -Prompt "Select one or more SKUs" -Options $valid
    }
    $invalid = $Skus | Where-Object { $_ -notin $valid }
    if ($invalid) {
        throw "Invalid SKU(s) provided: $($invalid -join ', ')"
    }
    $normalized = foreach ($sku in $Skus) {
        $matched = $valid | Where-Object { $_ -eq $sku } | Select-Object -First 1
        if (-not $matched) { throw "Invalid SKU '$sku'." }
        $matched
    }
    return $normalized
}

function Validate-HighAvailability {
    param([string]$HighAvailability)
    $opts = @("Enabled","Disabled")
    $HighAvailability = $opts | Where-Object { $_ -eq $HighAvailability } | Select-Object -First 1
    if (-not $HighAvailability) {
        $HighAvailability = Select-Option -Prompt "Select High Availability (HA)" -Options $opts
    }
    if ($HighAvailability -notin $opts) { throw "Invalid High Availability value '$HighAvailability'." }
    return $HighAvailability
}

function Validate-ClusteringPolicy {
    param([string]$ClusteringPolicy)
    $opts = @("OSSCluster","EnterpriseCluster","NoCluster")
    $ClusteringPolicy = $ClusteringPolicy.Trim() -replace '\s',''
    $ClusteringPolicy = $opts | Where-Object { $_ -eq $ClusteringPolicy } | Select-Object -First 1
    if (-not $ClusteringPolicy) {
        $ClusteringPolicy = Select-Option -Prompt "Select Clustering Policy" -Options $opts
    }
    if ($ClusteringPolicy -notin $opts) { throw "Invalid Clustering Policy value '$ClusteringPolicy'." }
    return $ClusteringPolicy
}

function Validate-EvictionPolicy {
    param([string]$EvictionPolicy)
    $opts = @("NoEviction","AllKeysLRU","AllKeysLFU","AllKeysRandom","VolatileLRU","VolatileLFU","VolatileRandom","VolatileTTL")
    $EvictionPolicy = $EvictionPolicy.Trim() -replace '\s',''
    $EvictionPolicy = $opts | Where-Object { $_ -eq $EvictionPolicy } | Select-Object -First 1
    if (-not $EvictionPolicy) {
        $EvictionPolicy = Select-Option -Prompt "Select Eviction Policy" -Options $opts
    }
    if ($EvictionPolicy -notin $opts) { throw "Invalid Eviction Policy value '$EvictionPolicy'." }
    return $EvictionPolicy
}

function Validate-GeoReplication {
    param(
        [string]$HighAvailability,
        [bool]$GeoReplicationEnabled,
        [string]$GeoReplicationGroupNickname,
        [string[]]$ExistentLinkedCacheNames,
        [string[]]$ExistentLinkedResourceGroupNames
    )
    if ($HighAvailability -eq "Disabled") {
        Write-ScriptMessage "Geo‑Replication은 HA가 비활성화된 경우 사용할 수 없습니다."
        return @{ GeoReplicationEnabled=$false; GeoReplicationGroupNickname=""; ExistingLinkedDatabaseIds=@() }
    }

    $cfg = Get-GeoReplicationConfiguration `
        -GeoReplicationEnabled $GeoReplicationEnabled `
        -GeoReplicationGroupNickname $GeoReplicationGroupNickname `
        -ExistentLinkedCacheNames $ExistentLinkedCacheNames `
        -ExistentLinkedResourceGroupNames $ExistentLinkedResourceGroupNames

    $msg = if ($cfg.ExistingLinkedDatabaseIds) { "(Existing Group)" } else { "(New Group)" }
    Write-ScriptMessage "Geo‑Replication 선택:"
    Write-ScriptMessage "  Enabled: $($cfg.GeoReplicationEnabled)"
    Write-ScriptMessage "  Group Name: $($cfg.GeoReplicationGroupNickname) $msg"
    if ($cfg.ExistingLinkedDatabaseIds) {
        Write-ScriptMessage "  Linked DB IDs:"
        $cfg.ExistingLinkedDatabaseIds | ForEach-Object { Write-Host "    $_" }
    }

    if ($cfg.GeoReplicationEnabled -and ($Skus -contains "Balanced_B0" -or $Skus -contains "Balanced_B1")) {
        Write-Host "  WARNING: Balanced_B0/B1은 Geo‑Replication을 지원하지 않으며, 해당 SKU가 성공하면 Geo‑Replication 없이 생성됩니다."
    }
    if ($cfg.GeoReplicationEnabled -and $HighAvailability -eq "Disabled") {
        Write-Host "  WARNING: HA가 비활성화된 경우 Geo‑Replication을 사용할 수 없습니다."
    }

    return $cfg
}

function Get-GeoReplicationConfiguration {
    param(
        [bool]$GeoReplicationEnabled,
        [string]$GeoReplicationGroupNickname,
        [string[]]$ExistentLinkedCacheNames,
        [string[]]$ExistentLinkedResourceGroupNames
    )
    if (-not $GeoReplicationEnabled) {
        return @{ GeoReplicationEnabled=$false; GeoReplicationGroupNickname=""; ExistingLinkedDatabaseIds=@() }
    }

    $isNewGroup = $false
    if ([string]::IsNullOrWhiteSpace($ExistentLinkedCacheNames) -and [string]::IsNullOrWhiteSpace($ExistentLinkedResourceGroupNames)) {
        $isNewGroup = $true
    }

    if ([string]::IsNullOrWhiteSpace($GeoReplicationGroupNickname)) {
        $GeoReplicationGroupNickname = Read-Host "Geo‑Replication Group name"
        while (-not (Verify-GeoGroupName $GeoReplicationGroupNickname)) {
            Write-Host "Invalid Geo‑Replication Group name. Try again."
            $GeoReplicationGroupNickname = Read-Host "Geo‑Replication Group name"
        }
    }

    if ($GeoReplicationEnabled -and $isNewGroup) {
        return @{ GeoReplicationEnabled=$true; GeoReplicationGroupNickname=$GeoReplicationGroupNickname; ExistingLinkedDatabaseIds=@() }
    }

    while ([string]::IsNullOrWhiteSpace($ExistentLinkedCacheNames) -or
           [string]::IsNullOrWhiteSpace($ExistentLinkedResourceGroupNames) -or
           (CountElementsFromList $ExistentLinkedCacheNames) -ne (CountElementsFromList $ExistentLinkedResourceGroupNames)) {
        if ([string]::IsNullOrWhiteSpace($ExistentLinkedCacheNames)) {
            $ExistentLinkedCacheNames = Request-ListOfNames -Prompt "Cache Names"
        }
        if ([string]::IsNullOrWhiteSpace($ExistentLinkedResourceGroupNames)) {
            $ExistentLinkedResourceGroupNames = Request-ListOfNames -Prompt "Resource Groups"
        }
        if ((CountElementsFromList $ExistentLinkedCacheNames) -ne (CountElementsFromList $ExistentLinkedResourceGroupNames)) {
            Write-Host "Cache Names와 Resource Groups 리스트는 동일한 개수여야 합니다."
            $ExistentLinkedCacheNames = Request-ListOfNames -Prompt "Cache Names"
            $ExistentLinkedResourceGroupNames = Request-ListOfNames -Prompt "Resource Groups"
        }
    }

    $ids = @()
    $cacheArr = $ExistentLinkedCacheNames -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ }
    $rgArr    = $ExistentLinkedResourceGroupNames -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ }

    for ($i = 0; $i -lt $cacheArr.Count; $i++) {
        $ids += "/subscriptions/$((Get-AzContext).Subscription.Id)/resourceGroups/$($rgArr[$i])/providers/Microsoft.Cache/redisEnterprise/$($cacheArr[$i])/databases/default"
    }

    return @{ GeoReplicationEnabled=$true; GeoReplicationGroupNickname=$GeoReplicationGroupNickname; ExistingLinkedDatabaseIds=$ids }
}

function CountElementsFromList {
    param([string[]]$List)
    if ([string]::IsNullOrWhiteSpace($List)) { return 0 }
    return @($List -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ }).Count
}

function Request-ListOfNames {
    param([string]$Prompt)
    $list = Read-Host "List of $Prompt (comma separated)"
    while ([string]::IsNullOrWhiteSpace($list)) {
        Write-Host "Invalid or empty list. Try again."
        $list = Read-Host "List of $Prompt (comma separated)"
    }
    return $list
}

function Verify-GeoGroupName {
    param([string]$Name)
    if ([string]::IsNullOrWhiteSpace($Name)) { return $false }
    return $Name -match '^(?!.*--)[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]$'
}

function Get-DeploymentOperationError {
    param([string]$DeploymentName, [string]$ResourceGroupName)
    $res = [ordered]@{
        DeploymentFound=$false; OperationsFound=$false; CapacityDetected=$false;
        FailedOperations=@(); ErrorText=""
    }
    try {
        $dep = Get-AzResourceGroupDeployment -ResourceGroupName $ResourceGroupName -Name $DeploymentName -ErrorAction Stop
        if (-not $dep) { $res.ErrorText="Deployment record not found."; return [pscustomobject]$res }
        $res.DeploymentFound=$true
        if (Test-CapacityError (ConvertTo-SearchableText $dep)) { $res.CapacityDetected=$true }
    } catch {
        $res.ErrorText = "Failed to retrieve deployment record.`n$($_ | Out-String)"
        return [pscustomobject]$res
    }

    try {
        $ops = Get-AzResourceGroupDeploymentOperation -ResourceGroupName $ResourceGroupName -DeploymentName $DeploymentName -ErrorAction Stop
        if ($ops.Count -eq 0) { $res.ErrorText="No deployment operations returned."; return [pscustomobject]$res }
        $res.OperationsFound=$true
        foreach ($op in $ops) {
            $txt = ConvertTo-SearchableText $op
            if (Test-CapacityError $txt) { $res.CapacityDetected=$true }
            $state = $op.ProvisioningState
            if (-not $state -and $op.Properties) { $state = $op.Properties.ProvisioningState }
            if ($state -in @("Failed","Canceled","Cancelled")) { $res.FailedOperations += $op }
        }
        if ($res.FailedOperations.Count -gt 0) {
            $res.ErrorText = ($res.FailedOperations | ForEach-Object { ConvertTo-SearchableText $_ }) -join "`n"
        } else {
            $res.ErrorText = ($ops | ForEach-Object { ConvertTo-SearchableText $_ }) -join "`n"
        }
    } catch {
        $res.ErrorText = "Failed to retrieve deployment operations.`n$($_ | Out-String)"
    }
    return [pscustomobject]$res
}

function Remove-FailedAmrResource {
    param([string]$Name, [string]$ResourceGroupName, [int]$TimeoutMinutes, [int]$CheckIntervalSeconds)
    try {
        $res = Get-AzResource -ResourceGroupName $ResourceGroupName -ResourceType "Microsoft.Cache/redisEnterprise" -ResourceName $Name -ErrorAction SilentlyContinue
        if (-not $res) { Write-ScriptMessage "No failed AMR resource found."; return $true }

        Write-ScriptMessage "Removing failed AMR resource '$Name'..."
        Remove-AzResource -ResourceGroupName $ResourceGroupName -ResourceType "Microsoft.Cache/redisEnterprise" -ResourceName $Name -Force -ErrorAction Stop | Out-Null
        Write-ScriptMessage "Delete request accepted."

        $deadline = (Get-Date).AddMinutes($TimeoutMinutes)
        while ((Get-Date) -lt $deadline) {
            $res = Get-AzResource -ResourceGroupName $ResourceGroupName -ResourceType "Microsoft.Cache/redisEnterprise" -ResourceName $Name -ErrorAction SilentlyContinue
            if (-not $res) {
                Write-ScriptMessage "Failed AMR resource completely removed."
                return $true
            }
            Write-ScriptMessage "Resource deletion still in progress."
            Start-Sleep -Seconds $CheckIntervalSeconds
        }
        Write-ScriptMessage "Timed out waiting for resource deletion."
        return $false
    } catch {
        Write-ScriptMessage "Cleanup threw an exception."
        Write-Host $_ | Out-String
        $still = Get-AzResource -ResourceGroupName $ResourceGroupName -ResourceType "Microsoft.Cache/redisEnterprise" -ResourceName $Name -ErrorAction SilentlyContinue
        return (-not $still)
    }
}

function Select-Option {
    param([string]$Prompt, [string[]]$Options, [int]$DefaultOption=1)
    Write-Host "`n$Prompt"
    for ($i=0;$i -lt $Options.Count;$i++) {
        $def = if (($i+1) -eq $DefaultOption) { " (default)" } else { "" }
        Write-Host "$($i+1). $($Options[$i])$def"
    }
    do {
        $sel = Read-Host "Select an option ($($Options[$DefaultOption-1]))"
        if ([string]::IsNullOrWhiteSpace($sel)) { $sel = $DefaultOption }
        try {
            $sel = [int]$sel
            if ($sel -lt 1 -or $sel -gt $Options.Count) { throw }
            return $Options[$sel-1]
        } catch {
            Write-Host "Invalid selection. Try again." -ForegroundColor Red
        }
    } while ($true)
}

function Select-MultipleOptions {
    param([string]$Prompt, [string[]]$Options, [int]$DefaultOption=1)
    Write-Host "`n$Prompt"
    for ($i=0;$i -lt $Options.Count;$i++) {
        $def = if (($i+1) -eq $DefaultOption) { " (default)" } else { "" }
        Write-Host "$($i+1). $($Options[$i])$def"
    }
    do {
        $sel = Read-Host "Enter option numbers separated by commas (e.g. 1,3,5)"
        if ([string]::IsNullOrWhiteSpace($sel)) { $sel = $DefaultOption }
        try {
            $indexes = $sel -split ',' | ForEach-Object { [int]($_.Trim()) - 1 }
            if ($indexes | Where-Object { $_ -lt 0 -or $_ -ge $Options.Count }) { throw }
            return $indexes | ForEach-Object { $Options[$_] }
        } catch {
            Write-Host "Invalid selection. Try again." -ForegroundColor Red
        }
    } while ($true)
}

# ======================================================================
# ARM 템플릿 (JSON)
# ======================================================================
$ArmTemplate = @'
{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "redisName": { "type": "string" },
    "location": { "type": "string" },
    "highAvailability": { "type": "string" },
    "clusteringPolicy": { "type": "string" },
    "evictionPolicy": { "type": "string" },
    "skuName": { "type": "string" },
    "geoReplicationEnabled": { "type": "bool" },
    "geoReplicationGroupNickname": { "type": "string", "defaultValue": "" },
    "existingLinkedDatabaseIds": { "type": "array", "defaultValue": [] }
  },
  "variables": {
    "currentDatabaseId": "[resourceId('Microsoft.Cache/redisEnterprise/databases', parameters('redisName'), 'default')]",
    "allLinkedDatabaseIds": "[union(parameters('existingLinkedDatabaseIds'), createArray(variables('currentDatabaseId')))]",
    "linkedDatabases": "[map(variables('allLinkedDatabaseIds'), lambda('databaseId', createObject('id', lambdaVariables('databaseId'))))]"
  },
  "resources": [
    {
      "type": "Microsoft.Cache/redisEnterprise",
      "apiVersion": "2025-04-01",
      "name": "[parameters('redisName')]",
      "location": "[parameters('location')]",
      "sku": { "name": "[parameters('skuName')]" },
      "properties": {
        "highAvailability": "[parameters('highAvailability')]",
        "minimumTlsVersion": "1.2",
        "clusteringPolicy": "[parameters('clusteringPolicy')]"
      }
    },
    {
      "condition": "[or(not(parameters('geoReplicationEnabled')), equals(parameters('skuName'), 'Balanced_B0'), equals(parameters('skuName'), 'Balanced_B1'))]",
      "type": "Microsoft.Cache/redisEnterprise/databases",
      "apiVersion": "2025-04-01",
      "name": "[concat(parameters('redisName'), '/default')]",
      "dependsOn": [ "[resourceId('Microsoft.Cache/redisEnterprise', parameters('redisName'))]" ],
      "properties": {
        "clientProtocol": "Encrypted",
        "clusteringPolicy": "[parameters('clusteringPolicy')]",
        "evictionPolicy": "[parameters('evictionPolicy')]",
        "port": 10000
      }
    },
    {
      "condition": "[and(parameters('geoReplicationEnabled'), not(or(equals(parameters('skuName'), 'Balanced_B0'), equals(parameters('skuName'), 'Balanced_B1'))))]",
      "type": "Microsoft.Cache/redisEnterprise/databases",
      "apiVersion": "2025-04-01",
      "name": "[concat(parameters('redisName'), '/default')]",
      "dependsOn": [ "[resourceId('Microsoft.Cache/redisEnterprise', parameters('redisName'))]" ],
      "properties": {
        "clientProtocol": "Encrypted",
        "clusteringPolicy": "[parameters('clusteringPolicy')]",
        "evictionPolicy": "[parameters('evictionPolicy')]",
        "port": 10000,
        "geoReplication": {
          "groupNickname": "[parameters('geoReplicationGroupNickname')]",
          "linkedDatabases": "[variables('linkedDatabases')]"
        }
      }
    }
  ]
}
'@

# ======================================================================
# 배포 시작
# ======================================================================
try {
    # ---------- ARM 템플릿 JSON 검증 ----------
    try {
        $ArmTemplateObject = $ArmTemplate | ConvertFrom-Json -AsHashtable -ErrorAction Stop
    } catch {
        Write-ScriptMessage "ARM 템플릿이 유효한 JSON이 아닙니다."
        Write-Host $_
        exit 1
    }

    # ---------- Azure 연결 ----------
    Write-ScriptMessage "Connecting to Azure."
    $ctx = Get-AzContext
    if ($ctx) {
        Write-ScriptMessage "AzContext 발견 – 인터랙티브 인증 불필요."
    } else {
        Connect-AzAccount -ErrorAction Stop | Out-Null
        $ctx = Get-AzContext -ErrorAction Stop
    }
    if (-not $ctx.Subscription) { throw "활성 Azure 구독이 없습니다." }
    $subId = $ctx.Subscription.Id
    Set-AzContext -SubscriptionId $subId -ErrorAction Stop | Out-Null
    Write-ScriptMessage "Using subscription $subId."

    # ---------- 매개변수 검증 ----------
    $MaxRetries      = Validate-RetryValues -ParameterName "MaxRetries"      -Value $MaxRetries -MinValue 1
    $MinDelayMinutes = Validate-RetryValues -ParameterName "Minimum Delay (min)" -Value $MinDelayMinutes -MinValue 15  -MaxValue 1440
    $MaxDelayMinutes = Validate-RetryValues -ParameterName "Maximum Delay (min)" -Value $MaxDelayMinutes -MinValue $MinDelayMinutes

    Write-ScriptMessage "Using $MaxRetries attempts; delay between $MinDelayMinutes and $MaxDelayMinutes minutes."

    $CacheName = Validate-CacheName $CacheName
    $Location = Validate-Location $Location
    $ResourceGroup = Validate-ResourceGroup $ResourceGroup
    $Skus = Validate-Skus $Skus
    $HighAvailability = Validate-HighAvailability $HighAvailability
    $ClusteringPolicy = Validate-ClusteringPolicy $ClusteringPolicy
    $EvictionPolicy = Validate-EvictionPolicy $EvictionPolicy
    $GeoCfg = Validate-GeoReplication `
                -HighAvailability $HighAvailability `
                -GeoReplicationEnabled $GeoReplicationEnabled `
                -GeoReplicationGroupNickname $GeoReplicationGroupNickname `
                -ExistentLinkedCacheNames $ExistingLinkedCacheNames `
                -ExistentLinkedResourceGroupNames $ExistingLinkedResourceGroupNames
    $GeoReplicationEnabled = $GeoCfg.GeoReplicationEnabled
    $GeoReplicationGroupNickname = $GeoCfg.GeoReplicationGroupNickname
    $ExistingLinkedDatabaseIds = $GeoCfg.ExistingLinkedDatabaseIds

    # ---------- 배포 재시도 루프 ----------
    for ($attempt=1; $attempt -le $MaxRetries; $attempt++) {
        $skuIdx = ($attempt-1) % $Skus.Count
        $sku = $Skus[$skuIdx]

        $deploymentName = "amr-{0}-{1:D2}-{2}" -f (Get-Date -Format "yyyyMMddHHmmss"), $attempt, ([guid]::NewGuid().ToString("N").Substring(0,8))

        Write-Host ""
        Write-ScriptMessage "==== Attempt $attempt of $MaxRetries ====================="
        Write-ScriptMessage "Cache: $CacheName"
        Write-ScriptMessage "Resource Group: $ResourceGroup (existent)"
        Write-ScriptMessage "Region: $Location"
        Write-ScriptMessage "SKU: $sku"
        Write-ScriptMessage "HA: $HighAvailability"
        Write-ScriptMessage "Clustering: $ClusteringPolicy"
        Write-ScriptMessage "Eviction: $EvictionPolicy"

        # Geo‑Replication은 HA 비활성 또는 지원되지 않는 SKU일 때 비활성화
        if ($HighAvailability -eq "Disabled" -or $sku -in @("Balanced_B0","Balanced_B1")) {
            $locGeoEnabled = $false
            $locGeoGroup   = ""
            $locGeoIds     = @()
        } else {
            $locGeoEnabled = $GeoReplicationEnabled
            $locGeoGroup   = $GeoReplicationGroupNickname
            $locGeoIds     = $ExistingLinkedDatabaseIds
        }
        Write-ScriptMessage "Geo‑Replication enabled: $locGeoEnabled"
        if ($locGeoEnabled) {
            $groupMsg = if ($locGeoIds) { "(existing Geo‑Group)" } else { "(new Geo‑Group)" }
            Write-ScriptMessage "Geo‑Replication Group: $locGeoGroup $groupMsg"
        }

        Write-ScriptMessage "Deployment name: $deploymentName"
        try {
            Write-ScriptMessage "Starting ARM deployment..."
            $dep = New-AzResourceGroupDeployment `
                -Name $deploymentName `
                -ResourceGroupName $ResourceGroup `
                -TemplateObject $ArmTemplateObject `
                -redisName $CacheName `
                -location $Location `
                -skuName $sku `
                -highAvailability $HighAvailability `
                -clusteringPolicy $ClusteringPolicy `
                -evictionPolicy $EvictionPolicy `
                -geoReplicationEnabled $locGeoEnabled `
                -geoReplicationGroupNickname $locGeoGroup `
                -existingLinkedDatabaseIds $locGeoIds `
                -Mode Incremental -DeploymentDebugLogLevel All -ErrorAction Stop `
                -Confirm:$false

            $depStatus = Get-AzResourceGroupDeployment -ResourceGroupName $ResourceGroup -Name $deploymentName -ErrorAction Stop
            if ($depStatus.ProvisioningState -eq "Succeeded") {
                Write-ScriptMessage "Deployment succeeded using SKU $sku."
                exit 0
            }
            throw "Deployment completed with unexpected state '$($depStatus.ProvisioningState)'."
        } catch {
            $origErr = $_ | Out-String
            Write-ScriptMessage "Deployment attempt failed."
            Write-Host $origErr

            $opRes = Get-DeploymentOperationError -DeploymentName $deploymentName -ResourceGroupName $ResourceGroup
            if ($opRes.DeploymentFound) { Write-ScriptMessage "ARM deployment record found." } else { Write-ScriptMessage "ARM deployment record NOT found." }
            if ($opRes.OperationsFound) { Write-ScriptMessage "Deployment operations retrieved." } else { Write-ScriptMessage "No operation details available." }

            $capErr = Test-CapacityError -ErrorText $origErr
            $capacityDetected = $capErr -or $opRes.CapacityDetected

            if ($capacityDetected) {
                Write-ScriptMessage "Capacity‑related error detected."
                $clean = Remove-FailedAmrResource -Name $CacheName -ResourceGroupName $ResourceGroup `
                         -TimeoutMinutes $DeletionTimeoutMinutes -CheckIntervalSeconds $DeletionCheckIntervalSeconds
                if (-not $clean) {
                    Write-ScriptMessage "Failed resource could not be confirmed deleted. Stopping."
                    exit 1
                }
                if ($attempt -ge $MaxRetries) {
                    Write-Host ""
                    Write-ScriptMessage "Maximum retry count reached."
                    if ($opRes.ErrorText) {
                        Write-ScriptMessage "Last ARM error details:"
                        Write-Host $opRes.ErrorText
                    }
                    exit 1
                }
                $delay = Get-Random -Minimum $MinDelayMinutes -Maximum ($MaxDelayMinutes+1)
                Write-ScriptMessage "Retrying in $delay minutes."
                Start-Sleep -Seconds ($delay*60)
                continue
            }

            # 비용량 오류 – 즉시 종료
            Write-ScriptMessage "Error is NOT a capacity issue. Stopping."
            if ($opRes.ErrorText) {
                Write-ScriptMessage "ARM error details:"
                Write-Host $opRes.ErrorText
            } else {
                Write-ScriptMessage "PowerShell error details:"
                Write-Host $origErr
            }
            exit 1
        }
    }

    Write-Host ""
    Write-ScriptMessage "Maximum retry count reached without success."
    exit 1
}
finally {
    Stop-Transcript
}