New-AzSqlDatabaseExport - blob already exists
Description
We are trying to use New-AzSqlDatabaseExport with a Shared Access Key that is locked down to the blob name.
Even when creating a totally fresh storage account that has absolutely no data in it, we get the error "Blob Already Exists"
We have created the below script to reproduce the behavior. Prerequisite is an existing Azure SQL Server with a Database that has SQL Login, and an AAD Account that can create Storage Accounts.
The script creates a brand new storage account, it creates SAS Tokens/Signatures, and it uploads a test file into the storage account, to "proof" that the SAS Token works.
It then tries to export the database to the same storage account (but different BLOB), where is fails with the blob already exists message.
The test upload can be commented out, and it still does not work.
So the error message is misleading at best (because "blob already exists" is really not possible), or we hit a scenario that is somehow not supported.
# Run only once as setup
$subscriptionName = "CHANGEME"
$userAccount = Connect-AzAccount -Subscription $subscriptionName
$sqlUsername = "CHANGEME"
$sqlLoginCredentials = Get-Credential -UserName $sqlUsername
# Storage
$resourceGroup = "CHANGEME"
$accountName = [guid]::NewGuid().ToString("N").SubString(0, 24)
$containerName = "CHANGEME"
$blobPathUploadTest = "$containerName/test3/path/to/blob_$((Get-Date).ToString("yyyyMMddhhmmss")).txt"
$blobPathSqlBackup = "$containerName/test2/path/to/blob_$((Get-Date).ToString("yyyyMMddhhmmss")).dacpac"
$fullPathToAzureSqlBackup = "https://$($accountName).blob.core.windows.net/$($blobPathSqlBackup)"
# SQL
$sqlServerResourceGroup = "CHANGEME"
$sqlServer = "CHANGEME"
$sqlDatabaseName = "CHANGEME"
# Create brand new Storage Account
$storageAccount = New-AzStorageAccount -ResourceGroupName $resourceGroup -Name $accountName -SkuName Standard_LRS -Location EastUS -Tag @{Purpose="Testing"} -AllowBlobPublicAccess $False
$ctx = New-AzStorageContext -StorageAccountName $accountName -UseConnectedAccount
$container = New-AzStorageContainer -Name $containerName -Context $ctx
# Add permissions to create SAS Token
$adUser = Get-AzADUser -UserPrincipalName $userAccount.Context.Account.Id
$role = Get-AzRoleDefinition -Name "Storage Blob Delegator"
$result = New-AzRoleAssignment -ObjectId $adUser.Id -RoleDefinitionId $role.Id -Scope $storageAccount.Id
$role = Get-AzRoleDefinition -Name "Storage Blob Data Contributor"
$result = New-AzRoleAssignment -ObjectId $adUser.Id -RoleDefinitionId $role.Id -Scope $storageAccount.Id
# Generate a SAS Token for the BLOB
$startTime = (Get-Date).AddHours(-24)
$endTime = (Get-Date).AddHours(2.0)
$sasTokenUploadTest = New-AzStorageBlobSASToken -Container $containerName -Blob $blobPathUploadTest -Context $ctx -StartTime $startTime -ExpiryTime $endTime -Permission rw -Protocol HttpsOnly
$sasTokenSqlBackup = New-AzStorageBlobSASToken -Container $containerName -Blob $blobPathSqlBackup -Context $ctx -StartTime $startTime -ExpiryTime $endTime -Permission rw -Protocol HttpsOnly
Write-Output "Sleeping 60 seconds intentionally."
Start-Sleep -Seconds 60 # Give it a few seconds to become fully valid
# Upload some text
$tempFile = New-TemporaryFile
"Just some text" | Out-File $tempFile
$ctx_sas = New-AzStorageContext -StorageAccountName $accountName -SasToken $sasTokenUploadTest -Protocol Https
Set-AzStorageBlobContent -Container $containerName -File $tempFile -Blob $blobPathUploadTest -Context $ctx_sas
# Start Export
New-AzSqlDatabaseExport -ResourceGroupName $sqlServerResourceGroup -ServerName $sqlServer -DatabaseName $sqlDatabaseName -StorageKeyType "SharedAccessKey" -StorageKey $sasTokenSqlBackup -StorageUri $fullPathToAzureSqlBackup -AdministratorLogin $($sqlLoginCredentials.UserName) -AdministratorLoginPassword $($sqlLoginCredentials.Password) -Verbose
Thank you very much
Issue script & Debug output
$DebugPreference='Continue'
# Start Export
New-AzSqlDatabaseExport -ResourceGroupName $sqlServerResourceGroup -ServerName $sqlServer -DatabaseName $sqlDatabaseName -StorageKeyType "SharedAccessKey" -StorageKey $sasTokenSqlBackup -StorageUri $fullPathToAzureSqlBackup -AdministratorLogin $($sqlLoginCredentials.UserName) -AdministratorLoginPassword $($sqlLoginCredentials.Password) -AuthenticationType Sql -Verbose
DEBUG: 2:51:34 PM - NewAzureSqlDatabaseExport begin processing with ParameterSet '__AllParameterSets'.
DEBUG: 2:51:34 PM - using account id '<upn>'...
DEBUG: 2:51:34 PM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
VERBOSE: Performing the operation "About to process resource" on target "<db>".
DEBUG: [Common.Authentication]: Authenticating using Account: '<account>', environment: 'AzureCloud', tenant: '<tenantid>'
DEBUG: 2:51:34 PM - [ConfigManager] Got nothing from [EnableLoginByWam], Module = [], Cmdlet = []. Returning default value [False].
DEBUG: 2:51:34 PM - [SilentAuthenticator] Calling SharedTokenCacheCredential.GetTokenAsync - TenantId:'<tenantid>', Scopes:'https://management.core.windows.net//.default', AuthorityHost:'https://login.microsoftonline.com/', UserId:'<user>'
DEBUG: SharedTokenCacheCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId:
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - ae2eb5db-b70f-4fd2-876d-60609e998bba] IsLegacyAdalCacheEnabled: yes
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - ae2eb5db-b70f-4fd2-876d-60609e998bba] [Region discovery] Not using a regional authority.
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - ae2eb5db-b70f-4fd2-876d-60609e998bba] [Region discovery] Not using a regional authority.
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - ae2eb5db-b70f-4fd2-876d-60609e998bba] IsLegacyAdalCacheEnabled: yes
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - ae2eb5db-b70f-4fd2-876d-60609e998bba] IsLegacyAdalCacheEnabled: yes
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z] Found 1 cache accounts and 0 broker accounts
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z] Returning 1 accounts
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] MSAL MSAL.NetCore with assembly version '4.49.1.0'. CorrelationId(0421f6e0-6671-4d46-9ffc-3a0fc392e137)
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] === AcquireTokenSilent Parameters ===
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] LoginHint provided: False
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] Account provided: True
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] ForceRefresh: False
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137]
=== Request Data ===
Authority Provided? - True
Scopes - https://management.core.windows.net//.default
Extra Query Params Keys (space separated) -
ApiId - AcquireTokenSilent
IsConfidentialClient - False
SendX5C - False
LoginHint ? False
IsBrokerConfigured - False
HomeAccountId - False
CorrelationId - 0421f6e0-6671-4d46-9ffc-3a0fc392e137
UserAssertion set: False
LongRunningOboCacheKey set: False
Region configured:
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] === Token Acquisition (SilentRequest) started:
Scopes: https://management.core.windows.net//.default
Authority Host: login.microsoftonline.com
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] [Region discovery] Not using a regional authority.
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] Access token is not expired. Returning the found cache entry. [Current time (06/12/2023 12:51:34) - Expiration Time (06/12/2023 13:11:55 +00:00) - Extended Expiration Time (06/12/2023 13:11:55 +00:00)]
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] Returning access token found in cache. RefreshOn exists ? False
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] [Region discovery] Not using a regional authority.
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137]
=== Token Acquisition finished successfully:
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] AT expiration time: 6/12/2023 1:11:55 PM +00:00, scopes: https://management.core.windows.net//user_impersonation https://management.core.windows.net//.default. source: Cache
DEBUG: SharedTokenCacheCredential.GetToken succeeded. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: ExpiresOn: 2023-06-12T13:11:55.0000000+00:00
DEBUG: [Common.Authentication]: Received token with LoginType 'User', Tenant: '<tenantId>', UserId: '<upn>'
DEBUG: ============================ HTTP REQUEST ============================
HTTP Method:
POST
Absolute Uri:
https://management.azure.com/subscriptions/<subscriptionid>/resourceGroups/<rg>/providers/Microsoft.Sql/servers/<server>/databases/<database>/export?api-version=2022-08-01-preview
Headers:
Accept-Language : en-US
x-ms-client-request-id : a34950da-83ae-47e5-9fa0-fa8ff3563a69
Body:
{
"storageKeyType": "SharedAccessKey",
"storageKey": "?skoid=7aaa4291-41bf-4e9a-8fbe-f87b63dbda10&sktid=<tenantId>&skt=2023-06-11T12%3A41%3A32Z&ske=2023-06-12T14%3A41%3A32Z&sks=b&skv=2022-11-02&sv=2022-11-02&spr=https&st=2023-06-11T12%3A41%3A32Z&se=2023-06-12T14%3A41%3A32Z&sr=b&sp=rw&sig=K0y3d2m2wF%2B1S33dZUFTDC%2FIPe2eFBwK%2FECH4gSMneY%3D",
"storageUri": "https://71c5e571a5b74865a9e5a58e.blob.core.windows.net/testcontainer/test2/path/to/blob_20230612024103.dacpac",
"administratorLogin": "sqladmin",
"administratorLoginPassword": "<password>",
"authenticationType": "sql"
}
DEBUG: ============================ HTTP RESPONSE ============================
Status Code:
BadRequest
Headers:
Cache-Control : no-cache
Pragma : no-cache
x-ms-request-id : fc28eb16-7a22-4920-ad3c-e6aa0c798789
Server : Microsoft-HTTPAPI/2.0
x-ms-ratelimit-remaining-subscription-writes: 1199
x-ms-correlation-request-id : 4cd41e16-d8fe-4511-81db-134a8a3ee50d
x-ms-routing-request-id : GERMANYWESTCENTRAL:20230612T125135Z:4cd41e16-d8fe-4511-81db-134a8a3ee50d
Strict-Transport-Security : max-age=31536000; includeSubDomains
X-Content-Type-Options : nosniff
Date : Mon, 12 Jun 2023 12:51:35 GMT
Body:
{
"error": {
"code": "BlobAlreadyExist",
"message": "The ImportExport operation failed because the storage blob already exists."
}
}
DEBUG: 2:51:35 PM - [ConfigManager] Got nothing from [EnableDataCollection], Module = [], Cmdlet = []. Returning default value [True].
New-AzSqlDatabaseExport:
Line |
5 | New-AzSqlDatabaseExport -ResourceGroupName $sqlServerResourceGroup -S …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| The ImportExport operation failed because the storage blob already exists.
DEBUG: 2:51:36 PM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 2:51:36 PM - [ConfigManager] Got nothing from [DisplayRegionIdentified], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: AzureQoSEvent: Module: Az.Sql:4.7.0; CommandName: New-AzSqlDatabaseExport; PSVersion: 7.3.4; IsSuccess: False; Duration: 00:00:01.1186080; Exception: The ImportExport operation failed because the storage blob already exists.;
DEBUG: 2:51:36 PM - NewAzureSqlDatabaseExport end processing.
Environment data
Name Value
---- -----
PSVersion 7.3.4
PSEdition Core
GitCommitId 7.3.4
OS Microsoft Windows 10.0.20348
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
Module versions
ModuleType Version PreRelease Name ExportedCommands
---------- ------- ---------- ---- ----------------
Script 2.12.3 Az.Accounts {Add-AzEnvironment, Clear-AzConfig, Clear-AzContext, Clear-AzDefault…}
Script 6.7.0 Az.Resources {Export-AzResourceGroup, Export-AzTemplateSpec, Get-AzDenyAssignment, Get-AzDeployment…}
Script 4.7.0 Az.Sql {Add-AzSqlDatabaseToFailoverGroup, Add-AzSqlElasticJobStep, Add-AzSqlElasticJobTarget, Add-AzSqlInstanceKeyVaultKey…}
Script 5.7.0 Az.Storage {Add-AzRmStorageContainerLegalHold, Add-AzStorageAccountManagementPolicyAction, Add-AzStorageAccountNetworkRule, Close-AzStorageFileHandle…}
Error output
HistoryId: 144
RequestId : 5f9e91dc-8934-4864-b644-c1b68d4eb32c
Message : The ImportExport operation failed because the storage blob already exists.
ServerMessage : BlobAlreadyExist: The ImportExport operation failed because the storage blob already exists. (System.Collections.Generic.List`1[Microsoft.Rest.Azure.CloudError])
ServerResponse : {BadRequest}
RequestMessage : {POST https://management.azure.com/subscriptions/<subid>/resourceGroups/<rg>/providers/Microsoft.Sql/servers/<server>/databases/<dbname>/export?api-version=2022-08-01-preview}
InvocationInfo : {New-AzSqlDatabaseExport}
Line : New-AzSqlDatabaseExport -ResourceGroupName $sqlServerResourceGroup -ServerName $sqlServer -DatabaseName $sqlDatabaseName -StorageKeyType "SharedAccessKey" -StorageKey $sasTokenSqlBackup -StorageUri $fullPathToAzureSqlBackup -AdministratorLogin
$($sqlLoginCredentials.UserName) -AdministratorLoginPassword $($sqlLoginCredentials.Password) -AuthenticationType Sql -Verbose
Position : At line:1 char:1
+ New-AzSqlDatabaseExport -ResourceGroupName $sqlServerResourceGroup -S …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
StackTrace : at Microsoft.Azure.Management.Sql.DatabasesOperations.BeginExportWithHttpMessagesAsync(String resourceGroupName, String serverName, String databaseName, ExportDatabaseDefinition parameters, Dictionary`2 customHeaders, CancellationToken cancellationToken)
at Microsoft.Azure.Management.Sql.DatabasesOperationsExtensions.BeginExportAsync(IDatabasesOperations operations, String resourceGroupName, String serverName, String databaseName, ExportDatabaseDefinition parameters, CancellationToken cancellationToken)
at Microsoft.Azure.Management.Sql.DatabasesOperationsExtensions.BeginExport(IDatabasesOperations operations, String resourceGroupName, String serverName, String databaseName, ExportDatabaseDefinition parameters)
at Microsoft.Azure.Commands.Sql.Database.Services.ImportExportDatabaseCommunicator.BeginExport(String resourceGroupName, String serverName, String databaseName, ExportDatabaseDefinition parameters, Uri& operationStatusLink)
at Microsoft.Azure.Commands.Sql.ImportExport.Service.ImportExportDatabaseAdapter.Export(AzureSqlDatabaseImportExportBaseModel exportRequest)
at Microsoft.Azure.Commands.Sql.ImportExport.Cmdlet.NewAzureSqlDatabaseExport.PersistChanges(AzureSqlDatabaseImportExportBaseModel entity)
at Microsoft.Azure.Commands.Sql.Common.AzureSqlCmdletBase`2.<>c__DisplayClass16_0.<ExecuteCmdlet>b__0()
at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ConfirmAction(String processMessage, String target, Action action)
at Microsoft.Azure.Commands.Sql.Common.AzureSqlCmdletBase`2.ExecuteCmdlet()
at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
HistoryId : 144
Thanks for the feedback! We are routing this to the appropriate team for follow-up. cc @azureSQLGitHub.
Issue Details
Description
We are trying to use New-AzSqlDatabaseExport with a Shared Access Key that is locked down to the blob name.
Even when creating a totally fresh storage account that has absolutely no data in it, we get the error "Blob Already Exists"
We have created the below script to reproduce the behavior. Prerequisite is an existing Azure SQL Server with a Database that has SQL Login, and an AAD Account that can create Storage Accounts.
The script creates a brand new storage account, it creates SAS Tokens/Signatures, and it uploads a test file into the storage account, to "proof" that the SAS Token works.
It then tries to export the database to the same storage account (but different BLOB), where is fails with the blob already exists message.
The test upload can be commented out, and it still does not work.
So the error message is misleading at best (because "blob already exists" is really not possible), or we hit a scenario that is somehow not supported.
# Run only once as setup
$subscriptionName = "CHANGEME"
$userAccount = Connect-AzAccount -Subscription $subscriptionName
$sqlUsername = "CHANGEME"
$sqlLoginCredentials = Get-Credential -UserName $sqlUsername
# Storage
$resourceGroup = "CHANGEME"
$accountName = [guid]::NewGuid().ToString("N").SubString(0, 24)
$containerName = "CHANGEME"
$blobPathUploadTest = "$containerName/test3/path/to/blob_$((Get-Date).ToString("yyyyMMddhhmmss")).txt"
$blobPathSqlBackup = "$containerName/test2/path/to/blob_$((Get-Date).ToString("yyyyMMddhhmmss")).dacpac"
$fullPathToAzureSqlBackup = "https://$($accountName).blob.core.windows.net/$($blobPathSqlBackup)"
# SQL
$sqlServerResourceGroup = "CHANGEME"
$sqlServer = "CHANGEME"
$sqlDatabaseName = "CHANGEME"
# Create brand new Storage Account
$storageAccount = New-AzStorageAccount -ResourceGroupName $resourceGroup -Name $accountName -SkuName Standard_LRS -Location EastUS -Tag @{Purpose="Testing"} -AllowBlobPublicAccess $False
$ctx = New-AzStorageContext -StorageAccountName $accountName -UseConnectedAccount
$container = New-AzStorageContainer -Name $containerName -Context $ctx
# Add permissions to create SAS Token
$adUser = Get-AzADUser -UserPrincipalName $userAccount.Context.Account.Id
$role = Get-AzRoleDefinition -Name "Storage Blob Delegator"
$result = New-AzRoleAssignment -ObjectId $adUser.Id -RoleDefinitionId $role.Id -Scope $storageAccount.Id
$role = Get-AzRoleDefinition -Name "Storage Blob Data Contributor"
$result = New-AzRoleAssignment -ObjectId $adUser.Id -RoleDefinitionId $role.Id -Scope $storageAccount.Id
# Generate a SAS Token for the BLOB
$startTime = (Get-Date).AddHours(-24)
$endTime = (Get-Date).AddHours(2.0)
$sasTokenUploadTest = New-AzStorageBlobSASToken -Container $containerName -Blob $blobPathUploadTest -Context $ctx -StartTime $startTime -ExpiryTime $endTime -Permission rw -Protocol HttpsOnly
$sasTokenSqlBackup = New-AzStorageBlobSASToken -Container $containerName -Blob $blobPathSqlBackup -Context $ctx -StartTime $startTime -ExpiryTime $endTime -Permission rw -Protocol HttpsOnly
Write-Output "Sleeping 60 seconds intentionally."
Start-Sleep -Seconds 60 # Give it a few seconds to become fully valid
# Upload some text
$tempFile = New-TemporaryFile
"Just some text" | Out-File $tempFile
$ctx_sas = New-AzStorageContext -StorageAccountName $accountName -SasToken $sasTokenUploadTest -Protocol Https
Set-AzStorageBlobContent -Container $containerName -File $tempFile -Blob $blobPathUploadTest -Context $ctx_sas
# Start Export
New-AzSqlDatabaseExport -ResourceGroupName $sqlServerResourceGroup -ServerName $sqlServer -DatabaseName $sqlDatabaseName -StorageKeyType "SharedAccessKey" -StorageKey $sasTokenSqlBackup -StorageUri $fullPathToAzureSqlBackup -AdministratorLogin $($sqlLoginCredentials.UserName) -AdministratorLoginPassword $($sqlLoginCredentials.Password) -Verbose
Thank you very much
Issue script & Debug output
$DebugPreference='Continue'
# Start Export
New-AzSqlDatabaseExport -ResourceGroupName $sqlServerResourceGroup -ServerName $sqlServer -DatabaseName $sqlDatabaseName -StorageKeyType "SharedAccessKey" -StorageKey $sasTokenSqlBackup -StorageUri $fullPathToAzureSqlBackup -AdministratorLogin $($sqlLoginCredentials.UserName) -AdministratorLoginPassword $($sqlLoginCredentials.Password) -AuthenticationType Sql -Verbose
DEBUG: 2:51:34 PM - NewAzureSqlDatabaseExport begin processing with ParameterSet '__AllParameterSets'.
DEBUG: 2:51:34 PM - using account id '<upn>'...
DEBUG: 2:51:34 PM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
VERBOSE: Performing the operation "About to process resource" on target "<db>".
DEBUG: [Common.Authentication]: Authenticating using Account: '<account>', environment: 'AzureCloud', tenant: '<tenantid>'
DEBUG: 2:51:34 PM - [ConfigManager] Got nothing from [EnableLoginByWam], Module = [], Cmdlet = []. Returning default value [False].
DEBUG: 2:51:34 PM - [SilentAuthenticator] Calling SharedTokenCacheCredential.GetTokenAsync - TenantId:'<tenantid>', Scopes:'https://management.core.windows.net//.default', AuthorityHost:'https://login.microsoftonline.com/', UserId:'<user>'
DEBUG: SharedTokenCacheCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId:
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - ae2eb5db-b70f-4fd2-876d-60609e998bba] IsLegacyAdalCacheEnabled: yes
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - ae2eb5db-b70f-4fd2-876d-60609e998bba] [Region discovery] Not using a regional authority.
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - ae2eb5db-b70f-4fd2-876d-60609e998bba] [Region discovery] Not using a regional authority.
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - ae2eb5db-b70f-4fd2-876d-60609e998bba] IsLegacyAdalCacheEnabled: yes
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - ae2eb5db-b70f-4fd2-876d-60609e998bba] IsLegacyAdalCacheEnabled: yes
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z] Found 1 cache accounts and 0 broker accounts
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z] Returning 1 accounts
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] MSAL MSAL.NetCore with assembly version '4.49.1.0'. CorrelationId(0421f6e0-6671-4d46-9ffc-3a0fc392e137)
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] === AcquireTokenSilent Parameters ===
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] LoginHint provided: False
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] Account provided: True
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] ForceRefresh: False
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137]
=== Request Data ===
Authority Provided? - True
Scopes - https://management.core.windows.net//.default
Extra Query Params Keys (space separated) -
ApiId - AcquireTokenSilent
IsConfidentialClient - False
SendX5C - False
LoginHint ? False
IsBrokerConfigured - False
HomeAccountId - False
CorrelationId - 0421f6e0-6671-4d46-9ffc-3a0fc392e137
UserAssertion set: False
LongRunningOboCacheKey set: False
Region configured:
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] === Token Acquisition (SilentRequest) started:
Scopes: https://management.core.windows.net//.default
Authority Host: login.microsoftonline.com
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] [Region discovery] Not using a regional authority.
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] Access token is not expired. Returning the found cache entry. [Current time (06/12/2023 12:51:34) - Expiration Time (06/12/2023 13:11:55 +00:00) - Extended Expiration Time (06/12/2023 13:11:55 +00:00)]
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] Returning access token found in cache. RefreshOn exists ? False
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] [Region discovery] Not using a regional authority.
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137]
=== Token Acquisition finished successfully:
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.5 Microsoft Windows 10.0.20348 [2023-06-12 12:51:34Z - 0421f6e0-6671-4d46-9ffc-3a0fc392e137] AT expiration time: 6/12/2023 1:11:55 PM +00:00, scopes: https://management.core.windows.net//user_impersonation https://management.core.windows.net//.default. source: Cache
DEBUG: SharedTokenCacheCredential.GetToken succeeded. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: ExpiresOn: 2023-06-12T13:11:55.0000000+00:00
DEBUG: [Common.Authentication]: Received token with LoginType 'User', Tenant: '<tenantId>', UserId: '<upn>'
DEBUG: ============================ HTTP REQUEST ============================
HTTP Method:
POST
Absolute Uri:
https://management.azure.com/subscriptions/<subscriptionid>/resourceGroups/<rg>/providers/Microsoft.Sql/servers/<server>/databases/<database>/export?api-version=2022-08-01-preview
Headers:
Accept-Language : en-US
x-ms-client-request-id : a34950da-83ae-47e5-9fa0-fa8ff3563a69
Body:
{
"storageKeyType": "SharedAccessKey",
"storageKey": "?skoid=7aaa4291-41bf-4e9a-8fbe-f87b63dbda10&sktid=<tenantId>&skt=2023-06-11T12%3A41%3A32Z&ske=2023-06-12T14%3A41%3A32Z&sks=b&skv=2022-11-02&sv=2022-11-02&spr=https&st=2023-06-11T12%3A41%3A32Z&se=2023-06-12T14%3A41%3A32Z&sr=b&sp=rw&sig=K0y3d2m2wF%2B1S33dZUFTDC%2FIPe2eFBwK%2FECH4gSMneY%3D",
"storageUri": "https://71c5e571a5b74865a9e5a58e.blob.core.windows.net/testcontainer/test2/path/to/blob_20230612024103.dacpac",
"administratorLogin": "sqladmin",
"administratorLoginPassword": "<password>",
"authenticationType": "sql"
}
DEBUG: ============================ HTTP RESPONSE ============================
Status Code:
BadRequest
Headers:
Cache-Control : no-cache
Pragma : no-cache
x-ms-request-id : fc28eb16-7a22-4920-ad3c-e6aa0c798789
Server : Microsoft-HTTPAPI/2.0
x-ms-ratelimit-remaining-subscription-writes: 1199
x-ms-correlation-request-id : 4cd41e16-d8fe-4511-81db-134a8a3ee50d
x-ms-routing-request-id : GERMANYWESTCENTRAL:20230612T125135Z:4cd41e16-d8fe-4511-81db-134a8a3ee50d
Strict-Transport-Security : max-age=31536000; includeSubDomains
X-Content-Type-Options : nosniff
Date : Mon, 12 Jun 2023 12:51:35 GMT
Body:
{
"error": {
"code": "BlobAlreadyExist",
"message": "The ImportExport operation failed because the storage blob already exists."
}
}
DEBUG: 2:51:35 PM - [ConfigManager] Got nothing from [EnableDataCollection], Module = [], Cmdlet = []. Returning default value [True].
New-AzSqlDatabaseExport:
Line |
5 | New-AzSqlDatabaseExport -ResourceGroupName $sqlServerResourceGroup -S …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| The ImportExport operation failed because the storage blob already exists.
DEBUG: 2:51:36 PM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 2:51:36 PM - [ConfigManager] Got nothing from [DisplayRegionIdentified], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: AzureQoSEvent: Module: Az.Sql:4.7.0; CommandName: New-AzSqlDatabaseExport; PSVersion: 7.3.4; IsSuccess: False; Duration: 00:00:01.1186080; Exception: The ImportExport operation failed because the storage blob already exists.;
DEBUG: 2:51:36 PM - NewAzureSqlDatabaseExport end processing.
Environment data
Name Value
---- -----
PSVersion 7.3.4
PSEdition Core
GitCommitId 7.3.4
OS Microsoft Windows 10.0.20348
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
Module versions
ModuleType Version PreRelease Name ExportedCommands
---------- ------- ---------- ---- ----------------
Script 2.12.3 Az.Accounts {Add-AzEnvironment, Clear-AzConfig, Clear-AzContext, Clear-AzDefault…}
Script 6.7.0 Az.Resources {Export-AzResourceGroup, Export-AzTemplateSpec, Get-AzDenyAssignment, Get-AzDeployment…}
Script 4.7.0 Az.Sql {Add-AzSqlDatabaseToFailoverGroup, Add-AzSqlElasticJobStep, Add-AzSqlElasticJobTarget, Add-AzSqlInstanceKeyVaultKey…}
Script 5.7.0 Az.Storage {Add-AzRmStorageContainerLegalHold, Add-AzStorageAccountManagementPolicyAction, Add-AzStorageAccountNetworkRule, Close-AzStorageFileHandle…}
Error output
HistoryId: 144
RequestId : 5f9e91dc-8934-4864-b644-c1b68d4eb32c
Message : The ImportExport operation failed because the storage blob already exists.
ServerMessage : BlobAlreadyExist: The ImportExport operation failed because the storage blob already exists. (System.Collections.Generic.List`1[Microsoft.Rest.Azure.CloudError])
ServerResponse : {BadRequest}
RequestMessage : {POST https://management.azure.com/subscriptions/<subid>/resourceGroups/<rg>/providers/Microsoft.Sql/servers/<server>/databases/<dbname>/export?api-version=2022-08-01-preview}
InvocationInfo : {New-AzSqlDatabaseExport}
Line : New-AzSqlDatabaseExport -ResourceGroupName $sqlServerResourceGroup -ServerName $sqlServer -DatabaseName $sqlDatabaseName -StorageKeyType "SharedAccessKey" -StorageKey $sasTokenSqlBackup -StorageUri $fullPathToAzureSqlBackup -AdministratorLogin
$($sqlLoginCredentials.UserName) -AdministratorLoginPassword $($sqlLoginCredentials.Password) -AuthenticationType Sql -Verbose
Position : At line:1 char:1
+ New-AzSqlDatabaseExport -ResourceGroupName $sqlServerResourceGroup -S …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
StackTrace : at Microsoft.Azure.Management.Sql.DatabasesOperations.BeginExportWithHttpMessagesAsync(String resourceGroupName, String serverName, String databaseName, ExportDatabaseDefinition parameters, Dictionary`2 customHeaders, CancellationToken cancellationToken)
at Microsoft.Azure.Management.Sql.DatabasesOperationsExtensions.BeginExportAsync(IDatabasesOperations operations, String resourceGroupName, String serverName, String databaseName, ExportDatabaseDefinition parameters, CancellationToken cancellationToken)
at Microsoft.Azure.Management.Sql.DatabasesOperationsExtensions.BeginExport(IDatabasesOperations operations, String resourceGroupName, String serverName, String databaseName, ExportDatabaseDefinition parameters)
at Microsoft.Azure.Commands.Sql.Database.Services.ImportExportDatabaseCommunicator.BeginExport(String resourceGroupName, String serverName, String databaseName, ExportDatabaseDefinition parameters, Uri& operationStatusLink)
at Microsoft.Azure.Commands.Sql.ImportExport.Service.ImportExportDatabaseAdapter.Export(AzureSqlDatabaseImportExportBaseModel exportRequest)
at Microsoft.Azure.Commands.Sql.ImportExport.Cmdlet.NewAzureSqlDatabaseExport.PersistChanges(AzureSqlDatabaseImportExportBaseModel entity)
at Microsoft.Azure.Commands.Sql.Common.AzureSqlCmdletBase`2.<>c__DisplayClass16_0.<ExecuteCmdlet>b__0()
at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ConfirmAction(String processMessage, String target, Action action)
at Microsoft.Azure.Commands.Sql.Common.AzureSqlCmdletBase`2.ExecuteCmdlet()
at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
HistoryId : 144
| Author: | MichelZ |
|---|---|
| Assignees: | - |
| Labels: |
|
| Milestone: | - |
Actually, this problem seems to be more generic than Azure Powershell only. After failing to do a backup via Powershell, I tried the same via Azure Portal and ended with the same error.
Error code: BlobAlreadyExist Message: The ImportExport operation failed because the storage blob already exists.
Hey @MichelZ I see that even with a unique blob name, you are still encountering the "BlobAlreadyExist" error.
Here are a few things you can check and try to resolve the issue:
Verify Blob Path: Double-check that the $blobPathSqlBackup variable is correctly generating a unique blob name. You can print out the value of $blobPathSqlBackup to ensure it is in the correct format.
Check Blob Existence: Before starting the export operation, you can check if the blob already exists in the storage account. You can use the Test-AzStorageBlob cmdlet to verify if the blob exists and take appropriate action based on the result. For example:
$blobExists = Test-AzStorageBlob -Container $containerName -Blob $blobPathSqlBackup -Context $ctx
if ($blobExists) {
# Handle the scenario when the blob already exists (e.g., generate a new unique blob name)
} else {
# Proceed with the export operation
New-AzSqlDatabaseExport -ResourceGroupName $sqlServerResourceGroup -ServerName $sqlServer -DatabaseName $sqlDatabaseName -StorageKeyType "SharedAccessKey" -StorageKey $sasTokenSqlBackup -StorageUri $fullPathToAzureSqlBackup -AdministratorLogin $($sqlLoginCredentials.UserName) -AdministratorLoginPassword $($sqlLoginCredentials.Password) -Verbose
}
Delete Existing Blob: If you determine that the blob already exists and needs to be overwritten, you can delete the existing blob before starting the export operation. You can use the Remove-AzStorageBlob cmdlet to remove the blob before proceeding with the export. For example:
Remove-AzStorageBlob -Container $containerName -Blob $blobPathSqlBackup -Context $ctx
After deleting the existing blob, you can then start the export operation as usual.
Please let me know if any of the above proposed solutions work. Thanks.
Hey @MichelZ I see that even with a unique blob name, you are still encountering the "BlobAlreadyExist" error.
Here are a few things you can check and try to resolve the issue:
Verify Blob Path: Double-check that the
$blobPathSqlBackupvariable is correctly generating a unique blob name. You can print out the value of$blobPathSqlBackupto ensure it is in the correct format.Check Blob Existence: Before starting the export operation, you can check if the blob already exists in the storage account. You can use the
Test-AzStorageBlobcmdlet to verify if the blob exists and take appropriate action based on the result. For example:
$blobExists = Test-AzStorageBlob -Container $containerName -Blob $blobPathSqlBackup -Context $ctx if ($blobExists) { # Handle the scenario when the blob already exists (e.g., generate a new unique blob name) } else { # Proceed with the export operation New-AzSqlDatabaseExport -ResourceGroupName $sqlServerResourceGroup -ServerName $sqlServer -DatabaseName $sqlDatabaseName -StorageKeyType "SharedAccessKey" -StorageKey $sasTokenSqlBackup -StorageUri $fullPathToAzureSqlBackup -AdministratorLogin $($sqlLoginCredentials.UserName) -AdministratorLoginPassword $($sqlLoginCredentials.Password) -Verbose }Delete Existing Blob: If you determine that the blob already exists and needs to be overwritten, you can delete the existing blob before starting the export operation. You can use the Remove-AzStorageBlob cmdlet to remove the blob before proceeding with the export. For example:
Remove-AzStorageBlob -Container $containerName -Blob $blobPathSqlBackup -Context $ctxAfter deleting the existing blob, you can then start the export operation as usual.
Please let me know if any of the above proposed solutions work. Thanks.
Thank you. After tinkering a bit more, here is what I found out:
- The Blob does NOT exist
- The Path to the Blob in the SAS token was different than the path to the Blob in the Export command (the SAS token had an extra /containerName/ in the Path)
After fixing the path, this worked as expected. So it seems the error message is misleading here. As the SAS token does not have access to the blob, there should be some kind of AccessDenied message, and not a BlobAlreadyExists, this is very misleading unfortunately.
@SudhirRaparla @rwestMSFT @WilliamDAssafMSFT @rothja long shot here but would anyone of you know who the right contact/product group would be for this issue? I found your tags based on docs authored by you related to this issue.
Thanks.
@tdoshin - Acknowledge this. Looking into this issue.
@SudhirRaparla I am running into the same issue with New-AzSqlDatabaseExport module. I've double checked that the storage blob doesn't exist on the container I am using. Could you pls help with it? I am running the script using Powershell btw.
"New-AzSqlDatabaseExport : The ImportExport operation failed because the storage blob already exists."
Hi @prahladravuri - You need to make sure the blob path in the SAS token and the Export command both match like MichelZ has found:
@SudhirRaparla I am using Storage Access Key for accessing the storage, not SAS tokens.
@SudhirRaparla I am having the same issue, using Storage Access Key and SAS tokens.
I have confirmed the path to the Blob in the SAS token matches
@jackcaplin I got the issue bypassed by creating another blob storage for my purpose. And I was able to export a bacpac successfully to the new storage. I am still not clear on what's the issue with my old storage. Anyways, below are the major differences between the 2 blob accounts, not sure if they play any role in the generating that error though. Just thought of sharing it here, maybe you can give a try. Please LMK what happens, kinda curious...
New storage:
Performance: Standard Replication: Read-access geo-redundant storage (RA-GRS) Account kind: StorageV2 (general purpose v2)
Old storage: Performance: Premium Replication: Locally-redundant storage (LRS) Account kind: BlockBlobStorage
I think this could be something getting cached on the client. I was repeatedly hitting this issue for two database exports and as soon as I ran the same script via an Azure DevOps pipeline, it succeeded.
Make sure that if you are generating a key using a user delegation token, the user you are generating the SAS with has the appropriate storage account RBAC rights:
I had the same issue when using "SharedAccessKey" with any SAS token (Account, Service, Container and BLOB) which was working one day, but then stopped working the next. When I switched to "StorageAccessKey" the export worked, which led me to investigate my SAS tokens:
I created a SAS token in the portal and the export worked.
My issue, which caused this error, was that I was creating SAS tokens with a user delegation key signing (-UseConnectedAccount) in Powershell:
$myctx = New-AzStorageContext -StorageAccountName mystorageaccount -UseConnectedAccount
My user account did not (Due to a PIM eligibility/assignment expiring) have the required rights (Storage Blob data contributor). See https://learn.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas for the details of the RBAC roles required to create a user delegation token (which is what -UseConnectedAccount uses). But this does not prevent you from creating such a SAS token.
In the portal, the default is to create SAS tokens signed via the account key. which I could generate as I had inherited 'Contributor' rights, meant the SAS key I generated via the portal did not have the issue.
Hope this helps - It boiled my noodle for a few hours.
Closing as resolved
I had the same issue, but in my case the solution was to enable public access from all networks to the storage account, as suggested in the answer here: https://learn.microsoft.com/en-us/answers/questions/52722/error-while-export-database-to-a-storage-account
Same issue here, I had to allow access from all networks. Command was run from an Azure Automation Runbook.
So I see 2 problems:
- error message is not correct
- why is Azure Automation not in the allowed services list for a storage account?
I had the same problem, but in my case it was that I had not granted Read permissions to the SAS, because my logic was, why would a backup export script that only needs to write data need read permissions?
I had the same issue, but in my case the solution was to enable public access from all networks to the storage account
I'm having the same issue and tried to add range 0.0.0.0 to 255.255.255.255 to firewall but it doesn't help (I haven't found any option for "allow all" in Azure Portal). What else can be the issue? I'm trying with Storage Access Key.
I don't have this option.