source/Public/Set-RJKeyVault.ps1

function Set-RJKeyVault {
    <#
    .SYNOPSIS
    Deploys the RealmJoin LAPS Key Vault to Azure.
 
    .DESCRIPTION
    Deploys the Key Vault used by RealmJoin LAPS (local administrator password solution) with the
    Azure role-based access control permission model, and grants the RealmJoin Client service principal
    the Key Vault Certificates Officer, Key Vault Secrets Officer and Key Vault Crypto User roles on it.
 
    An existing Key Vault (-KeyVaultName) is not redeployed; only the missing roles are assigned.
    It must use the Azure role-based access control permission model.
 
    Uses bundled ARM templates (JSON).
 
    Prerequisites:
    - Az.Accounts and Az.Resources PowerShell modules
    - Resource group must already exist
    - The RealmJoin Client service principal must exist (add the 'Client' feature with Update-RJTenant)
 
    .PARAMETER ResourceGroupName
    The name of the resource group to deploy to (must exist).
 
    .PARAMETER KeyVaultName
    Optional. The name of the Key Vault (3-24 letters, digits and hyphens, starting with a letter). If not provided, a unique name is auto-generated.
 
    .PARAMETER SubscriptionId
    Optional. The Azure subscription ID to deploy to. If not provided, uses the current context.
 
    .PARAMETER Token
    Optional. The RealmJoin onboarding token. When provided, registers the Key Vault with RealmJoin API.
 
    .PARAMETER WhatIf
    Shows what would be deployed without actually performing the deployment.
 
    .EXAMPLE
    Set-RJKeyVault -ResourceGroupName "rg-realmjoin"
 
    .EXAMPLE
    Set-RJKeyVault -ResourceGroupName "rg-realmjoin" -KeyVaultName "kv-rj-contoso"
 
    .EXAMPLE
    Set-RJKeyVault -ResourceGroupName "rg-realmjoin" -WhatIf
    Shows what resources would be deployed without actually deploying.
 
    .EXAMPLE
    Set-RJKeyVault -ResourceGroupName "rg-realmjoin" -Token "your-token"
    Deploys and registers with the RealmJoin API.
    #>


    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)]
        [string]$ResourceGroupName,

        [ValidatePattern('^(?=.{3,24}$)(?!.*--)[a-zA-Z][a-zA-Z0-9-]*[a-zA-Z0-9]$')]
        [string]$KeyVaultName,

        [string]$SubscriptionId,

        [string]$Token
    )

    begin {
        Write-Verbose "Set-RJKeyVault: Starting"
    }

    process {
        if (-not (Test-RJModuleVersion)) {
            # Module is outdated - exit gracefully without throwing
            return
        }

        # Initialize Az modules
        Write-Information "Initializing required Azure modules..."
        if (-not (Initialize-RequiredModule)) {
            Write-Verbose "Azure module initialization failed - cannot proceed"
            return
        }

        # Connect to Azure
        $connectParams = @{}
        if ($SubscriptionId) { $connectParams.SubscriptionId = $SubscriptionId }
        $context = Connect-RJAzureContext @connectParams
        if ($null -eq $context) {
            Write-Information "Operation cancelled."
            return
        }

        # Verify resource group
        $null = Test-ResourceGroup -ResourceGroupName $ResourceGroupName

        if ($PSCmdlet.ShouldProcess("Resource Group: $ResourceGroupName", "Deploy RealmJoin LAPS Key Vault")) {
            Write-Information ""
            Write-Information "============================================"
            Write-Information "RealmJoin LAPS Key Vault Deployment"
            Write-Information "============================================"
            Write-Information ""

            # Deploy
            $deployParams = @{
                ResourceGroupName = $ResourceGroupName
            }
            if ($KeyVaultName) {
                $deployParams.KeyVaultName = $KeyVaultName
            }

            $result = Set-RJKeyVaultResource @deployParams

            if (-not $result.Success) {
                throw "Key Vault deployment failed"
            }

            # Optional API registration
            if ($Token) {
                Write-Information ""
                Write-Information "--- RealmJoin API Registration ---"
                $additionalData = @{
                    tenantId          = $context.TenantId
                    subscriptionId    = $context.SubscriptionId
                    resourceGroupName = $ResourceGroupName
                    keyVaultName      = $result.Outputs.KeyVaultName
                    keyVaultUri       = $result.Outputs.VaultUri
                }

                try {
                    Invoke-RJOnboarding -Token $Token -ApiUrl (Get-RealmJoinTenantKeyVaultConfigApiUrl) -AdditionalData $additionalData
                }
                catch {
                    # The Azure deployment already succeeded. Surfacing this as a terminating error would make
                    # the interactive retry loop redeploy and re-send the (single-use) onboarding token.
                    Write-Warning "RealmJoin API registration failed: $($_.Exception.Message)"
                    Write-Warning "The Key Vault was deployed successfully but is not registered with RealmJoin. Resolve the error above, then run the command from the Key Vault page in the RealmJoin Portal settings."
                }
            }

            # Summary
            Write-Information ""
            Write-Information "============================================"
            Write-Information "Deployment Complete!"
            Write-Information "============================================"
            Write-Information "Key Vault Name: $($result.Outputs.KeyVaultName)"
            Write-Information "Key Vault ID: $($result.Outputs.KeyVaultId)"
            Write-Information "Key Vault URI: $($result.Outputs.VaultUri)"
            Write-Information ""
        }
        else {
            # WhatIf: show analysis
            $analysis = Get-RJAzureResourceAnalysis -ResourceGroupName $ResourceGroupName `
                -DeployKeyVault $true `
                -KeyVaultName $KeyVaultName
            Show-RJAzureResourceAnalysis -Analysis $analysis
        }
    }

    end {
        Write-Verbose "Set-RJKeyVault: Completed"
    }
}