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
Related
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
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
I'm not proficient in Powershell yet, so please bear with me if I use the incorrect terminology.(And please correct me if I do.)
I have installed the Az and Azure.Storage modules.
I have also connected to my account using Connect-AZAccount (Is this the best way? Since you need to copy the URL and login via a browser)
Then I was just trying to view the files, to test the connection. Using Get-AzureStorageFile
This prompts me for a sharename - I used the name of the folder under File Shares in Azure Storage Explorer. But this failed, see failure below
cmdlet Get-AzureStorageFile at command pipeline position 1 Supply
values for the following parameters: (Type !? for Help.) ShareName:
bss get-azurestoragefile : Could not get the storage context. Please
pass in a storage context or set the current storage context.
Additional information to note, I do not have access to the Account Key, only the SAS Token.
Any help would be appreciated.
If you use Connect-AzAccount, you will use the Az module powershell Get-AzStorageFile instead of Get-AzureStorageFile. Before running the Get-AzStorageFile command, you need to pass the storage context with New-AzStorageContext to fix the error.
Sample:
$context = New-AzStorageContext -StorageAccountName "<StorageAccountName>" -StorageAccountKey "<StorageAccountKey>"
Get-AzStorageFile -ShareName "<ShareName>" -Path "<ContosoWorkingFolder>" -Context $context
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!
I think I have setup my powershell environment to connect to my Azure account. I want to upload a file to my HDInsight blob storage. I did:
Set-AzureStorageFileContent -ShareName "what is a share name?" -Source "c:\local.file" -Path "test/"
But I got
Set-AzureStorageFileContent : Can not find your azure storage credential.
Please set current storage account using
"Set-AzureSubscription" or set the "AZURE_STORAGE_CONNECTION_STRING" environment variable.
The help information for Set-AzureSubscription is so useless, I have no idea what it is talking about...
A few things here:
Set-AzureStorageFileContent uploads a file into File Service Share and not Blob Storage. To upload a file into blob storage, you would need to use Set-AzureStorageBlobContent Cmdlet.
I believe the error you're getting is because no storage account is specified. Set-AzureStorageBlobContent cmdlet has a parameter called Context and you would need to specify the context which can do by calling New-AzureStorageContext Cmdlet.
Sample code:
$storageContext = New-AzureStorageContext -StorageAccountName "accountname" -StorageAccountKey "accountkey"
Set-AzureStorageBlobContent -File "full file path" -Container "container name" -BlobType "Block" -Context $storageContext -Verbose
Please note that the container must exist in your storage account which you can create using New-AzureStorageContainer Cmdlet.