'this.Client.SubscriptionId' cannot be null - azure

We noticed that our Azure Subscription field is empty eg:
Get-AzContext -ListAvailable
Name Account SubscriptionName Environment TenantId
---- ------- ---------------- ----------- --------
kk89gan-db99-41c8-95c4-d43adfdfaf34ad ... mymy#outlook.zzz ... AzureCloud 674ce2a1-d4sd1da..
so when I try to run on ps command, I receive an error:
New-AzResourceGroup -Name az1rg -Location 'eastus'
New-AzResourceGroup : 'this.Client.SubscriptionId' cannot be null.
At line:1 char:1

If you don't set an Azure subscription, you won't be allowed to create any Azure resources without the subscription.
You need use Get-AzSubscription to list all the available subscriptions.
Then set the subscription by using Select-AzSubscription {subscription id}.
Now you could create Azure resources.
I notice that your account seems to be a guest user right?
If so, you should assign the guest user as an administrator of a subscription at first. Then the guest user can see the subscription in Powershell.

Add your System Managed Identity as Contributor role in Subscription level.
Add Contributor role on subscription level.
Correct me if I am wrong. Thank You.

The following works
Use Get-AzSubscription to list all the available subscriptions.
Set the subscription by using Select-AzSubscription {subscription id}.

This error also occurs if you are using a Managed Identity to authenticate, but the Automation Account (or Functional App) does not have a Role assigned. Assigning a Role (presumably) "homes" this identity in Subscription and populates this property automatically during authentication.
Issue reported in 2019:
https://github.com/Azure/Azure-Functions/issues/1285

Related

Azure Policy Definition Permission Error : AuthorizationFailed

I am defining a custom azure policy by using this azure template (official github repo of azure).
As a parameter, i am just passing the log analytics workspace name in the param. The below powershell code (taken from the azure repo) is used for that purpose, i have just added -AssignIdentity to the second command as it is necessary. As a role definition, i give owner of subscription rights inside the template.
$definition = New-AzPolicyDefinition -Name "deploy-oms-vm-extension-windows-vm" -DisplayName "Deploy default Log Analytics VM Extension for Windows VMs." -description "This policy deploys the Log Analytics VM Extensions on Windows VMs, and connects to the selected Log Analytics workspace." -Policy 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/Compute/deploy-oms-vm-extension-windows-vm/azurepolicy.rules.json' -Parameter 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/Compute/deploy-oms-vm-extension-windows-vm/azurepolicy.parameters.json' -Mode Indexed
$definition
$assignment = New-AzPolicyAssignment -Name <assignmentname> -Scope <scope> -logAnalytics <logAnalytics> -PolicyDefinition $definition -AssignIdentity
$assignment
The policy is created correctly. But when i try to create a remediation task, the task fails and i get the error below:
Details
Code AuthorizationFailed
Message The client 'xxxx-xxx-xxxx-xxxx-xxxx' with object id 'xxxx-xxx-xxxx-xxxx-xxxx' does not have authorization to perform action 'Microsoft.Resources/deployments/validate/action' over scope '/subscriptions/xxxx-xxx-xxxx-xxxx-xxxx/resourcegroups/rg-test/providers/Microsoft.Resources/deployments/PolicyDeployment_17825756917269472742' or the scope is invalid. If access was recently granted, please refresh your credentials.
On the portal, i see that the policy definition has owner rights as i have defined.
But i also see this on the policy remediation page:
I don't understand the reason of this error. Does someone have any idea?
According to some test, it may be caused by your account permission. I don't think it has anything to do with the role of your policy definition.
One case to show the same error message is do the operation with wrong subscription or wrong resource group, but I think it's a very low probability to choose wrong subscription or resource group because you do it on portal.
The other case to show this error message is what I test in my side. I test with one account hasn't be assigned a role which have enough permission, it shows same error message. So please check your account role and assign a role with higher permission, then create remediation task.
I have found a solution. So the managed identity created during the New-AzPolicyAssignment command execution, is not created with the right permission. The workaround solution is like this:
$definition = New-AzPolicyDefinition -Name "deploy-oms-vm-extension-windows-vm" -DisplayName "Deploy default Log Analytics VM Extension for Windows VMs." -description "This policy deploys the Log Analytics VM Extensions on Windows VMs, and connects to the selected Log Analytics workspace." -Policy 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/Compute/deploy-oms-vm-extension-windows-vm/azurepolicy.rules.json' -Parameter 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/Compute/deploy-oms-vm-extension-windows-vm/azurepolicy.parameters.json' -Mode Indexed
$assignment = New-AzPolicyAssignment -Name <assignmentname> -Scope <scope> -logAnalytics <logAnalytics> -PolicyDefinition $definition -AssignIdentity
## Get newly created policy assignment object
$PolicyAssignment = Get-AzPolicyAssignment -Name $assignmentname -Scope $scope
## Extract the RoleID and ObjectID
$roleDefinitionId = [GUID]($definition.properties.policyRule.then.details.roleDefinitionIds -split "/")[4]
$objectID = [GUID]($PolicyAssignment.Identity.principalId)
## Create a role assignment from the previous information
New-AzRoleAssignment -Scope $scope -ObjectId $objectID -RoleDefinitionId $roleDefinitionId
There is a already opened issue here. I have adapted the solution from there.

List of all the SItes in Azure tenant

like to know all the sites in Azure that are currently associated to our Azure Tenant includes full URL,azure web apps,azure SQL,Storage accounts,Datalake,Cosmosdb,container registries
Tried Get-AzureADTenantDetail and also az resource list but not able find it
Any Powershell script will help
You can use
Azure CLI
az resource list
Powershell
Get-AzureRmResource
You can use Get-AzureRmResource to get the list of resources in an Azure Subscription. By default this Cmdlet will list all resources in an Azure Subscription. To get a list of certain resource types, you can specify an OData filter query.
For example, the Cmdlet below will list all storage accounts and webapps in an Azure Subscription:
Get-AzureRmResource -ODataQuery "ResourceType eq 'Microsoft.Storage/storageAccounts' or ResourceType eq 'Microsoft.Web/sites'" | ft
You will need to find the proper resource type values for each kind of resource that you want to find.
Another thing to notice is that this Cmdlet is scoped to a single Azure Subscription. If your Azure Tenant serves as authentication/authorization source for multiple subscriptions, you would need to run this Cmdlet for each subscription separately.
If you have multiple tenants, you can switch between tenants and get resources within them (subscription by subscription) via
connect-azaccount -Tenant [different tenant id]
$context = Get-AzSubscription [subscriptionid in different tenant id]
set-azcontext $context
get-azresource > resources.tenantname.subcription.txt
where tenantname and subscription are the names of the tenant and subscription in english form (instead of id's).
you should probably not use those azurerm commands anymore, they will stop working sometime in 2024. use the az equivalents (basically replace azurerm with az (yeah, i could delete urerm but that seems weirder!))

How do I Choose which AAD you Create the Service Principal in?

I can't find any documentation on how to choose which AAD to create the service principal in. Basically, I can't find out if there is even a way to add the SP to the local AAD.
So we have a default Global AD which covers all of our enrollment and below that all subscriptions. I'm using Powershell derived from the many many examples on the net to create a SP in the default AD. Then I permission that SP against the subscription it is going to be working in.
At this point I've run into the following problem.
I'm rolling out a Key Vault, this works.
New-AzureRmKeyVault -VaultName $VaultName -EnabledForDeployment -EnabledForTemplateDeployment -ResourceGroupName $ResourceGroupName -Location $Location -Verbose
I need to add the first secret into it as part of the deployment. This bit fails because the SP doesn't have access to the KV.
# Set-AzureRmKeyVaultAccessPolicy -VaultName $VaultName -ResourceGroupName $ResourceGroupName -PermissionsToSecrets get,set -ServicePrincipalName $ServicePrincipalName
This is the result of that command.
Set-AzureRmKeyVaultAccessPolicy : Cannot find the Active Directory object
'Service-Principal-Name' in tenant '6166a717-xxxx-xxxxx-b0e8-6b7288c1f7ec'.
Please make sure that the user or application service principal you are
authorizing is registered in the current subscription's Azure Active
directory.
Reading into this, its not possible to set the Global AD Service Principal to have get/set on the local Keyvault. it would have to be a local Service Principal. However, we dont have one of them and nowhere can I work out how to create one of them.
Anyone else feeling this pain and know how to resolve it?
In the settings section of the old portal (manage.windowsazure.com), you will find a list of all subscriptions. The fourth column (Directory) shows the default directory that is associated with each subscription. No matter what, you will have to create the Service Principal in the Directory that is associated with that particular subscription. Please check this link to understand the relationship between Subscriptions and AAD.

Using Move-AzureRmResource to different subscription with different tenants

I am trying to move some Azure resources from one subscription to another one. I have one Microsoft Account which is co-administrator in both source and target subscriptions.
I run Powershell and log in using the following commandlet:
Add-AzureRmAccount -TenantId "source tenant GUID"
Then I use
Move-AzureRmResource -ResourceId "id of the resource" -DestinationResourceGroupName "xxx" -SubscriptionId "target subscription GUID"
I am getting this error:
Move-AzureRmResource : LinkedAuthorizationFailed : The client has permission to perform
action 'Microsoft.Resources/subscriptions/resourceGroups/write' on scope '/subscriptions/
xxx/resourceGroups/dotnetportal', however the linked subscription 'target subscription GUID' is not in
current tenant 'source tenant GUID'.
Can't reproduce your question and no official material found, but according to the error message however the linked subscription 'target subscription GUID' is not in
current tenant 'source tenant GUID', I think resources moving between subscriptions belong to different tenant is not allowed. Microsoft Azure should have limited the function within identical tenant.
The Azure PowerShell module Move-AzureRmResource cmdlet allows you to move a resource to a different resource group or subscription, but it requires the subscriptions to be in the same tenant.
The best way to check if you have linked subscription is using UI, first.
Login to your source azure subscription.
Browse > Resource groups and select the resource group that contains the VM.
In the Resource group blade, select Move from the menu.
Check if you can see the linked subscription.
A good workaround to copy or move a resource group from one subscription to another see: https://blogs.msdn.microsoft.com/azuregov/2016/12/09/copying-azure-resource-groups-between-different-azure-subscriptions-or-environments/
Share you some code as referenceļ¼š
Get-AzureRMResource -ResourceName **** -ResourceGroupName **** |
Move-AzureRMResource -DestinationResourceGroupName *** -DestinationSubscriptionId **** -Force

How to find the current Azure RM Subscription

In Azure Classic / Service Management, Get-AzureSubscription would give a list of subscriptions in the Tenant with an indicator of which was current.
There was also a Get-AzureSubscription -Current flag that would give you just the current subscription.
Is there a way to find the current subscription in AzureRM.Profile?
Get-AzureRmContext gives you info about the selected subscription, default storage account, etc.
(Get-AzureRmContext).Subscription gives you the current subscription.
Now you can use the new Az commands
Get-AzContext
You can also use Get-AzureRmSubscription
$sub = Get-AzureRmSubscription
$sub.SubscriptionId
This will give you the SubscriptionId

Resources