Поделиться через


Add or edit Azure role assignment conditions using Azure PowerShell

Условие назначения ролей Azure — это дополнительная проверка, которую можно дополнительно добавить в назначение роли, чтобы обеспечить более точное управление доступом. Например, можно добавить условие, требующее, чтобы у объекта был конкретный тег, чтобы его можно было прочитать. This article describes how to add, edit, list, or delete conditions for your role assignments using Azure PowerShell.

Предпосылки

Дополнительные сведения о предварительных требованиях для добавления и изменения условий назначения ролей см. в разделе Требования к условиям.

Добавить условие

To add a role assignment condition, use New-AzRoleAssignment. The New-AzRoleAssignment command includes the following parameters related to conditions.

Параметр Тип Описание
Condition Струна Условие, при котором пользователю может быть предоставлено разрешение.
ConditionVersion Струна Version of the condition syntax. Must be set to 2.0. If Condition is specified, ConditionVersion must also be specified.

The following example shows how to initialize the variables to assign the Storage Blob Data Reader role with a condition. The condition checks whether container name equals 'blobs-example-container'.

$subscriptionId = "<subscriptionId>"
$resourceGroup = "<resourceGroup>"
$roleDefinitionName = "Storage Blob Data Reader"
$roleDefinitionId = "2a2b9908-6ea1-4ae2-8e65-a410df84e7d1"
$userObjectId = "<userObjectId>"
$scope = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup"
$description = "Read access if container name equals blobs-example-container"
$condition = "((!(ActionMatches{'Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read'})) OR (@Resource[Microsoft.Storage/storageAccounts/blobServices/containers:name] StringEquals 'blobs-example-container'))"
$conditionVersion = "2.0"

Use New-AzRoleAssignment to assign the role with a condition.

New-AzRoleAssignment -ObjectId $userObjectId -Scope $scope -RoleDefinitionId $roleDefinitionId -Description $description -Condition $condition -ConditionVersion $conditionVersion

Пример результата выглядит следующим образом.

RoleAssignmentId   : /subscriptions/<subscriptionId>/resourceGroups/<resourceGroup>/providers/Microsoft.Authorization/roleAssignments/<roleAssignmentId>
Scope              : /subscriptions/<subscriptionId>/resourceGroups/<resourceGroup>
DisplayName        : User1
SignInName         : [email protected]
RoleDefinitionName : Storage Blob Data Reader
RoleDefinitionId   : 2a2b9908-6ea1-4ae2-8e65-a410df84e7d1
ObjectId           : <userObjectId>
ObjectType         : User
CanDelegate        : False
Description        : Read access if container name equals blobs-example-container
ConditionVersion   : 2.0
Condition          : ((!(ActionMatches{'Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read'})) OR (@Resource[Microsoft.Storage/storageAccounts/blobServices/containers:name] StringEquals 'blobs-example-container'))

В PowerShell, если условие включает знак доллара ($), необходимо префиксить его с помощью обратной символики ('). For example, the following condition uses dollar signs to delineate the tag key name. Дополнительные сведения о правилах кавычек в PowerShell см. в разделе "О правилах кворирования".

$condition = "((!(ActionMatches{'Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read'} AND NOT SubOperationMatches{'Blob.List'})) OR (@Resource[Microsoft.Storage/storageAccounts/blobServices/containers/blobs/tags:Project<`$key_case_sensitive`$>] StringEquals 'Cascade'))"

Изменение условия

To edit an existing role assignment condition, use Set-AzRoleAssignment. Только свойства Condition, ConditionVersion и Description можно изменять. The -PassThru parameter causes Set-AzRoleAssignment to return the updated role assignment, which allows visualization or storage in a variable for further use.

There are two ways to edit a condition. You can use the PSRoleAssignment object or a JSON file.

Edit a condition using the PSRoleAssignment object

  1. Use Get-AzRoleAssignment to get the existing role assignment with a condition as a PSRoleAssignment object.

    $testRa = Get-AzRoleAssignment -Scope $scope -RoleDefinitionName $roleDefinitionName -ObjectId $userObjectId
    
  2. Измените условие.

    $condition = "((!(ActionMatches{'Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read'})) OR (@Resource[Microsoft.Storage/storageAccounts/blobServices/containers:name] StringEquals 'blobs-example-container' OR @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:name] StringEquals 'blobs-example-container2'))"
    
  3. Initialize the condition and description.

    $testRa.Condition = $condition
    $testRa.Description = "Read access if container name equals blobs-example-container or blobs-example-container2"
    
  4. Используйте Set-AzRoleAssignment , чтобы обновить условие назначения роли.

    Set-AzRoleAssignment -InputObject $testRa -PassThru
    

    Пример результата выглядит следующим образом.

    RoleAssignmentId   : /subscriptions/<subscriptionId>/resourceGroups/<resourceGroup>/providers/Microsoft.Authorization/roleAssignments/<roleAssignmentId>
    Scope              : /subscriptions/<subscriptionId>/resourceGroups/<resourceGroup>
    DisplayName        : User1
    SignInName         : [email protected]
    RoleDefinitionName : Storage Blob Data Reader
    RoleDefinitionId   : 2a2b9908-6ea1-4ae2-8e65-a410df84e7d1
    ObjectId           : <userObjectId>
    ObjectType         : User
    CanDelegate        : False
    Description        : Read access if container name equals blobs-example-container or blobs-example-container2
    ConditionVersion   : 2.0
    Condition          : ((!(ActionMatches{'Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read'})) OR (@Resource[Microsoft.Storage/storageAccounts/blobServices/containers:name] StringEquals 'blobs-example-container' OR @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:name] StringEquals 'blobs-example-container2'))
    

Edit a condition using a JSON file

To edit a condition, you can also provide a JSON file as input. The following shows an example JSON file where Condition and Description are updated. You must specify all the properties in the JSON file to update a condition.

{
    "RoleDefinitionId": "2a2b9908-6ea1-4ae2-8e65-a410df84e7d1",
    "ObjectId": "<userObjectId>",
    "ObjectType": "User",
    "Scope": "/subscriptions/<subscriptionId>/resourceGroups/<resourceGroup>",
    "Condition": "((!(ActionMatches{'Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read'})) OR (@Resource[Microsoft.Storage/storageAccounts/blobServices/containers:name] StringEquals 'blobs-example-container' OR @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:name] StringEquals 'blobs-example-container2'))",
    "ConditionVersion": "2.0",
    "CanDelegate": false,
    "Description": "Read access if container name equals blobs-example-container or blobs-example-container2",
    "RoleAssignmentId": "/subscriptions/<subscriptionId>/resourceGroups/<resourceGroup>/providers/Microsoft.Authorization/roleAssignments/<roleAssignmentId>"
}

Используйте Set-AzRoleAssignment , чтобы обновить условие назначения роли.

Set-AzRoleAssignment -InputFile "C:\path\roleassignment.json" -PassThru

Пример результата выглядит следующим образом.

RoleAssignmentId   : /subscriptions/<subscriptionId>/resourceGroups/<resourceGroup>/providers/Microsoft.Authorization/roleAssignments/<roleAssignmentId>
Scope              : /subscriptions/<subscriptionId>/resourceGroups/<resourceGroup>
DisplayName        : User1
SignInName         : [email protected]
RoleDefinitionName : Storage Blob Data Reader
RoleDefinitionId   : 2a2b9908-6ea1-4ae2-8e65-a410df84e7d1
ObjectId           : <userObjectId>
ObjectType         : User
CanDelegate        : False
Description        : Read access if container name equals blobs-example-container or blobs-example-container2
ConditionVersion   : 2.0
Condition          : ((!(ActionMatches{'Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read'})) OR (@Resource[Microsoft.Storage/storageAccounts/blobServices/containers:name] StringEquals 'blobs-example-container' OR @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:name] StringEquals 'blobs-example-container2'))

Edit conditions in multiple role assignments

If you need to make the same update to multiple role assignments, you can use a loop. The following commands perform the following task:

  • Finds role assignments in a subscription with <find-condition-string-1> or <find-condition-string-2> strings in the condition.

    $tenantId = "<your-tenant-id>"
    $subscriptionId = "<your-subscription-id>";
    $scope = "/subscriptions/$subscriptionId"
    $findConditionString1 = "<find-condition-string-1>"
    $findConditionString2 = "<find-condition-string-2>"
    Connect-AzAccount -TenantId $tenantId -SubscriptionId $subscriptionId
    $roleAssignments = Get-AzRoleAssignment -Scope $scope
    $foundRoleAssignments = $roleAssignments | Where-Object { ($_.Condition -Match $findConditionString1) -Or ($_.Condition -Match $findConditionString2) }
    

The following commands perform the following tasks:

  • In the condition of the found role assignments, replaces <condition-string> with <replace-condition-string>.

  • Updates the role assignments with the changes.

    $conditionString = "<condition-string>"
    $conditionStringReplacement = "<condition-string-replacement>"
    $updatedRoleAssignments = $foundRoleAssignments | ForEach-Object { $_.Condition = $_.Condition -replace $conditionString, $conditionStringReplacement; $_ }
    $updatedRoleAssignments | ForEach-Object { Set-AzRoleAssignment -InputObject $_ -PassThru }
    

If strings include special characters, such as square brackets ([ ]), you'll need to escape these characters with a backslash (\).

Перечислите условие

To list a role assignment condition, use Get-AzRoleAssignment. For more information, see List Azure role assignments using Azure PowerShell.

Удаление условия

To delete a role assignment condition, edit the role assignment condition and set both the Condition and ConditionVersion properties to either an empty string ("") or $null.

Alternatively, if you want to delete both the role assignment and the condition, you can use the Remove-AzRoleAssignment command. Дополнительные сведения см. в статье Удаление назначений ролей Azure.

Дальнейшие действия