Forum Discussion
Marek_Belan
Jan 15, 2025Brass Contributor
Addin Eligible role to Subscription by powershell Question
I need assign groups to roles for subscription by powershell (100+ groups and subsc) I need this was eligible so users in grop must use PIN to activate role. How to do this?
Adeelaziz
Jan 15, 2025Brass Contributor
I responded to this earlier today but noticed my reply is stick. Here goes attempt #2.
You can do this by reading in a list of Group names and Resource Groups from a csv file. The CSV file should be formatted like the example below and please keep the column headers as they will be referenced in the script.
CSV input file for script:
GroupName,ResourceGroup
Group1,ResourceGroup1
Group2,ResourceGroup2
Group3,ResourceGroup3
Note:
The duration is set by -Duration flag in the New-AzRoleAssignment cmdlet. I've set it to be "P1Y" which denotes 1 year. You could change that to "P1M" for 1 month etc. This is the ISO 8601 standard for setting durations.
Script:
# Import the CSV file
$groups = Import-Csv -Path "path\to\your\groups.csv"
# Connect to Azure
Connect-AzAccount
# Define the role
$roleDefinitionId = (Get-AzRoleDefinition -Name "Contributor").Id
# Loop through each group and assign the role
foreach ($group in $groups) {
try {
$groupName = $group.GroupName
$resourceGroup = $group.ResourceGroup
$scope = "/subscriptions/your-subscription-id/resourceGroups/$resourceGroup"
$groupObject = Get-AzADGroup -DisplayName $groupName
$groupId = $groupObject.Id
# Assign the role with eligible and time-bound settings for 1 year
New-AzRoleAssignment -ObjectId $groupId -RoleDefinitionId $roleDefinitionId -Scope $scope -AssignmentType "Eligible" -Duration "P1Y"
Write-Output "Successfully assigned role to group: $groupName for resource group: $resourceGroup"
}
catch {
Write-Error "Failed to assign role to group: $groupName for resource group: $resourceGroup. Error: $_"
}
}
Write-Output "Role assignments completed."
- Marek_BelanJan 16, 2025Brass Contributor
This is wrong.
New-AzRoleAssignment doesn't have parameter AssignmentType.