Private/New-VMMetricsStorageContext.ps1
|
function New-VMMetricsStorageContext { <# .SYNOPSIS Resolves account-key auth and returns a ready storage context, ensuring the target container exists. .DESCRIPTION Account-key authentication (per design). The key is taken from -StorageAccountKey when supplied, otherwise fetched from the control plane via Get-AzStorageAccountKey using -ResourceGroupName (works in Cloud Shell where the signed-in identity has control-plane rights). The container is created if missing, with no public access. .PARAMETER StorageAccountName Target storage account. .PARAMETER ContainerName Blob container; created if absent. .PARAMETER StorageAccountKey Account key. If omitted, -ResourceGroupName must be given to fetch it (unless -SasToken). .PARAMETER ResourceGroupName Resource group of the storage account, used to fetch the key when not supplied. .PARAMETER SasToken A shared-access-signature token scoped to the container (e.g. for cross-tenant uploads from a customer's Cloud Shell). When given, key auth is bypassed entirely and the container is assumed to exist (a container-scoped SAS cannot create one). .OUTPUTS Microsoft.WindowsAzure.Commands.Storage.AzureStorageContext #> [CmdletBinding(SupportsShouldProcess)] param( [Parameter(Mandatory)] [string] $StorageAccountName, [Parameter(Mandatory)] [string] $ContainerName, [string] $StorageAccountKey, [string] $ResourceGroupName, [string] $SasToken ) # SAS auth: no key, no control-plane access, no container creation. if ($SasToken) { Write-Verbose "Using SAS token for $StorageAccountName (container assumed to exist)." return New-AzStorageContext -StorageAccountName $StorageAccountName -SasToken $SasToken -ErrorAction Stop } if (-not $StorageAccountKey) { if (-not $ResourceGroupName) { throw "Provide -StorageAccountKey, -StorageAccountResourceGroup (to fetch the key), or -SasToken." } Write-Verbose "Fetching account key for $StorageAccountName from RG $ResourceGroupName." $keys = Get-AzStorageAccountKey -ResourceGroupName $ResourceGroupName -Name $StorageAccountName -ErrorAction Stop $StorageAccountKey = $keys[0].Value } $ctx = New-AzStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey -ErrorAction Stop $container = Get-AzStorageContainer -Name $ContainerName -Context $ctx -ErrorAction SilentlyContinue if (-not $container -and $PSCmdlet.ShouldProcess($ContainerName, "Create blob container")) { Write-Verbose "Creating container '$ContainerName'." New-AzStorageContainer -Name $ContainerName -Context $ctx -Permission Off -ErrorAction Stop | Out-Null } return $ctx } |