Unable to assign role to user using New-AzureRmRoleAssignment
command. When I run the above command its thronging an error as follows .
New-AzureRmRoleAssignment : Object reference not set to an instance of an object.
Can any one help to resole the issue.
To assign role to user successfully in the runbook, follow the steps below.
Note : The New-AzureRmRoleAssignment
you used belongs to the old AzureRM
, it was deprecated and will not be updated anymore. In my sample, I use the new Az
command New-AzRoleAssignment
, I also recommend you to use it.
1.Navigate to the subscription in the portal(you need to be Owner/User Access Administrator
in the subscription) -> add the service principal of your automation RunAs account as an Owner/User Access Administrator
(by default it will be added as Contributor
when it was created, but Contributor
have no permission to run New-AzRoleAssignment
).
2.Navigate to the Azure Active Directory
in the portal -> App registrations
-> find the AD App of your RunAs Account and add the Directory.Read.All
application permission in Azure Active Directory Graph
(Not Microsoft Graph) like below, don't forget to click the Grant admin consent for xxx
button at last(you need to be the admin role in your AAD tenant). The permission may take about 30 min to take effect.
3.Navigate to the automation account in the portal -> Modules
-> make sure you have installed the Az.Accounts
, Az.Resources
modules, if not, go to Browse Gallery
, search for the names, and install them.
4.Then in the runbook, use the script below, it works fine on my side. In my sample, I add the user as a Reader
in the resource group joyRG
, you can change it, it depends on your requirement.
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Connect-AzAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
$user = Get-AzADUser -UserPrincipalName [email protected]
New-AzRoleAssignment -ObjectId $user.id -ResourceGroupName joyRG -RoleDefinitionName Reader