An Azure service that provides an event-driven serverless compute platform.
Hello !
Thank you for posting on MS Learn Q&A.
You can reply like this:
The error is raised by Get-AzSubscription, not directly by Connect-AzAccount. That means the Function runtime has no valid Az context at the moment Get-AzSubscription runs.
In a PS Azure Function, I would avoid using a user/password credential like this:
Connect-AzAccount -Environment AzureChinaCloud -Credential $Cred
That pattern is fragile in non-interactive automation. If MFA, Conditional Access, password policy, token/cache behavior, tenant selection, or an Az.Accounts change affects the login, Connect-AzAccount may not establish a usable context and the next command fails with:
Run Connect-AzAccount to login
If you check the doc below, Connect-AzAccount you will find that credentialvbased user login only works when MFA is not enabled otherwise interactive login or service principal authentication should be used. Connect-AzAccount supports both managed identity login and service principal login.
https://learn.microsoft.com/en-us/powershell/module/az.accounts/connect-azaccount?view=azps-15.5.0
For an Azure Function, the fix is usually managed identity:
param($Timer)
$ErrorActionPreference = "Stop"
Disable-AzContextAutosave -Scope Process | Out-Null
$TenantId = "<tenant-id>"
$SubscriptionId = "<subscription-id>"
Connect-AzAccount `
-Environment AzureChinaCloud `
-Identity `
-Tenant $TenantId `
-ErrorAction Stop | Out-Null
Set-AzContext -Subscription $SubscriptionId -Tenant $TenantId -ErrorAction Stop | Out-Null
$Subscriptions = Get-AzSubscription -ErrorAction Stop
foreach ($subscription in $Subscriptions) {
Write-Host $subscription.Name
}
Then assign the Function app managed identity the required RBAC role, for example reader, at the subscription or resource group scope.
If managed identity is not possible, use a service principal not a user password:
param($Timer)
$ErrorActionPreference = "Stop"
Disable-AzContextAutosave -Scope Process | Out-Null
$TenantId = "<tenant-id>"
$ApplicationId = "<app-client-id>"
$ClientSecret = $env:CLIENT_SECRET
$SubscriptionId = "<subscription-id>"
$SecurePassword = ConvertTo-SecureString $ClientSecret -AsPlainText -Force
$Credential = [System.Management.Automation.PSCredential]::new($ApplicationId, $SecurePassword)
Connect-AzAccount `
-Environment AzureChinaCloud `
-ServicePrincipal `
-TenantId $TenantId `
-Credential $Credential `
-ErrorAction Stop | Out-Null
Set-AzContext -Subscription $SubscriptionId -Tenant $TenantId -ErrorAction Stop | Out-Null
Get-AzSubscription -ErrorAction Stop
Azure China documentation shows the same service principal pattern with Connect-AzAccount -Environment AzureChinaCloud -ServicePrincipal -TenantId ... -Credential ....
https://docs.azure.cn/en-us/databricks/dev-tools/auth/azure-powershell-login