Search code examples
powershellazure-cliazure-storage-accountazure-sas

Generate Azure Storage Account SAS Key using PowerShell


I am trying to generate an azure storage account shared access key so that i can use it with azcopy to retrieve files from all containers in my storage account.

I have generated a key successfully using the Azure Portal and proven this works with azcopy

But i am struggling to get an equivalent key to generate using PowerShell that works.

Powershell Query az storage container generate-sas --account-name $SaName --account-key $accountKey --permissions 'rl' --start $start --expiry $expiry --name $SaName --https-only --output tsv

Azure Portal (GUI) Result

sv=2019-12-12
&ss=b
&srt=sco
&sp=rl
&se=2021-02-08T17:40:26Z
&st=2021-02-08T09:40:26Z
&spr=https
&sig=REDACTED

Powershell Result

st=2021-02-08T17%3A17%3A47Z
&se=2021-02-08T17%3A47%3A47Z
&sp=rl
&spr=https
&sv=2018-11-09
&sr=c
&sig=REDACTED

I guess the first problem is that i have not found a way of adding the missing and ss=b srt=sco (not sr) there doesn't seem to be those parameters available, perhaps if they were there the sig would have the correct hash.

I have tried this in Azure Cloudshell as well as on my own machine with az 1.12.1


Solution

  • The command az storage container generate-sas is not powershell command, it's azure cli command.

    Because in Azure portal, you're generating an account level sas-token, but in azure cli, you're actually generating a container level sas-token by using az storage container generate-sas.

    To generate an account level sas-token, you should use this azure cli command: az storage account generate-sas.

    The sample like below:

    az storage account generate-sas --account-key "xxxxx"  --account-name your_storage_account_name --expiry 2020-02-10 --https-only --permissions rl --resource-types sco --services b
    

    Here is the test result, the ss=b srt=sco are generated:

    enter image description here

    If you want to use powershell to generate an account level sas-token, please use this powershell command: New-AzStorageAccountSASToken. The sample is as below(you can add other parameters as per your need):

    $account_name = "yy1"
    
    $account_key = "xxxxxxx"
    
    $context = New-AzStorageContext -StorageAccountName $account_name -StorageAccountKey $account_key
    
    #you can also add other parameter as per your need, like StartTime, ExpiryTime etc.
    New-AzStorageAccountSASToken -Service Blob -ResourceType Service,Container,Object -Permission rl -Context $context
    

    Here is the test result:

    enter image description here