Get-AzStorageFileContent: Can not find your azure storage credential - azure

I am using a automation account runbook to compare files within a storage account fileshare and have been trying to use Get-AzStorageFileContent to download them so I can then compare.
However, I get the error: "Get-AzStorageFileContent : Can not find your azure storage credential. Please set current storage account using "Set-AzSubscription" or set the "AZURE_STORAGE_CONNECTION_STRING" environment variable."
When I google "Set-AzSubscription" it doesn't appear to exist but I am directed to Set-Azcontext which I have tried to use to set the context to the subscription the storage account is in but this produces the either the same error when testing in powershell ISE or the erorr "please provide a valid tenant or a valid subscription" in the runbook (even though I am using the correct IDs for both)
I have noticed that the storage account is in a different subscription to the runbook could this be breaking it? It does allow me to save files to the storage in the same script so I'm not sure why it would break here.
I am authenticating with a managed identity if that's relevant.
My code to get the file looks like this:
try{
write-output "get file"
Set-Azcontext -Subscription "--storage account subscription--" -Tenant "--Our tenant--"
Get-AzStorageFileContent -ShareName "--storage account name--" -Path "--path of file--"
}
catch{
Write-Output "couldn't get file"
Write-Warning $_.Exception.Message
break
}

Get-AzStorageFileContent : Can not find your azure storage credential. Please set current storage account using "Set-AzSubscription" or set the "AZURE_STORAGE_CONNECTION_STRING" environment variable:
I also got the same error when I tried in my environment.
This issue usually occurs if you do not create a storage context by specifying a storage account name and storage account key, which is required for storage account authentication.
I tried below script in Azure runbook, and it worked successfully as detailed below:
Connect-AzAccount
Set-AzContext -Subscription "<SubscriptionID>"
$context = New-AzStorageContext -StorageAccountName "<StorageAccountName>" -StorageAccountKey "<StorageAccountKey>"
Get-AzStorageFile -ShareName <FileshareName> -context $context
Output:

Related

How to connect with Storage account in Azure automation runbook

In Azure automation runbook I want to connect with storage account and get the context without the account key. I can connect with the storage account key but I don't want to connect with storage key.
FYI
$Context = New-AzStorageContext -StorageAccountName "cordus6abfsuat001" -UseConnectedAccount
echo $Context
ERROR is "Context cannot be null."
I am expecting to connect with storage account with out the storage account key.
You can use a system-assigned managed identity for you Azure Automation account
Then, in your storage account, you got to:
Access Control
Add Role Assignment
There you can give the Role Contributor for your Automation Account Identity
Hoppe This helps!
I am expecting to connect with storage account with out the storage account key.
You can alternatively use Connection string and get the context as below and I followed Microsoft-Document:
Connect-AzAccount
$Context = New-AzStorageContext -ConnectionString "XX"
Write-Host $Context
XX is the Connection string of Storage account.
Output:
You can also get it with uisng SAS token as below:
$Context = New-AzStorageContext -StorageAccountName "rithvayamo" -SasToken "sp=r&st=2022i4n3vHCuHye6PzkDLUbXTnQT2jeNphU1j0%3D"
Write-Host $Context
Output:

Azure APIM Backup throwing error "Invalid parameter: "This request is not authorized to perform this operation.Parameter name: backupContainerName"

I am using the Azure automation runbook to back up APIM on the same region using "user assigned Managed Identities". Have given the role assignment "Storage Account Contributor" to the user assigned managed identity. Also whitelisted IP address of APIM control panel IP i.e "20.44.72.3" for east us 2. Doing all this still i get the error as
Body:
{
"error": {
"code": "InvalidParameters",
"message": "Invalid parameter: This request is not authorized to perform this operation.\r\nParameter name: backupContainerName (value: [apimbackup])",
"details": null,
"innerError": null
}
}
PowerShel Script:
$AzureContext = (Connect-AzAccount -Identity -AccountId XXXX-e9f9-XXXX-ad22-95f821a2c9bc).context
# set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
$storageKey = (Get-AzStorageAccountKey -ResourceGroupName "rg-nau2d-XXXX-01" -StorageAccountName "stornau2dXXXXXX")[0].Value
$storageContext = New-AzStorageContext -StorageAccountName "stornau2dXXXXXX" -StorageAccountKey $storageKey
$storageKey
$StorageContext
$resourceGroupName="rg-nau2d-XXXX-01";
$apiManagementName="apim-01";
$containerName="apimbackup";
$backupName= $apiManagementName +"blob1";
$clientId = "XXXX-e9f9-XXXX-ad22-95f821a2c9bc"
Backup-AzApiManagement -Debug -ResourceGroupName $resourceGroupName -Name $apiManagementName -StorageContext $storageContext -TargetContainerName $containerName -TargetBlobName $backupName -AccessType "UserAssignedManagedIdentity" -IdentityClientId $clientId -PassThru
Please note that the storage account that you have to back up to
can be in any Azure region except in the region where the API Management
service is located i.e.; except the same region.
For example: If at all the APIM service is in West US, then the Storage account must or can be
in West US 2 and have to open the API Management control plane
IP of West US in the firewall beacause the requests to Azure
Storage are not SNATed to a public IP from (compute )
i.e. ; Azure API Management control plane here ,in the same
Azure region. Public IP address can or will be SNATed to
Cross-region storage requests.
And as you are using user assigned identity, please make sure that
identity is given or assigned the role of Storage Blob Data Contributor from the Azure portal , which has scope
to the storage account that you are using for the APIM backup
/restore.After that save changes and refresh the portal and try again.
Note:
Backup is not possible in Consumption but is available in the Premium, Standard, Basic, and Developer tiers of API Management.
Also make sure CORS is not enabled to the target blob storage account
Also check if backup-contributor role is required in your case
Disable AzContextAutosave which makes sure to not to inherit AzContext in your runbook before creating azcontext when using backup-azapimanagement
Disable-AzContextAutosave -Scope Process
$AzureContext = (Connect-AzAccount .....).context
While creating the blob container to store backup , give it a blob permission
New-AzStorageContainer -Name "<apim name>" -Context $storageAccount.Context -Permission blob
Please check the below references to get in detail information about the same.
If the issue seems to be same , try to raise a support request for the same from support+troubleshooting blade from the azure portal.
References:
Implement disaster recovery using backup and restore in API
Management - Azure API Management | Microsoft Docs
Backup and Restore in Azure API Management | Azure Blog
(svenmalvik.com)

Get Azure File share size using PowerShell

is there a way to use powershell to get the size of an Azure File share?
I can use the Get-AzStorageShare to pull the etag, quota, tier, etc. but I can't seem to find where to get the "usage".
I can see it in the portal so it must come from somewhere...
As of version 7.5 of Azure PowerShell, there is no Cmdlet in Az.Storage module which would give you this information directly.
However, there is a workaround.
The idea is to call Get-AzStorageShare which will give you an object of type AzureStorageFileShare. This object has a property called ShareClient which is available in Azure Storage File SDK. Once you have access to this object, you can call GetStatistics method to get the share usage.
$accountName = "your storage account name"
$accountKey = "your storage account key"
$shareName = "your share name"
$ctx = New-AzStorageContext -StorageAccountName $accountName -StorageAccountKey $accountKey
$share = Get-AzStorageShare -Name $shareName
$client = $share.ShareClient
# We now have access to Azure Storage SDK and we can call any method available in the SDK.
# Get statistics of the share
$stats = $client.GetStatistics()
$shareUsageInBytes = $stats.Value.ShareUsageInBytes
Write-Host $shareUsageInBytes

Assign Key Vault Secrets to an Azure Function using Azure PowerShell

I am trying to automate the creation of certain azure resources via an Azure PowerShell script that is triggered from an Azure DevOps release pipeline. I want to create a function app, and automatically integrate reading right access to secrets in an already existing Key Vault. This Key Vault is in the same Azure subscription.
While I can create most resources following the documentation, there seems to be a lack of documentation regarding the creation of certain resources using Azure PowerShell (or I can't find it).
If I follow the sample from this link, I can accomplish it without a problem by using the UI in the Azure Portal, but I can't find any documentation on Microsoft Docs to do it using PowerShell.
Write-Host "Creating Function App..."
$fnApp = New-AzFunctionApp -Name $functionAppName `
-ResourceGroupName $emailFunctionRg `
-Location "$(AzureRegion)" `
-StorageAccount $storageName `
-Runtime dotnet `
-FunctionsVersion '3' `
-IdentityType SystemAssigned
Write-Host "Function App created!"
Write-Host "Assigning Key Vault access..."
$appId = Get-AzADServicePrincipal -DisplayName $functionAppName
Set-AzKeyVaultAccessPolicy -VaultName EmailSettings -ServicePrincipalName $appId -PermissionsToSecrets Get,List
Write-Host "Key Vault access granted!"
Running Set-AzKeyVaultAccessPolicy fails with "Insufficient privileges to complete the operation.". But I am not sure if this is the right path to follow, it was just a guess, based on the available functions in the documentation.
Any ideas?
Two potential issues to check out here:
your app creation assigns the result to $fnApp. perhaps $fnApp or as commented above, $fnApp.ApplicationId is what you should be using for the -ServicePrincipalName parameter on the access policy grant.
you don't have privileges to assign RBAC roles. Go to the Key Vault, choose Access Control, then click the Role Assignments tab and verify that your user appears in the list as an Administrator, User Access Administrator, or Owner.
Edit: With respect to the RBAC privilege, since this is running in Azure Powershell from Azure DevOps, you need to check the role assignment for the Service Connection's service principal - under Azure Active Directory in the Azure Portal, look up the principal used to create the service connection, and make sure THAT gets the correct Role on the key vault.
After a little of trial and error I just came to the conclusion I was not using the right parameter for the Set-AzKeyVaultAccessPolicy cmdlet.
The following script will work (if the service principle running it has the appropriate role, like WaitingForGuacamole mentioned in his/her answer):
Write-Host "Creating Function App..."
$fnApp = New-AzFunctionApp -Name <FnAppName> `
-ResourceGroupName <ResourceGroupName> `
-Location <AzureRegion> `
-StorageAccount <StorageAccount> `
-Runtime dotnet `
-FunctionsVersion '3' `
-IdentityType SystemAssigned
Write-Host "Function App created!"
Write-Host "Assigning Key Vault access..."
Set-AzKeyVaultAccessPolicy -VaultName <NameOfTheKeyVault> -ObjectId (Get-AzADServicePrincipal -DisplayName <FnAppName>).Id -PermissionsToSecrets <Get, List, etc...>
Write-Host "Key Vault access granted!"

Unable to sign in to azure subscription through Azure Automation

I want to execute a runbook from subscription A which will create a storage a/c on subscription B. I provided the (Username/Password) of subscription B in credential asset.
Firstly, please let me know is it possible to do that ?
When i try to run the below code, it gives an error "Unable to acquire token for tenant 'Common' " when i run Get-AzureRmSubscription
$CredentialAssetName = "login";
$Cred = Get-AutomationPSCredential -Name $CredentialAssetName
if(!$Cred) {
Throw "Could not find an Automation Credential Asset named
'${CredentialAssetName}'. Make sure you have created one in this Automation
Account."
}
add-azurermaccount -credential $Cred
login-AzureRMAccount -Credential $Cred
Select-AzureRmSubscription -SubscriptionName 'Free Trial'
get-azurermsubscription
Unable to acquire token for tenant 'Common'
It just a WARNING, that will not affect your script.
please let me know is it possible to do that?
Yes, it is possible, we can use Azure runbook to login subscription B, and use PowerShell to create an Azure storage account in that subscription.
Runbook just like PowerShell, when we use subscription B to log in, the script will work on subscription B.
If subscription B is a Microsoft account, we can follow this answer to login Azure runbook. (Microsoft account does not support non-interactive login.)

Resources