I have requirement to assign Azure Roles to multiple users on subscription scope and Reader role to Managed Identity-Storage Account.
1.Assign Azure RBAC roles to multiple users
2.Assign system assigned managed identity to existing Virtual Machine, Role Reader
Here is the script.
$vm-(Get-Azum-ResourceGroupName <Resourcegrpupname> -Name <VMName>),identity.principalid
New-AzRoleAssignment -Objectid <Objectid> -RoleDefinitionName "Reader" -Scope "/subscriptions/<Id>/resourceGroups/VResourcregroup Name>/providers/Microsoft.Storage/StoragrAccounts/<storageaccoumt>
New-AzRoleAssignment -ObjectId <ID> -RoleDefinationName <RBACRule> -Scope '/Subscription/<I'D>`
`
Script is working,butneed to assign same roles to multiple users.
Assign Azure RBAC roles to multiple users":
To assign roles to multiple users at the same time, simply form a group by adding users who need the "reader" role assignments.
Created a group under AzureAD -> Groups:
new-azroleassignment -objectID <ObjectId of group> -Roledefinitionname "Reader" -scope "/subscriptions/<subscriptionID>/resourceGroups/xxxxRG/..." #Give scope of the resource as per the requirements.
Output:
Assign system assigned managed identity to existing Virtual Machine:
Previously, System assigned identity status is Off:
If not for any particular roles, You can directly update VM configurations/identities by using below commands:
$vminfo = Get-AzVM -ResourceGroupName xxxxxxRG -Name xxxxVM
Update-AzVM -ResourceGroupName xxxxxxRG -VM $vminfo -IdentityType SystemAssigned
System assigned identity status is "ON" now:
Assign system assigned managed identity to existing Virtual Machine, Role Reader:
Using PowerShell, you may configure identities for the appropriate app roles under App services. To work with VMs, use AzCLI command
az vm identity to assign the system-assigned identity as shown here:
az vm identity assign -g xxxxResourceGroup -n xxxxVirtualMachineName --role Reader --scope /subscriptions/<subscriptionID>/resourceGroups/xxxxRG
Assigned:
Updated:
Assigning 'reader' role from VM managed identity to access a storage account:
SID=$(az resource list -n newVM --query [*].identity.principalId --out tsv)
az role assignment create --assignee $SID --role 'Reader' --scope /subscriptions/<subscriptionID>/resourceGroups/xxxxRG/providers/Microsoft.Storage/storageAccounts/<storageaccount>
Assigning Azure RBAC roles with scope as storage account:
new-azroleassignment -objectID <ObjectId of group> -Roledefinitionname "Reader" -scope "/subscriptions/<subscriptionID>/resourceGroups/xxxxRG/providers/Microsoft.Storage/storageAccounts/<storageaccount>
Related
I have been trying to use Powershell to assign users access control privileges for a file share in Azure. What I have been doing is:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Login to Azure
az login
Get User Information and isolate the User Principle Name
$UPN = (Get-AzADUser -StartsWith $UserName).UserPrincipalName
Get the row that contains Scope
$TempScope = az storage share-rm show -g $ResourceGroup --storage-account $StorageAccount --name $FileShareName | Select-String -Pattern '/subscriptions' -CaseSensitive
Change that row to a string
$TempScope = $TempScope | foreach {$_.ToString()}
Remove the first 8 characters
$scope = $TempScope.Substring(9)
Get Name of Role
$FileShareRole = Get-AzRoleDefinition $RoleName
Assign the role to the target identity with the specified scope
New-AzRoleAssignment -SignInName $UPN -RoleDefinitionName $FileShareRole.Name -Scope $scope
It has not been giving the user access to the file share but instead to microsoft.storage/storageaccounts/fileservices/shares.
Yes, You can add Access Control to the file share. In the above-shared script, you are using the long approach to pull the resource ID of the file share. We have made some changes to the above script.
Here is the Modified script to add Access Control to the file Share:
$UserName="<UserName>"
$ResourceGroup="<RGName>"
$StorageAccount="<strgAccountName>"
$FileShareName="<FileShareName>"
$RoleName="Storage File Data SMB Share Reader"
$UPN = (Get-AzADUser -StartsWith $UserName).UserPrincipalName
$TempScope = az storage share-rm show -g $ResourceGroup --storage-account $StorageAccount --name $FileShareName --query id -o tsv
$FileShareRole = Get-AzRoleDefinition $RoleName
New-AzRoleAssignment -SignInName $UPN -RoleDefinitionName $FileShareRole.Name -Scope $scope
Here are the three Azure built-in roles for granting share-level permissions to users:
Storage File Data SMB Share Reader allows read access in Azure Storage file shares over SMB.
Storage File Data SMB Share Contributor allows read, write, and delete access in Azure Storage file shares over SMB.
Storage File Data SMB Share Elevated Contributor allows read, write, delete and modify NTFS permissions in Azure Storage file shares over SMB.
I have an Azure environment with multiple subscriptions and resources. My requirement is to have a functionality where if I pass a user name or SPN name, it gives me all azure resources (from management group to azure resource) where that user/spn has access to and what access it is (reader/ data reader etc).
Major catch is - I want PIM role assignments too. Is there a way to get it?
Options explored
https://learn.microsoft.com/en-us/rest/api/authorization/role-assignments but this gives role assignments per scope. I want per user/spn
https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-list-portal it does not cover PIM assignments and gives assignments per subscription only
Azure Resource Graph Explorer - this does not cover role assignments at all
Apart from iterating through 50 subscriptions, fetching role assignments per scope and then comparing object id, is there any better way?
You can use the below Powershell Script to get the role-assignement for a Service Principal Name in multiple Subscriptions.
Connect-AzAccount
$tenantID = "yourTenantID"
$spn = "serviceprincipalname"
$user= Get-AzADUser -UserPrincipalName $spn
$subscriptions = Get-AzSubscription -TenantId $tenantID
#$subscriptions.Id
foreach ($subscription in $subscriptions) {
$set = Set-AzContext -Subscription $subscription
$set
$roleassignment= Get-AzRoleAssignment -ObjectId $user.Id
$roleassignment
}
Output:
Reference:
Install the Azure Az PowerShell module | Microsoft Docs
This might help you:
az role assignment list --all --assignee <Pricipal_ID>
https://learn.microsoft.com/en-us/cli/azure/role/assignment?view=azure-cli-latest#az-role-assignment-list
#Gjoshevski has shared a useful command, but you still need to loop through each subscription to list the role assignments on each subscription (if you have more than one in your tenant).
The following Azure CLI commands will do the job.
spID='<ObjectID here>' # ObjectID of an Applicatin or Service Principal
$tenantId='<TenantID here>'
az login --tenant 'Your Tenant'
$sub_ids=$(az account list --query id -o tsv)
foreach ($sub_id in $sub_ids) {
az account set --subscription $sub_id
"Subscription Name: $(az account show --query name)"
az role assignment list --all --assignee $spID --include-inherited --include-groups -o table
}
Note that the above is PowerShell syntax but is using Aure CLI commands
I am new to Azure PIM and exploring its capabilities.
I have a use case in hand wherein I need to make the VM Admin role requestable via PIM. I am trying to build a custom role so that I can attach a single VM in the role as part of scope but am unable to do so. All the VMs that are present in the subscription/resource group are getting attached to the role which is not the requirement.
So, in short, is it possible to create a custom role with scope defined for a single VM only though there are multiple VM's in the subscription and(or) resource group.
Yes. You could do that with Az PowerShell cmdlet New-AzRoleDefinition.
Please refer to second example here. (Modify $subs = '/subscriptions/{subscription_id}/resourceGroups/{resourceGroup_name}/providers/Microsoft.Compute/virtualMachines/{VM_name}')
$role = [Microsoft.Azure.Commands.Resources.Models.Authorization.PSRoleDefinition]::new()
$role.Name = 'Virtual Machine Operator 2'
$role.Description = 'Can monitor and restart virtual machines.'
$role.IsCustom = $true
$perms = 'Microsoft.Storage/*/read','Microsoft.Network/*/read','Microsoft.Compute/*/read'
$perms += 'Microsoft.Compute/virtualMachines/start/action','Microsoft.Compute/virtualMachines/restart/action'
$perms += 'Microsoft.Authorization/*/read'
$perms += 'Microsoft.ResourceHealth/availabilityStatuses/read'
$perms += 'Microsoft.Resources/subscriptions/resourceGroups/read'
$perms += 'Microsoft.Insights/alertRules/*','Microsoft.Support/*'
$role.Actions = $perms
$role.NotActions = (Get-AzRoleDefinition -Name 'Virtual Machine Contributor').NotActions
$subs = '/subscriptions/{subscription_id}/resourceGroups/{resourceGroup_name}/providers/Microsoft.Compute/virtualMachines/{VM_name}'
$role.AssignableScopes = $subs
New-AzRoleDefinition -Role $role
Then you can assign this custom role to users in Azure Portal -> this VM -> Access control (IAM).
You can also use cmdlet New-AzRoleAssignment to assign the role.
New-AzRoleAssignment -ObjectId {objectID of the user} -RoleDefinitionName 'Virtual Machine Operator 2' -Scope /subscriptions/{subscription_id}/resourceGroups/{resourceGroup_name}/providers/Microsoft.Compute/virtualMachines/{VM_name}
Make sure the value of -Scope here is the same as AssignableScopes in the first script.
BTW:
In fact, I don't think it's necessary to attach a single VM in the role as part of scope.
When you assign the role to a user, you need to specify the scope as the second script above shown. You can create the custom role with all the VMs that are present in the subscription/resource group getting attached. When you assign the role, you specify only one particular VM as the scope. Then the user can only manage this VM, but not any other VMs.
Using Powershell in an Azure DevOps pipeline, I am trying to assign the key vault's principal the role Storage Account Key Operator Service Role to a storage account.
Command Line
The command line is run after I connected Azure with the service principal:
$credentials = New-Object -TypeName System.Management.Automation.PSCredential($servicePrincipalApplicationId, $clientSecret)
Connect-AzAccount -ServicePrincipal -Credential $credentials -Tenant $tenantId
Here is the command line that I execute :
New-AzRoleAssignment -ApplicationId $keyVaultServicePrincipalId -ResourceGroupName $resourceGroupName -ResourceName $storageAccountName -ResourceType "Microsoft.Storage/storageAccounts" -RoleDefinitionName "Storage Account Key Operator Service Role"
Where:
$keyVaultServicePrincipalId is the pre-registered principal ID for Key Vault. Its value is cfa8b339-82a2-471a-a3c9-0fc0be7a4093.
$resourceGroupName is the name of the resource group in which the storage is located. Its value is accountsmanager-test-global-rg.
$storageAccountName is the name of my storage account. Its value is accountsmanagertest.
Service Principal
Here are the permission of the service principal under which the command is run:
The command is run as a Service Principal that has the Owner role in the subscription:
The resource group created in that subscription is also owned by that Service Principal:
Question
When I run the command, I get the following error:
New-AzRoleAssignment: The provided information does not map to an AD object id.
Why do I get the error The provided information does not map to an AD object id. when executing the command New-AzRoleAssignment?
I can also reproduce this on my side, there are two issues.
1.In your command, the ResourceType should be Microsoft.Storage/storageAccounts, not Microsoft.Storage/storageAccount.
2.In the API permission of your AD App related to the service principal used in the DevOps servcie connection, you need to add the Application permission Directory.Read.All in Azure Active Directory Graph, not Microsoft Graph.
After a while to take effect, it will work fine.
When I try to use Powershell to make a peering link in Azure, between vnets in different subscriptions but in the same tenant, I get the following error messages.
Without specifying tenant:
Set-AzureRmContext : Please provide a valid tenant or a valid subscription.
So I tried specifying the tenant:
Get-AzureRmSubscription : Subscription was not found in tenant ****. Please verify that the subscription exists in this tenant.
I'm using Jenkins with a root account that has access to the dev subscription. I'm setting those credentials using the Microsoft Azure Service Principal bindings, before the job is run.
Does anyone know how I can code my Powershell script so that the Azure end recognises the 2nd subscription ID that I'm trying to peer to?
Current code below.
Write-Host "Create Vnet Peering from dev-vnet to test-centralhub-vnet"
$Subscription1 = Get-AzureRmSubscription -TenantId '(sanitised for Stackoverflow)' -SubscriptionId '(sanitised for Stackoverflow)'
Set-AzureRmContext -Subscription $subscription1
$Vnet1 = Get-AzureRmVirtualNetwork -name 'test-centralhub-vnet' -ResourceGroupName 'test-networks-hub-rg'
$Subscription2 = Get-AzureRmSubscription -TenantId '(sanitised for Stackoverflow)' -SubscriptionId '(sanitised for Stackoverflow)'
Set-AzureRmContext -Subscription $Subscription2
$Vnet2 = Get-AzureRmVirtualNetwork -name 'dev-vnet' -ResourceGroupName 'networks-dev-rg'
Set-AzureRmContext -Subscription '(sanitised for Stackoverflow)'
Add-AzureRmVirtualNetworkPeering -Name 'dev-vnet_to_test-centralhub-vnet' -VirtualNetwork $Vnet2 -RemoteVirtualNetworkId $Vnet1.ID -UseRemoteGateways
As the comment points out, the account you log in with must have the necessary permissions to create a virtual network peering. You can peer virtual networks that exist in two different subscriptions as long as a privileged user of both subscriptions authorizes the peering and the subscriptions are associated with the same Active Directory tenant.
For a list of permissions, see Virtual network peering permissions.
I just test this on my local Powershell. My account was assigned a contributor role in another subscription level, then run your Powershell scripts with the same account successfully.
If you create peering with a different account in the different subscription. You may log in to Azure by entering the Connect-AzureRmAccount command for each subscription. More details from Create peering - PowerShell. Note, the linking scripts are using new Az module. You can refer it to replace Az with AzureRm for AzureRm module.