Примените Azure RBAC к ресурсу, используя ARM
Есть ли способ применить правила RBAC на уровне ресурсов через ARM? Мне удалось следовать этому руководству Microsoft, чтобы добавить пользователя / роль на уровне группы ресурсов, но не на уровне ресурса. В частности, я пытаюсь добавить новую роль читателя в AppInsights через ARM. Однако, когда я настраиваю область, шаблон просто терпит неудачу с этой ошибкой:
"error": {
"code": "InvalidCreateRoleAssignmentRequest",
"message": "The request to create role assignment '{guid}' is not valid. Role assignment scope '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.Insights/components/{resourceGroupName}' must match the scope specified on the URI '/subscriptions/{resourceGroupName}/resourcegroups/{resourceGroupName}'."
}
Мне интересно, для чего нужна переменная области видимости, если она не может быть изменена. Есть ли какое-то другое место, где я должен изменить область, чтобы это работало?
Заранее спасибо!
2 ответа
Ключ должен бросить scope
свойство, и вместо этого вложите назначение роли в нужный ресурс, используя Microsoft.FooResource/BarSubType/providers/roleAssignments
как тип, и используя следующий формат для имени: {resourceName}/Microsoft.Authorization/{uniqueRoleAssignmentGuid}
, Обратите внимание, что GUID должен быть стабильным, но уникальным для данного назначения ролей, одним из простых вариантов является guid(subscription().subscriptionId, 'some-sub-identifier-if-you-wish')
,
Вот шаблон, который показывает, как применить RBAC к одному ресурсу, используя назначенный пользователем управляемый идентификатор, определенный в том же шаблоне:
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"storageAccountName": { "type": "string" },
"userAssignedIdentityName": { "type": "string" }
},
"variables": {
"ContributorRoleDefinition": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', 'b24988ac-6180-42a0-ab88-20f7382dd24c')]",
},
"resources": [
{
"type": "Microsoft.ManagedIdentity/userAssignedIdentities",
"name": "[parameters('userAssignedIdentityName')]",
"location": "[resourceGroup().location]",
"apiVersion": "2018-11-30"
},
{
"type": "Microsoft.Storage/storageAccounts",
"name": "[parameters('storageAccountName')]",
"location": "[resourceGroup().location]",
"apiVersion": "2016-12-01",
"sku": { "name": "Standard_LRS" },
"kind": "Storage",
"resources": [
{
"type": "Microsoft.Storage/storageAccounts/providers/roleAssignments",
"apiVersion": "2017-05-01",
"name": "[concat(parameters('storageAccountName'), '/Microsoft.Authorization/', guid(subscription().subscriptionId, 'foo'))]",
"properties": {
"roleDefinitionId": "[variables('ContributorRoleDefinition')]",
"principalId": "[reference(parameters('userAssignedIdentityName'), '2018-11-30').principalId]"
},
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))]",
"[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', parameters('userAssignedIdentityName'))]"
]
}
]
}
]
}
Источник: https://www.henrybeen.nl/creating-an-authorization-rule-using-an-arm-template/
Вы применяете правила RBAC на уровне ресурсов через ARM, и здесь есть пример шаблона, который применяет правила RBAC на виртуальной машине Azure:
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"principalId": {
"type": "string",
"metadata": {
"description": "Principal ID associated with the subscription ID"
}
},
"virtualMachineName": {
"type": "string",
"metadata": {
"description": "Name of the virtual machine"
}
},
"builtInRoleType": {
"type": "string",
"metadata": {
"description": "Built In Role Type for the Virtual Machine"
},
"allowedValues": [
"Owner",
"Contributor",
"Reader",
"Virtual Machine Contributor"
]
},
"guid": {
"type": "string",
"metadata": {
"description": "A new GUID used to identify the role"
}
},
"location": {
"type": "string",
"defaultValue": "[resourceGroup().location]",
"metadata": {
"description": "Location for all resources."
}
}
},
"variables": {
"Owner": "[concat('/subscriptions/',subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', '8e3af657-a8ff-443c-a75c-2fe8c4bcb635')]",
"Contributor": "[concat('/subscriptions/',subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', 'b24988ac-6180-42a0-ab88-20f7382dd24c')]",
"Reader": "[concat('/subscriptions/',subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', 'acdd72a7-3385-48ef-bd42-f606fba81ae7')]",
"Virtual Machine Contributor": "[concat('/subscriptions/',subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', 'd73bb868-a0df-4d4d-bd69-98a00b01fccb')]",
"resourceName": "[concat(parameters('virtualMachineName'), '/Microsoft.Authorization/', parameters('guid'))]"
},
"resources": [
{
"type": "Microsoft.Compute/virtualMachines/providers/roleAssignments",
"apiVersion": "2017-05-01",
"name": "[variables('resourceName')]",
"properties": {
"roleDefinitionId": "[variables(parameters('builtInRoleType'))]",
"principalId": "[parameters('principalId')]"
}
}
]
}
Надеюсь, что это поможет вам.
Наконец, Microsoft предоставила документацию, объясняющую это:
https://docs.microsoft.com/en-us/azure/role-based-access-control/role-assignments-template
Можно применить RBAC на уровне ресурсов, используя ARM.
В приведенном вами примере показано, как применить RBAC к определенной группе ресурсов, где область действия - это путь к группе ресурсов.
Здесь вы пытаетесь назначить роль определенному ресурсу. Изменение области действия от группы ресурсов до ресурса (AppInsights) будет работать.
Из исключения я вижу, что путь к ресурсу может быть не в ожидаемом формате.
Путь AppInsights должен быть в следующем формате,
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{insightName}
Надеюсь, что создание рамок, как это помогает!
Согласитесь, документация по этому вопросу менее чем полезна. У меня есть массив идентификаторов ролей, которые я хотел добавить в качестве владельцев в ресурс App Insight, не делая пользователей владельцами на уровне группы ресурсов. Я не хотел использовать подход с вложенными ресурсами, так как я хотел перебирать массив объектов для динамического создания ролей, поэтому после настройки атрибутов типа, имени и области действия следующий блок ресурсов - это то, что в итоге сработало для меня.:
{
"comments": "Add the Application Insights resource",
"apiVersion": "2014-04-01",
"name": "[variables('appInsightsName')]",
"type": "Microsoft.Insights/components",
"location": "[resourceGroup().location]",
"properties": {
"ApplicationId": "[variables('appInsightsName')]"
}
},
{
"comments": "Add the IAM roles to the App Insights resource",
"condition": "[parameters('isProduction')]",
"type": "Microsoft.Insights/components/providers/roleAssignments",
"name": "[concat(variables('appInsightsName'),'/Microsoft.Authorization/',guid(parameters('roleAssignments')[copyIndex()].principalId))]",
"apiVersion": "2017-05-01",
"location": "[resourceGroup().location]",
"properties": {
"roleDefinitionId": "[concat(subscription().Id, '/providers/Microsoft.Authorization/roleDefinitions/8e3af657-a8ff-443c-a75c-2fe8c4bcb635')]", // Owner Role
"principalId": "[parameters('roleAssignments')[copyIndex()].principalId]",
"scope": "[resourceId('Microsoft.Insights/components', variables('appInsightsName'))]"
},
"copy": {
"name": "appInsightsRoleAssignments",
"count": "[length(parameters('roleAssignments'))]"
},
"dependsOn": [
"[resourceId('Microsoft.Insights/components', variables('appInsightsName'))]"
]
}