Azure Storage SAS URL Generation - powershell

I would like to have the SAS URL generated for temporary access to use during backup. How could I do this with powershell.
( Note : Posting this as I couldn't find a straight pointer on how to, since from PHP background and other pages talks about generating with console applications and using. )

The MSDN links https://msdn.microsoft.com/en-us/library/dn140255.aspx details the structure of a SAS Url and the same could be generated with cmdlet New-AzureStorageContainerSASToken
$SAStokenURL = New-AzureStorageContainerSASToken -Name $BackupContainerName -Context $context -Permission rwdl -StartTime $now.AddHours(-1) -ExpiryTime $now.AddMonths(1) -FullUri
write-host $SAStokenURL
Where,
$Context is the Storage context
and -FullUri returns the desired URL.
( I might not be complete or missing something and would glad to know further from experts here )

To generate a SAS token for providing temporary access to your Storage account containers/blobs through PowerShell, here are the commands that you can fire up to get things working.
$StartTime - Start time from when you want to the access to be given
$expiryTime - End time till when you want to the access to be given
$sasTokenFullURI = New-AzureStorageContainerSASToken -Name $StorageContainerName -Permission $Permission -StartTime $StartTime -ExpiryTime $expiryTime -Context $context -FullUri
Hope this helps!

Related

Getting blank while trying to get list of blobs from PowerShell

I am trying to fetch the list of blobs present in the Azure Blob Container from PowerShell.
I have tried using function in my script to do that. But it is returning nothing.
My script is somewhat like this(Hiding names of resources):
## Connect to Azure Account
Connect-AzAccount
Function GetBlobs
{
## Get the storage account
$storageAcc=Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName
## Get all the containers
$containers=Get-AzStorageContainer
## Get all the blobs
$blobs=Get-AzStorageBlob -Container $containerName
## Loop through all the blobs
foreach($blob in $blobs)
{
write-host $blob.Name
}
}
GetBlobs
But it returned blank though I have blobs in my container. I don't know what I'm doing wrong.
Can someone help me out? I'm new to this platform too, don't know if I put my question in the right way.
I have tested in my environment. It returned the list of blobs successfully.
Try including storage account context. If you want to know more about this, go through this link. After including that, you may get the list of blobs successfully.
Please check if your script is something like this:
$resourceGroupName = "your_RG"
$storageAccountName= "your_SA"
$containerName= "your_container_name"
## Connect to Azure Account
Connect-AzAccount
## Function to get all the blobs
Function GetBlobs
{
$storageAcc=Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName
## Get the storage account context
$context=$storageAcc.Context
## Get all the containers
$containers=Get-AzStorageContainer -Context $context
$blobs=Get-AzStorageBlob -Container $containerName -Context $context
foreach ($blob in $blobs)
{
write-host $blob.Name
}
}
GetBlobs
Please check the below reference if it is helpful.
Reference:
How to Get All the Blobs from an Azure Storage Account using PowerShell (c-sharpcorner.com)

Using Only a SAS Token To Upload in PowerShell

I have a SAS Token in the form:
https://name.blob.core.windows.net/container?sv=2015-04-05&sr=b&sig=abc123&se=2017-03-07T12%3A58%3A52Z&sp=rw
I am attempting to use an Az Provided Cmdlet in Powershell to upload content to this blob. I am unable to find an API that simply takes the above SAS token and a file to upload.
Reading this reddit post it seems like my options are:
Parse out the StorageAccountName (in the example name), Container (in the example container) and SASToken (in the example above sv=2015-04-05&sr=b&sig=abc123&se=2017-03-07T12%3A58%3A52Z&sp=rw) and then use New-AzStorageContext/Set-AzStorageBlobContent. This more or less is the answer in this StackOverflow Post (Connect to Azure Storage Account using only SAS token?)
Use Invoke-WebRequest or its kin to basically perform the REST call myself.
I would like to use as many Az provided cmdlets possible so starting with option 1, there doesn't seem to be an API to parse this, the closest I can find is this StackOverflow Post (Using SAS token to upload Blob content) talking about using CloudBlockBlob, however it is unclear if this class is available to me in PowerShell.
To these ends I've created a Regex that appears to work, but is most likely brittle, is there a better way to do this?
$SASUri = https://name.blob.core.windows.net/container?sv=2015-04-05&sr=b&sig=abc123&se=2017-03-07T12%3A58%3A52Z&sp=rw
$fileToUpload = 'Test.json'
$regex = [System.Text.RegularExpressions.Regex]::Match($SASUri, '(?i)\/+(?<StorageAccountName>.*?)\..*\/(?<Container>.*)\?(?<SASToken>.*)')
$storageAccountName = $regex.Groups['StorageAccountName'].Value
$container = $regex.Groups['Container'].Value
$sasToken = $regex.Groups['SASToken'].Value
$storageContext = New-AzStorageContext -StorageAccountName $storageAccountName -SasToken $sasToken
Set-AzStorageBlobContent -File $fileToUpload -Container $container -Context $storageContext -Force
To Restate The Questions
Is there an Az Cmdlet that takes the SAS URI and SAS Token to allow upload?
(If not) Is there an API to parse the SAS URI + SAS Token?
Considering $SASUri is a URI, you can get a System.Uri object using something like:
$uri = [System.Uri] $SASUri
Once you have that, you can get the container name and the SAS token using something like:
$storageAccountName = $uri.DnsSafeHost.Split(".")[0]
$container = $uri.LocalPath.Substring(1)
$sasToken = $uri.Query
After that your code should work just fine:
$storageContext = New-AzStorageContext -StorageAccountName $storageAccountName -SasToken $sasToken
Set-AzStorageBlobContent -File $fileToUpload -Container $container -Context $storageContext -Force

upload file to blob storage with Azure functions in PowerShell using Azure module

Requirement is to store the file in Storage account through Azure functions in PowerShell using Az module. Please help.
$todaydate = Get-Date -Format MM-dd-yy
$LogFull = "AzureScan-$todaydate.log"
$LogItem = New-Item -ItemType File -Name $LogFull
" Text to write" | Out-File -FilePath $LogFull -Append
First of all, what you need to figure out is the input of your function and how you're handling that. If you're just wanting to write a file to blob storage everytime an HTTP triggered Azure function is executed then that is simple enough.
There are a number of elements that come into play when working with blob storage with Azure Functions however that you will need to understand to develop a working solution.
Managed Identities
Azure Funtions are able to be assigned an identity so that you can grant access to the FunctionApp itself rather than having to authenticate as a user. This means you don't have to handle the authentication aspect of your function to access the storage account content and you just need to grant your FunctionApp the relevant permissions to read/write/delete blob or storage content.
There are a number of built in RBAC roles in AzureAD which you can grant to access storage accounts and blobs etc.
You can find the documentation on the RBAC permissions for that here: https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#storage
and the documentation on how to activate a managed identity on your functionApp can be found here: https://learn.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=dotnet#add-a-system-assigned-identity
Storage Account(s)
Programmatically accessing storage account contents depends on the permissions but you can use the access keys associated to the storage account which provide access to at the storage account level
You can read about the access keys here: https://learn.microsoft.com/en-us/azure/storage/common/storage-account-keys-manage?tabs=azure-portal#view-account-access-keys
Just remember that least-privilege access should be adopted and if you leak your keys then someone could access your data.
PowerShell Commands
The PowerShell commands required for programmatically accessing storage accounts and writing blob data can be summarised below
# Variables required - Fill these out
$storageAccountName = '<Insert Storage Account Here'
$containerName = '<Insert StorageContainer Name Here>'
# Set the context to the subscription you want to use
# If your functionApp has access to more than one subscription it will load the first subscription by default.
# Possibly a good habit to be explicit about context.
Set-AzContext -Subscription $subscription
# Get the Storage Account Key to authenticate
$storAccKeys = Get-AzStorageAccountKey -ResourceGroupName 'Storage-ResourceGroup' -Name $storageAccountName
$primaryKey = $storAccKeys | Where-Object keyname -eq 'key1' | Select-Object -ExpandProperty value
# Create a Storage Context which will be used in the subsequent commands
$storageContext = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $primaryKey
# Attempt to create a container in the storage account. Handle Error appropriately.
try {
New-AzStorageContainer -Name $containerName -Context $storageContext -ErrorAction Stop
}
catch [Microsoft.WindowsAzure.Commands.Storage.Common.ResourceAlreadyExistException] {
Write-Output ('Container {0} already exists in Storage Account {1}' -f $containerName, $storageAccountName)
# Throw Here if you want it to fail instead.
}
catch {
throw $_
}
# Upload your file here. This may vary depending on your function input and how you plan to have your functionApp work.
Set-AzStorageBlobContent -Container $containerName -File ".\PlanningData" -Blob "Planning2015"
You can see the documentation on Set-AzStorageBlobContent for examples on that here:
https://learn.microsoft.com/en-us/powershell/module/az.storage/set-azstorageblobcontent?view=azps-6.2.1#examples
Generally though you will need a file to upload to blob storage and you can't just write directly to a file in blob storage.
If you need to read more on the Azure Functions side of things then there is the quickstart guide:
https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-vs-code-powershell
Or the Developer Reference on MS docs is really detailed:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-powershell?tabs=portal

Using SAS token to upload Blob content

I'm having difficulty in using a Blob SAS token to write a file to a Blob in Azure via Powershell.
The code I'm using to generate the SAS token is:
$storageContext = Get-AzureRmStorageAccount -ResourceGroupName $resourceGroup -Name $storageName
$token = New-AzureStorageBlobSASToken -Container $conName -Context $storageContext.Context -Blob $blobName -ExpiryTime $expiry -Permission rw -FullUri
This generates a token as expected: https://name.blob.core.windows.net/container/test.json?sv=2015-04-05&sr=b&sig=abc123&se=2017-03-07T12%3A58%3A52Z&sp=rw
If I use this in the browser it's working fine and downloading the file as expected. However, I can't use this to upload a file. Whenever I try I'm receiving a (403) Forbidden. The code I'm using to upload is:
$accountContext = New-AzureStorageContext -SasToken $sasToken
Get-AzureStorageContainer -Context $accountContext.Context | Set-AzureStorageBlobContent -File $blobFile
I've successfully been using a method similar to this to set Blob content after making a call to Add-AzureRmAccount to authenticate.
I've also tried to use a Container SAS token but I keep getting a 403 error with that.
The fact that the token works for a read leads me to believe that I'm missing something in my Powershell script - can anyone shed any light on what that is?
The fact that the token works for a read leads me to believe that I'm
missing something in my Powershell script - can anyone shed any light
on what that is?
I believe the problem is with the following line of code:
Get-AzureStorageContainer -Context $accountContext.Context
Two things here:
This cmdlet tries to list the blob containers in your storage account. In order to list blob containers using SAS, you would need an Account SAS where as the SAS you're using is a Container SAS.
Your SAS only has Read and Write permission. For listing containers, you would need List permission as well.
I would recommend simply using Set-AzureStorageBlobContent Cmdlet and provide necessary information to it instead of getting the container name through pipeline.
Set-AzureStorageBlobContent -File $blobFile -Container $conName -Context $accountContext.Context -Blob $blobName

List existing SASTokens on a container using Azure powershell

When creating a SASToken via powershell it retunrs the created SAS token url from New-AzureStorageContainerSASToken comdlet.
$Context = New-AzureStorageContext -StorageAccountName $StorageAccount -StorageAccountKey $StorageAccountKey
$now = Get-Date
$sasUrl = New-AzureStorageContainerSASToken -Name mycontainer -Permission rwdl -StartTime $now.AddHours(-1) -ExpiryTime $now.AddMonths(1) -Context $context -FullUri
echo $sasUrl
But now in case I lost it, how can I list the exiting SASTokens? You may have few on the same container.
Tried Get-AzureStorageContainer but this information is unavailable.
Played with other Get-AzureStorage* and failed to find it.
Is this operation supported via powershell?
It is not possible to get the list of SAS URLs because they are not stored anywhere in Azure Storage.
Probably a bit late.... but on this page:
https://learn.microsoft.com/en-us/azure/storage/storage-dotnet-shared-access-signature-part-1
It says:
"The SAS token generated by the storage client library is not tracked by Azure Storage in any way. You can create an unlimited number of SAS tokens on the client side."
HTH!
Paul
With Powershell perhaps not, but Perhaps possible with the REST API: https://learn.microsoft.com/en-us/rest/api/storagerp/storageaccounts/listaccountsas
For the POST request, some of the request body parameters are REQUIRED to be filled which will need trial and error as you may not remember for what duration the SAS was allowed for. But provided all the values at https://learn.microsoft.com/en-us/rest/api/storagerp/storageaccounts/listaccountsas#request-body are somehow documented , then it should be programmatically possible to get the SAS token itself.
I think you don't understand how SAS token works: Generated SAS tokens are not stored anywhere because when you generate a SAS token, no call is made to the Azure Storage server. This is just a local calculation based on the secret key (like an asymetrical encryption with public and private key)