0

When I run my script below it keeps failing with "The ImportExport operation failed because of invalid storage credentials." The access key and SAS all seem to be correct when I check in the portal. Can someone please point me in the right direction

    param(
        [string]$SubscriptionId,
        [string]$ResourceGroupName,
        [string]$storageRG,
        [string]$ServerName,
        [string]$DatabaseName,
        [string]$StorageAccountName,
        [string]$StorageContainerName,
        [string]$StorageAccountKey,
        [string]$ImportBacpacFilename,
        [string]$AdministratorLogin, 
        [string]$AdministratorLoginPassword
    )

    Add-Type -AssemblyName System.Web

    try {
        # Set the subscription context
        Write-Verbose "Setting subscription context..."
        Select-AzSubscription -SubscriptionId $SubscriptionId

        # Get the storage account
        Write-Verbose "Getting storage account..."
        $StorageAccount = Get-AzStorageAccount -ResourceGroupName $storageRG -Name $StorageAccountName

        # Get the storage account context
        Write-Verbose "Getting storage account context..."
        $StorageAccountContext = $StorageAccount.Context

        # Generate the SAS token for the storage container
        $StartTime = Get-Date
        $ExpiryTime = $StartTime.AddHours(6)
        $SasTokenRaw = New-AzStorageContainerSASToken -Name $StorageContainerName -Permission rw -StartTime $StartTime -ExpiryTime $ExpiryTime -Context $StorageAccountContext
        $SasToken = [System.Web.HttpUtility]::UrlEncode($SasTokenRaw)
        $StorageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $storageRG -Name $StorageAccountName)[0].Value
        # Build the destination URL
        $Sourceurl = "https://$StorageAccountName.blob.core.windows.net/$StorageContainerName/$ImportBacpacFilename$SasToken"
        # Import the Azure SQL Database to the Blob Storage container
        $ImportRequest = New-AzSqlDatabaseImport -DatabaseName $DatabaseName -ResourceGroupName $ResourceGroupName -StorageKeyType StorageAccessKey -StorageKey $StorageAccountKey -StorageUri $Sourceurl -Edition Standard -ServiceObjectiveName S0 -DatabaseMaxSizeBytes 5000000 -AdministratorLogin $AdministratorLogin -AdministratorLoginPassword (ConvertTo-SecureString $AdministratorLoginPassword -AsPlainText -Force)-ServerName $ServerName

        # Check the status of the import operation
        $ImportStatus = Get-AzSqlDatabaseImportExportStatus -OperationStatusLink $ImportRequest.OperationStatusLink
        [System.Console]::Write("Importing")
        while ($ImportStatus.Status -eq "InProgress") {
            Start-Sleep -s 30
            $ImportStatus = Get-AzSqlDatabaseImportExportStatus -OperationStatusLink $ImportStatus.OperationStatusLink
            [System.Console]::Write(".")
        }
        [System.Console]::Write("")
        $ImportStatus
        if ($ImportStatus.Status -eq "Succeeded") {
            Write-Host "Import completed successfully!"
        }
        else {
            Write-Host "Import failed. Status: $($ImportStatus.Status)"
        }
    }
    catch {
        Write-Error "An error occurred: $_"
    }

}
jarlh
  • 42,561
  • 8
  • 45
  • 63
KayMan
  • 23
  • 6
  • What database are you using in backend? Check log files of database for more info. If SQL Server than connect with SQL Server Management Studio for log files under management. – jdweng Apr 18 '23 at 11:37
  • I have updated the script and seems to work when I run it, displaying Import completed successfully. However, when I go in the portal I cannot see the imported database. – KayMan Apr 18 '23 at 12:18
  • You are not reporting the status of the IMPORT request. If it fails you loose the error message because you are going and overriding the status with the Get-AzSqlDatabaseImportExportStatus command. – jdweng Apr 18 '23 at 12:39
  • @jdweng Should I remove the first Get-AzSqlDatabaseImportExportStatus command ? – KayMan Apr 18 '23 at 12:49
  • Removing the one before the while loop should work. – jdweng Apr 18 '23 at 14:10

3 Answers3

1

I have reproduced in my environment and got expected results as below and I followed Microsoft-Document and Micrsoft-Document2:

Firstly, I have got Access key as below:

(Get-AzStorageAccountKey -ResourceGroupName "resource group name" -Name "name of storage account")[0].Value

enter image description here

Then have used below command:

New-AzSqlDatabaseExport -ResourceGroupName "resource group name" -DatabaseName "databasename" -StorageKeytype StorageAccessKey -StorageKey "PVggweeFl6SqaVjzHX3eKD7Qs7BWFqRpAG2AW/CvyLBYB/QezI+ASt9Ms02w==" -StorageUri "https://storageaccountname.blob.core.windows.net/rconatinername/blobaname" -AdministratorLogin "emo" -AdministratorLoginPassword $(ConvertTo-SecureString "Password" -AsPlainText -Force) -ServerName "servername"

enter image description here

Output in Portal:

enter image description here

Here you don't need SAS token and try to follow above process.

RithwikBojja
  • 5,069
  • 2
  • 3
  • 7
0

For anyone else (like me) that finds this page via Google. The "invalid storage credentials" error also appears when you supply an invalid URL for the blob that holds the export.

To test this, try and download the blob with your account key through the CLI. This is an example command to test the URI:

az storage blob download --blob-url  https://$storageAccount.blob.core.windows.net/$storageContainer/$backupName.bacpac --account-key $yourStorageKey
Joon
  • 2,127
  • 1
  • 22
  • 40
0

The root cause in my scenario was a lack of permissions to access the Storage Account container. The operation I was performing even failed when done over the Azure Portal. The error message "The ImportExport operation failed because of invalid storage credentials." was not helpful at all.

Even though I HEAVILY discourage allowing public access to the resource, you can temporarily do so to discard this as a potential issue: enter image description here

NOTE: A proper use of Azure Storage Resource Instance Rules might be the way to go here instead of allowing public access.

You can also run any Azure CLI command you're using with the --debug flag for more insights if you need to:

$ az sql db import --admin-password "PASS" --admin-user USER --storage-key MYKEY --storage-key-type StorageAccessKey --storage-uri "https://mystorageaccount.blob.core.windows.net/container-name/backup.bacpac" --name DBNAME --resource-group RGNAME --server SQLSERVERNAME --debug

PS: I'm very very new to Azure, so take this with a grain of salt.

ryuzakyl
  • 511
  • 8
  • 14