Azure / azure-powershell

Microsoft Azure PowerShell
Other
4.21k stars 3.81k forks source link

Set-AzRoleDefinition fails to update if Assignable Scope is changed to new Management Group #13449

Open scottstout opened 3 years ago

scottstout commented 3 years ago

Description

If you do the Set-AzRoleDefinition it will fail if you change the scope from one Management Group to another. It will say it can't find a role definition by that ID. It appears to be relying on the assignable scope to look for the ID and the role isn't currently in the new assignable scope you are trying to update to.

Note that this works fine in Azure CLI.

Steps to reproduce

Try to reproduce the scenario described here. In particular we are trying to reproduce the approach described as "Change the assignable scope within the role definition. In the above example, you can update the assignable scopes from Marketing to Root Management Group so that the definition can be reached by both branches of the hierarchy."

  1. Create custom role with an assignable scope set to a custom MG.
  2. Get the role definition and modify the assignable scope to be the tenant root assignable scope.
  3. Run Set-AzRoleDefinition to update the role definition to the new scope. This will fail with a message saying it can't find a role definition with the specified ID.

Environment data

Module versions

Debug output

Error output

ghost commented 3 years ago

Thanks for the feedback! We are routing this to the appropriate team for follow-up. cc @armleads-azure.


Issue meta data

Issue content: ## Description If you do the Set-AzRoleDefinition it will fail if you change the scope from one Management Group to another. It will say it can't find a role definition by that ID. It appears to be relying on the assignable scope to look for the ID and the role isn't currently in the new assignable scope you are trying to update to. Note that this works fine in Azure CLI. ## Steps to reproduce Try to reproduce the scenario described [here](https://docs.microsoft.com/en-us/azure/governance/management-groups/overview#issues-with-breaking-the-role-definition-and-assignment-hierarchy-path). In particular we are trying to reproduce the approach described as "Change the assignable scope within the role definition. In the above example, you can update the assignable scopes from Marketing to Root Management Group so that the definition can be reached by both branches of the hierarchy." 1. Create custom role with an assignable scope set to a custom MG. 2. Get the role definition and modify the assignable scope to be the tenant root assignable scope. 3. Run Set-AzRoleDefinition to update the role definition to the new scope. This will fail with a message saying it can't find a role definition with the specified ID. ```powershell ``` ## Environment data ``` ``` ## Module versions ```powershell ``` ## Debug output ``` ``` ## Error output ``` ```
Issue author: scottstout
Assignees: -
Milestone: -

msJinLei commented 3 years ago

@scottstout could you provide the following information, thanks

Environment data

Please run $PSVersionTable and paste the output in the below code block If running the Docker container image, indicate the tag of the image used and the version of Docker engine

Module versions

Please run (Get-Module -ListAvailable) and paste the output in the below code block

Debug output

Set $DebugPreference='Continue' before running the repro and paste the resulting debug stream in the below code block

Error output

Please run Resolve-AzError and paste the output in the below code block

jberry777 commented 2 years ago

I'm also encountering this. I'm using a PowerShell session from inside the Azure portal.

I created a new custom role using New-AzRoleDefinition -Role $role Made a note of the output which included the ID value. Then I tried updating the custom role's AssignableScopes value from subscription to a management group using the management group ID with Set-AzRoleDefinition -Role $role This returned an error line: Set-AzRoleDefinition: Cannot find role definition with id '<customRoleID>'

I was following the documentation provided here when attempting to create and update custom roles: https://docs.microsoft.com/en-us/azure/role-based-access-control/custom-roles-powershell#update-a-custom-role-with-the-psroledefinition-object

Environment data: (output from $PSVersionTable)

Name                           Value
----                           -----
PSVersion                      7.2.4
PSEdition                      Core
GitCommitId                    7.2.4
OS                             Linux 5.4.0-1080-azure #83~18.04.2-Ubuntu SMP Thu May 19 18:52:16 UTC 2022
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Module versions: (output from (Get-Module -ListAvailable)

Directory: /usr/local/share/powershell/Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Script     8.0.0                 Az                                  Core,Desk 
Script     2.8.0                 Az.Accounts                         Core,Desk {Disable-AzDataCollection, Disable-AzContextAutosave, Enable-AzDataCollection…
Script     1.1.2                 Az.Advisor                          Core,Desk {Get-AzAdvisorRecommendation, Enable-AzAdvisorRecommendation, Disable-AzAdvis…
Script     4.1.0                 Az.Aks                              Core,Desk {Get-AzAksCluster, New-AzAksCluster, Remove-AzAksCluster, Import-AzAksCredent…
Script     1.1.4                 Az.AnalysisServices                 Core,Desk {Resume-AzAnalysisServicesServer, Suspend-AzAnalysisServicesServer, Get-AzAna…
Script     3.0.0                 Az.ApiManagement                    Core,Desk {Add-AzApiManagementApiToGateway, Add-AzApiManagementApiToProduct, Add-AzApiM…
Script     1.1.0                 Az.AppConfiguration                 Core,Desk {Get-AzAppConfigurationStore, Get-AzAppConfigurationStoreKey, New-AzAppConfig…
Script     2.0.0                 Az.ApplicationInsights              Core,Desk {Get-AzApplicationInsights, Get-AzApplicationInsightsApiKey, Get-AzApplicatio…
Script     1.0.0                 Az.Attestation                      Core,Desk {New-AzAttestation, Get-AzAttestation, Remove-AzAttestation, Get-AzAttestatio…
Script     1.7.3                 Az.Automation                       Core,Desk {Get-AzAutomationHybridWorkerGroup, Remove-AzAutomationHybridWorkerGroup, Get…
Script     3.2.0                 Az.Batch                            Core,Desk {Remove-AzBatchAccount, Get-AzBatchAccount, Get-AzBatchAccountKey, New-AzBatc…
Script     2.0.0                 Az.Billing                          Core,Desk {Get-AzBillingInvoice, Get-AzBillingPeriod, Get-AzEnrollmentAccount, Get-AzCo…
Script     2.1.0                 Az.Cdn                              Core,Desk {Clear-AzCdnEndpointContent, Clear-AzFrontDoorCdnEndpointContent, Disable-AzC…
Script     1.1.0                 Az.CloudService                     Core,Desk {Get-AzCloudService, Get-AzCloudServiceInstanceView, Get-AzCloudServiceNetwor…
Script     1.11.0                Az.CognitiveServices                Core,Desk {Get-AzCognitiveServicesAccount, Get-AzCognitiveServicesAccountKey, Get-AzCog…
Script     4.27.0                Az.Compute                          Core,Desk {Remove-AzAvailabilitySet, Get-AzAvailabilitySet, New-AzAvailabilitySet, Upda…
Script     3.1.0                 Az.ContainerInstance                Core,Desk {Add-AzContainerInstanceOutput, Get-AzContainerGroup, Get-AzContainerInstance…
Script     3.0.0                 Az.ContainerRegistry                Core,Desk {New-AzContainerRegistry, Get-AzContainerRegistry, Update-AzContainerRegistry…
Script     1.8.0                 Az.CosmosDB                         Core,Desk {Get-AzCosmosDBSqlContainer, Get-AzCosmosDBSqlContainerThroughput, Get-AzCosm…
Script     1.1.0                 Az.DataBoxEdge                      Core,Desk {Get-AzDataBoxEdgeJob, Get-AzDataBoxEdgeDevice, Invoke-AzDataBoxEdgeDevice, N…
Script     1.2.0                 Az.Databricks                       Core,Desk {Get-AzDatabricksOutboundNetworkDependenciesEndpoint, Get-AzDatabricksVNetPee…
Script     1.16.7                Az.DataFactory                      Core,Desk {Set-AzDataFactoryV2, Update-AzDataFactoryV2, Get-AzDataFactoryV2, Remove-AzD…
Script     1.0.2                 Az.DataLakeAnalytics                Core,Desk {Get-AzDataLakeAnalyticsDataSource, New-AzDataLakeAnalyticsCatalogCredential,…
Script     1.3.0                 Az.DataLakeStore                    Core,Desk {Get-AzDataLakeStoreTrustedIdProvider, Remove-AzDataLakeStoreTrustedIdProvide…
Script     1.0.1                 Az.DataShare                        Core,Desk {New-AzDataShareAccount, Get-AzDataShareAccount, Remove-AzDataShareAccount, N…
Script     1.1.0                 Az.DeploymentManager                Core,Desk {Get-AzDeploymentManagerArtifactSource, New-AzDeploymentManagerArtifactSource…
Script     3.1.0                 Az.DesktopVirtualization            Core,Desk {Disconnect-AzWvdUserSession, Expand-AzWvdMsixImage, Get-AzWvdApplication, Ge…
Script     1.0.2                 Az.DevTestLabs                      Core,Desk {Get-AzDtlAllowedVMSizesPolicy, Get-AzDtlAutoShutdownPolicy, Get-AzDtlAutoSta…
Script     1.1.2                 Az.Dns                              Core,Desk {Get-AzDnsRecordSet, New-AzDnsRecordConfig, Remove-AzDnsRecordSet, Set-AzDnsR…
Script     1.3.0                 Az.EventGrid                        Core,Desk {New-AzEventGridTopic, Get-AzEventGridTopic, Set-AzEventGridTopic, New-AzEven…
Script     2.0.0                 Az.EventHub                         Core,Desk {New-AzEventHubNamespace, Get-AzEventHubNamespace, Set-AzEventHubNamespace, R…
Script     1.9.0                 Az.FrontDoor                        Core,Desk {New-AzFrontDoor, Get-AzFrontDoor, Set-AzFrontDoor, Remove-AzFrontDoor…}
Script     4.0.3                 Az.Functions                        Core,Desk {Get-AzFunctionApp, Get-AzFunctionAppAvailableLocation, Get-AzFunctionAppPlan…
Script     0.10.8                Az.GuestConfiguration               Core,Desk {Get-AzVMGuestPolicyStatus, Get-AzVMGuestPolicyStatusHistory}
Script     5.0.1                 Az.HDInsight                        Core,Desk {Get-AzHDInsightJob, New-AzHDInsightSqoopJobDefinition, Wait-AzHDInsightJob, …
Script     2.0.0                 Az.HealthcareApis                   Core,Desk {Get-AzHealthcareApisService, Get-AzHealthcareApisWorkspace, Get-AzHealthcare…
Script     2.7.4                 Az.IotHub                           Core,Desk {Add-AzIotHubKey, Get-AzIotHubEventHubConsumerGroup, Get-AzIotHubConnectionSt…
Script     4.5.0                 Az.KeyVault                         Core,Desk {Add-AzKeyVaultCertificate, Update-AzKeyVaultCertificate, Stop-AzKeyVaultCert…
Script     2.1.0                 Az.Kusto                            Core,Desk {Add-AzKustoClusterLanguageExtension, Add-AzKustoDatabasePrincipal, Get-AzKus…
Script     1.5.0                 Az.LogicApp                         Core,Desk {Get-AzIntegrationAccountAgreement, Get-AzIntegrationAccountAssembly, Get-AzI…
Script     1.1.3                 Az.MachineLearning                  Core,Desk {Move-AzMlCommitmentAssociation, Get-AzMlCommitmentAssociation, Get-AzMlCommi…
Script     1.2.0                 Az.Maintenance                      Core,Desk {Get-AzApplyUpdate, Get-AzConfigurationAssignment, Get-AzMaintenanceConfigura…
Script     1.0.0                 Az.ManagedServiceIdentity           Core,Desk {Get-AzSystemAssignedIdentity, Get-AzUserAssignedIdentity, New-AzUserAssigned…
Script     3.0.0                 Az.ManagedServices                  Core,Desk {Get-AzManagedServicesAssignment, Get-AzManagedServicesDefinition, Get-AzMana…
Script     1.0.2                 Az.MarketplaceOrdering              Core,Desk {Get-AzMarketplaceTerms, Set-AzMarketplaceTerms}
Script     1.1.1                 Az.Media                            Core,Desk {Sync-AzMediaServiceStorageKey, Set-AzMediaServiceKey, Get-AzMediaServiceKey,…
Script     1.1.2                 Az.Migrate                          Core,Desk {Get-AzMigrateDiscoveredServer, Get-AzMigrateJob, Get-AzMigrateProject, Get-A…
Script     3.0.1                 Az.Monitor                          Core,Desk {Get-AzMetricDefinition, Get-AzMetric, Remove-AzLogProfile, Get-AzLogProfile…}
Script     1.0.0                 Az.MySql                            Core,Desk {Get-AzMySqlConfiguration, Get-AzMySqlConnectionString, Get-AzMySqlFirewallRu…
Script     4.17.0                Az.Network                          Core,Desk {Add-AzApplicationGatewayAuthenticationCertificate, Get-AzApplicationGatewayA…
Script     1.1.1                 Az.NotificationHubs                 Core,Desk {Get-AzNotificationHub, Get-AzNotificationHubAuthorizationRule, Get-AzNotific…
Script     3.1.0                 Az.OperationalInsights              Core,Desk {New-AzOperationalInsightsAzureActivityLogDataSource, New-AzOperationalInsigh…
Script     1.5.0                 Az.PolicyInsights                   Core,Desk {Get-AzPolicyEvent, Get-AzPolicyState, Get-AzPolicyStateSummary, Get-AzPolicy…
Script     1.1.0                 Az.PostgreSql                       Core,Desk {Get-AzPostgreSqlConfiguration, Get-AzPostgreSqlConnectionString, Get-AzPostg…
Script     1.1.2                 Az.PowerBIEmbedded                  Core,Desk {Remove-AzPowerBIWorkspaceCollection, Get-AzPowerBIWorkspaceCollection, Get-A…
Script     1.0.3                 Az.PrivateDns                       Core,Desk {Get-AzPrivateDnsZone, Remove-AzPrivateDnsZone, Set-AzPrivateDnsZone, New-AzP…
Script     5.4.0                 Az.RecoveryServices                 Core,Desk {Get-AzRecoveryServicesBackupProperty, Get-AzRecoveryServicesVault, Get-AzRec…
Script     1.6.0                 Az.RedisCache                       Core,Desk {Remove-AzRedisCachePatchSchedule, New-AzRedisCacheScheduleEntry, Get-AzRedis…
Script     1.0.0                 Az.RedisEnterpriseCache             Core,Desk {Export-AzRedisEnterpriseCache, Get-AzRedisEnterpriseCache, Get-AzRedisEnterp…
Script     1.0.3                 Az.Relay                            Core,Desk {New-AzRelayNamespace, Get-AzRelayNamespace, Set-AzRelayNamespace, Remove-AzR…
Script     1.1.0                 Az.ResourceMover                    Core,Desk {Add-AzResourceMoverMoveResource, Get-AzResourceMoverMoveCollection, Get-AzRe…
Script     6.0.0                 Az.Resources                        Core,Desk {Get-AzProviderOperation, Remove-AzRoleAssignment, Get-AzRoleAssignment, New-…
Script     1.3.0                 Az.Security                         Core,Desk {Get-AzSecuritySolution, Get-AzSecuritySolutionsReferenceData, New-AzAlertsSu…
Script     1.1.0                 Az.SecurityInsights                 Core,Desk {Get-AzSentinelAlertRuleAction, New-AzSentinelAlertRuleAction, Remove-AzSenti…
Script     1.9.0                 Az.ServiceBus                       Core,Desk {New-AzServiceBusNamespace, Get-AzServiceBusNamespace, Set-AzServiceBusNamesp…
Script     3.0.2                 Az.ServiceFabric                    Core,Desk {Add-AzServiceFabricClientCertificate, Add-AzServiceFabricNode, Add-AzService…
Script     1.4.1                 Az.SignalR                          Core,Desk {New-AzSignalR, Get-AzSignalR, Get-AzSignalRKey, New-AzSignalRKey…}
Script     3.9.0                 Az.Sql                              Core,Desk {Get-AzSqlDatabaseTransparentDataEncryption, Get-AzSqlDatabaseTransparentData…
Script     1.1.0                 Az.SqlVirtualMachine                Core,Desk {New-AzSqlVM, Get-AzSqlVM, Update-AzSqlVM, Remove-AzSqlVM…}
Script     1.1.1                 Az.StackHCI                         Core,Desk {Register-AzStackHCI, Unregister-AzStackHCI, Test-AzStackHCIConnection, Set-A…
Script     4.6.0                 Az.Storage                          Core,Desk {Get-AzStorageAccount, Get-AzStorageAccountKey, New-AzStorageAccount, New-AzS…
Script     1.7.0                 Az.StorageSync                      Core,Desk {Invoke-AzStorageSyncCompatibilityCheck, New-AzStorageSyncService, Get-AzStor…
Script     2.0.0                 Az.StreamAnalytics                  Core,Desk {Get-AzStreamAnalyticsCluster, Get-AzStreamAnalyticsClusterStreamingJob, Get-…
Script     1.0.0                 Az.Support                          Core,Desk {Get-AzSupportService, Get-AzSupportProblemClassification, Get-AzSupportTicke…
Script     1.4.0                 Az.Synapse                          Core,Desk {Get-AzSynapseSparkJob, Stop-AzSynapseSparkJob, Submit-AzSynapseSparkJob, Wai…
Script     1.1.0                 Az.TrafficManager                   Core,Desk {Add-AzTrafficManagerCustomHeaderToEndpoint, Remove-AzTrafficManagerCustomHea…
Script     2.11.2                Az.Websites                         Core,Desk {Get-AzAppServicePlan, Set-AzAppServicePlan, New-AzAppServicePlan, Remove-AzA…
Script     0.0.0.10              AzureAD.Standard.Preview            Desk      {Get-AzureADDeviceRegisteredUser, Get-AzureADApplicationServiceEndpoint, Get-…
Script     0.9.3                 AzurePSDrive                        Desk      
Script     17.0.4716…            EXOPSSessionConnector               Desk      Connect-EXOPSSession
Binary     0.1.1                 Microsoft.PowerShell.UnixCompleters Core      {Import-UnixCompleters, Remove-UnixCompleters, Set-UnixCompleter}
Manifest   1.2.1077              MicrosoftPowerBIMgmt                Desk      
Binary     1.2.1077              MicrosoftPowerBIMgmt.Admin          Desk      {Add-PowerBIEncryptionKey, Get-PowerBIEncryptionKey, Get-PowerBIWorkspaceEncr…
Binary     1.2.1077              MicrosoftPowerBIMgmt.Capacities     Desk      Get-PowerBICapacity
Binary     1.2.1077              MicrosoftPowerBIMgmt.Data           Desk      {Add-PowerBIDataset, Set-PowerBITable, New-PowerBIDataset, New-PowerBITable…}
Binary     1.2.1077              MicrosoftPowerBIMgmt.Profile        Desk      {Connect-PowerBIServiceAccount, Disconnect-PowerBIServiceAccount, Invoke-Powe…
Binary     1.2.1077              MicrosoftPowerBIMgmt.Reports        Desk      {Get-PowerBIReport, New-PowerBIReport, Export-PowerBIReport, Get-PowerBIDashb…
Binary     1.2.1077              MicrosoftPowerBIMgmt.Workspaces     Desk      {Get-PowerBIWorkspace, Get-PowerBIWorkspaceMigrationStatus, Add-PowerBIWorksp…
Script     4.3.0                 MicrosoftTeams                      Core,Desk {Add-TeamChannelUser, Add-TeamUser, Connect-MicrosoftTeams, Disconnect-Micros…
Script     0.9.3                 PSCloudShellUtility                 Desk      {Enter-AzVM, Get-AzCommand, Invoke-AzVMCommand, Enable-AzVMPSRemoting…}
Binary     0.8.1                 SHiPS                               Desk      
Script     21.1.18256            SqlServer                           Desk      {Add-RoleMember, Add-SqlAvailabilityDatabase, Add-SqlAvailabilityGroupListene…

    Directory: /opt/microsoft/powershell/7/Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Manifest   1.2.5                 Microsoft.PowerShell.Archive        Desk      {Compress-Archive, Expand-Archive}
Manifest   7.0.0.0               Microsoft.PowerShell.Host           Core      {Start-Transcript, Stop-Transcript}
Manifest   7.0.0.0               Microsoft.PowerShell.Management     Core      {Add-Content, Clear-Content, Clear-ItemProperty, Join-Path…}
Manifest   7.0.0.0               Microsoft.PowerShell.Security       Core      {Get-Credential, Get-ExecutionPolicy, Set-ExecutionPolicy, ConvertFrom-Secure…
Manifest   7.0.0.0               Microsoft.PowerShell.Utility        Core      {Export-Alias, Get-Alias, Import-Alias, New-Alias…}
Script     1.4.7                 PackageManagement                   Desk      {Find-Package, Get-Package, Get-PackageProvider, Get-PackageSource…}
Script     2.2.5                 PowerShellGet                       Desk      {Find-Command, Find-DSCResource, Find-Module, Find-RoleCapability…}
Script     2.1.0                 PSReadLine                          Desk      {Get-PSReadLineKeyHandler, Set-PSReadLineKeyHandler, Remove-PSReadLineKeyHand…
Binary     2.0.3                 ThreadJob                           Desk      Start-ThreadJob

Debug output: (from $DebugPreference='Continue')

PS /home/lhtestuser> $role = Get-AzRoleDefinition "Lighthouse Monitor"
DEBUG: 6:36:02 PM - GetAzureRoleDefinitionCommand begin processing with ParameterSet 'RoleDefinitionNameParameterSet'.
DEBUG: 6:36:02 PM - using account id 'MSI@50342'...
DEBUG: 6:36:02 PM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: [Common.Authentication]: Authenticating using Account: 'MSI@50342', environment: 'AzureCloud', tenant: '78985729-1ae1-redacted'
DEBUG: 6:36:02 PM - [ManagedServiceIdentityAuthenticator] Calling ManagedIdentityCredential.GetTokenAsync - TenantId:'78985729-1ae1-redacted', Scopes:'https://graph.microsoft.com/', UserId:''
DEBUG: ManagedIdentityCredential.GetToken invoked. Scopes: [ https://graph.microsoft.com/ ] ParentRequestId: 
DEBUG: Request [da3e5a01-8c7b-4803-9692-da6b84c1632e] POST http://localhost:50342/oauth2/token
Metadata:REDACTED
x-ms-client-request-id:da3e5a01-8c7b-4803-9692-da6b84c1632e
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.6.0,(.NET 6.0.5; Linux 5.4.0-1080-azure #83~18.04.2-Ubuntu SMP Thu May 19 18:52:16 UTC 2022)
Content-Type:application/x-www-form-urlencoded
client assembly: Azure.Identity
DEBUG: Response [da3e5a01-8c7b-4803-9692-da6b84c1632e] 200 OK (01.1s)
X-Powered-By:REDACTED
ETag:W/"8fe-dvtrYKUwFRKiyZbqN/PELfyg2MM"
Date:Wed, 08 Jun 2022 18:36:03 GMT
Connection:keep-alive
Content-Type:application/json; charset=utf-8
Content-Length:2302

DEBUG: ManagedIdentityCredential.GetToken succeeded. Scopes: [ https://graph.microsoft.com/ ] ParentRequestId:  ExpiresOn: 2022-06-08T19:22:00.0000000+00:00
DEBUG: [Common.Authentication]: Received token with LoginType 'User', Tenant: '78985729-1ae1-redacted', UserId: 'MSI@50342'
DEBUG: [Common.Authentication]: Authenticating using Account: 'MSI@50342', environment: 'AzureCloud', tenant: '78985729-1ae1-redacted'
DEBUG: 6:36:03 PM - [ManagedServiceIdentityAuthenticator] Calling ManagedIdentityCredential.GetTokenAsync - TenantId:'78985729-1ae1-redacted', Scopes:'https://management.core.windows.net/', UserId:''
DEBUG: ManagedIdentityCredential.GetToken invoked. Scopes: [ https://management.core.windows.net/ ] ParentRequestId: 
DEBUG: Request [789f2ceb-594d-498b-8b20-18c17889c852] POST http://localhost:50342/oauth2/token
Metadata:REDACTED
x-ms-client-request-id:789f2ceb-594d-498b-8b20-18c17889c852
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.6.0,(.NET 6.0.5; Linux 5.4.0-1080-azure #83~18.04.2-Ubuntu SMP Thu May 19 18:52:16 UTC 2022)
Content-Type:application/x-www-form-urlencoded
client assembly: Azure.Identity
DEBUG: Response [789f2ceb-594d-498b-8b20-18c17889c852] 200 OK (00.0s)
X-Powered-By:REDACTED
ETag:W/"7b5-JsOkO+yzWATAaEWu5Nz1ar/Ldb8"
Date:Wed, 08 Jun 2022 18:36:03 GMT
Connection:keep-alive
Content-Type:application/json; charset=utf-8
Content-Length:1973

DEBUG: ManagedIdentityCredential.GetToken succeeded. Scopes: [ https://management.core.windows.net/ ] ParentRequestId:  ExpiresOn: 2022-06-08T19:18:46.0000000+00:00
DEBUG: [Common.Authentication]: Received token with LoginType 'User', Tenant: '78985729-1ae1-redacted', UserId: 'MSI@50342'
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

Absolute Uri:
https://management.azure.com//subscriptions/9a5b9b40-0f4b-redacted/providers/Microsoft.Authorization/roleDefinitions?$filter=roleName eq 'Lighthouse Monitor'&api-version=2018-01-01-preview

Headers:
x-ms-client-request-id        : 5d57b5c1-f4d2-4484-8663-cbc80c146ccf
Accept-Language               : en-US

Body:

DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
OK

Headers:
Cache-Control                 : no-cache
Pragma                        : no-cache
x-ms-request-id               : 4b0ae265-8f80-4ac1-ae08-479a9952cf59
X-Content-Type-Options        : nosniff
Strict-Transport-Security     : max-age=31536000; includeSubDomains
Set-Cookie                    : x-ms-gateway-slice=Production; path=/; secure; samesite=none; httponly
x-ms-ratelimit-remaining-subscription-reads: 11999
x-ms-correlation-request-id   : e5711518-0742-45a0-aee7-ee7b62331654
x-ms-routing-request-id       : WESTUS:20220608T183603Z:e5711518-0742-45a0-aee7-ee7b62331654
Date                          : Wed, 08 Jun 2022 18:36:03 GMT

Body:
{
  "value": [
    {
      "properties": {
        "roleName": "Lighthouse Monitor",
        "type": "CustomRole",
        "description": "Enroll subscriptions into Azure Lighthouse.",
        "assignableScopes": [
          "/subscriptions/9a5b9b40-0f4b-redacted"
        ],
        "permissions": [
          {
            "actions": [
              "*/read",
              "Microsoft.Authorization/operations/*",
              "Microsoft.Authorization/permissions/*",
              "Microsoft.Authorization/roleAssignments/*",
              "Microsoft.Authorization/roleDefinitions/*",
              "Microsoft.Resources/deployments/*",
              "Microsoft.ManagedServices/*"
            ],
            "notActions": [],
            "dataActions": [],
            "notDataActions": []
          }
        ],
        "createdOn": "2022-06-08T17:18:10.2277126Z",
        "updatedOn": "2022-06-08T17:18:10.2277126Z",
        "createdBy": "1887be4b-1256-42c2-9f62-e49961c70e47",
        "updatedBy": "1887be4b-1256-42c2-9f62-e49961c70e47"
      },
      "id": "/subscriptions/9a5b9b40-0f4b-redacted/providers/Microsoft.Authorization/roleDefinitions/2cc0431e-de00-4ce6-8da2-15ef787ce539",
      "type": "Microsoft.Authorization/roleDefinitions",
      "name": "2cc0431e-de00-4ce6-8da2-15ef787ce539"
    }
  ]
}

DEBUG: 6:36:03 PM - [ConfigManager] Got [True] from [EnableDataCollection], Module = [], Cmdlet = [].
DEBUG: AzureQoSEvent: Module: Az.Resources:6.0.0; CommandName: Get-AzRoleDefinition; PSVersion: 7.2.4; IsSuccess: True; Duration: 00:00:01.3043144
DEBUG: Finish sending metric.
DEBUG: 6:36:03 PM - GetAzureRoleDefinitionCommand end processing.
PS /home/lhtestuser> $role.AssignableScopes = "/providers/Microsoft.Management/managementGroups/78985729-1ae1-redacted"
PS /home/lhtestuser> Set-AzRoleDefinition -Role $role
DEBUG: 6:37:51 PM - SetAzureRoleDefinitionCommand begin processing with ParameterSet 'RoleDefinitionParameterSet'.
DEBUG: 6:37:51 PM - using account id 'MSI@50342'...
DEBUG: 6:37:51 PM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: [Common.Authentication]: Authenticating using Account: 'MSI@50342', environment: 'AzureCloud', tenant: '78985729-1ae1-redacted'
DEBUG: 6:37:51 PM - [ManagedServiceIdentityAuthenticator] Calling ManagedIdentityCredential.GetTokenAsync - TenantId:'78985729-1ae1-redacted', Scopes:'https://graph.microsoft.com/', UserId:''
DEBUG: ManagedIdentityCredential.GetToken invoked. Scopes: [ https://graph.microsoft.com/ ] ParentRequestId: 
DEBUG: Request [f1e2edc4-3c85-4450-b175-14d024fb9697] POST http://localhost:50342/oauth2/token
Metadata:REDACTED
x-ms-client-request-id:f1e2edc4-3c85-4450-b175-14d024fb9697
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.6.0,(.NET 6.0.5; Linux 5.4.0-1080-azure #83~18.04.2-Ubuntu SMP Thu May 19 18:52:16 UTC 2022)
Content-Type:application/x-www-form-urlencoded
client assembly: Azure.Identity
DEBUG: Response [f1e2edc4-3c85-4450-b175-14d024fb9697] 200 OK (00.0s)
X-Powered-By:REDACTED
ETag:W/"8fe-5Np2FfUIvo0prSMfwBFXTRe3rSA"
Date:Wed, 08 Jun 2022 18:37:51 GMT
Connection:keep-alive
Content-Type:application/json; charset=utf-8
Content-Length:2302

DEBUG: ManagedIdentityCredential.GetToken succeeded. Scopes: [ https://graph.microsoft.com/ ] ParentRequestId:  ExpiresOn: 2022-06-08T19:22:00.0000000+00:00
DEBUG: [Common.Authentication]: Received token with LoginType 'User', Tenant: '78985729-1ae1-redacted', UserId: 'MSI@50342'
DEBUG: [Common.Authentication]: Authenticating using Account: 'MSI@50342', environment: 'AzureCloud', tenant: '78985729-1ae1-redacted'
DEBUG: 6:37:51 PM - [ManagedServiceIdentityAuthenticator] Calling ManagedIdentityCredential.GetTokenAsync - TenantId:'78985729-1ae1-redacted', Scopes:'https://management.core.windows.net/', UserId:''
DEBUG: ManagedIdentityCredential.GetToken invoked. Scopes: [ https://management.core.windows.net/ ] ParentRequestId: 
DEBUG: Request [9a54b7a3-3389-42c3-873b-81b47ae45dd4] POST http://localhost:50342/oauth2/token
Metadata:REDACTED
x-ms-client-request-id:9a54b7a3-3389-42c3-873b-81b47ae45dd4
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.6.0,(.NET 6.0.5; Linux 5.4.0-1080-azure #83~18.04.2-Ubuntu SMP Thu May 19 18:52:16 UTC 2022)
Content-Type:application/x-www-form-urlencoded
client assembly: Azure.Identity
DEBUG: Response [9a54b7a3-3389-42c3-873b-81b47ae45dd4] 200 OK (00.0s)
X-Powered-By:REDACTED
ETag:W/"7b5-s25IC66RGiWHExh60exK/72MMA4"
Date:Wed, 08 Jun 2022 18:37:51 GMT
Connection:keep-alive
Content-Type:application/json; charset=utf-8
Content-Length:1973

DEBUG: ManagedIdentityCredential.GetToken succeeded. Scopes: [ https://management.core.windows.net/ ] ParentRequestId:  ExpiresOn: 2022-06-08T19:18:46.0000000+00:00
DEBUG: [Common.Authentication]: Received token with LoginType 'User', Tenant: '78985729-1ae1-redacted', UserId: 'MSI@50342'
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

Absolute Uri:
https://management.azure.com//providers/Microsoft.Management/managementGroups/78985729-1ae1-redacted/providers/Microsoft.Authorization/roleDefinitions/2cc0431e-de00-4ce6-8da2-15ef787ce539?api-version=2018-01-01-preview

Headers:
x-ms-client-request-id        : 4b35ec9f-252e-48c1-9512-c3bd55cb2b59
Accept-Language               : en-US

Body:

DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
NotFound

Headers:
Cache-Control                 : no-cache
Pragma                        : no-cache
x-ms-request-id               : bbd1745b-5959-4ef3-88e1-d9fbd1a10fd7
X-Content-Type-Options        : nosniff
Strict-Transport-Security     : max-age=31536000; includeSubDomains
Set-Cookie                    : x-ms-gateway-slice=Production; path=/; secure; samesite=none; httponly
x-ms-ratelimit-remaining-tenant-reads: 11999
x-ms-correlation-request-id   : c6f37078-22d9-41b2-b527-ded77f0607b0
x-ms-routing-request-id       : WESTUS:20220608T183751Z:c6f37078-22d9-41b2-b527-ded77f0607b0
Date                          : Wed, 08 Jun 2022 18:37:51 GMT

Body:
{
  "error": {
    "code": "RoleDefinitionDoesNotExist",
    "message": "The specified role definition with ID '2cc0431e-de00-4ce6-8da2-15ef787ce539' does not exist."
  }
}

DEBUG: 6:37:51 PM - [ConfigManager] Got [True] from [EnableDataCollection], Module = [], Cmdlet = [].
Set-AzRoleDefinition: Cannot find role definition with id '2cc0431e-de00-4ce6-8da2-15ef787ce539'.
DEBUG: 6:37:51 PM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: AzureQoSEvent: Module: Az.Resources:6.0.0; CommandName: Set-AzRoleDefinition; PSVersion: 7.2.4; IsSuccess: False; Duration: 00:00:00.1944423; Exception: Cannot find role definition with id '2cc0431e-de00-4ce6-8da2-15ef787ce539'.;
DEBUG: Finish sending metric.
DEBUG: 6:37:51 PM - SetAzureRoleDefinitionCommand end processing.

Error output: (from Resolve-AzError)

DEBUG: 6:38:09 PM - ResolveError begin processing with ParameterSet 'AnyErrorParameterSet'.
DEBUG: 6:38:09 PM - using account id 'MSI@50342'...
DEBUG: 6:38:09 PM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
WARNING: Upcoming breaking changes in the cmdlet 'Resolve-AzError' :
The `Resolve-Error` alias will be removed in a future release.  Please change any scripts that use this alias to use `Resolve-AzError` instead.
Note : Go to https://aka.ms/azps-changewarnings for steps to suppress this breaking change warning, and other information on breaking changes in Azure PowerShell.

   HistoryId: 5

Message        : Cannot find role definition with id '2cc0431e-de00-4ce6-8da2-15ef787ce539'.
StackTrace     :    at Microsoft.Azure.Commands.Resources.Models.Authorization.AuthorizationClient.UpdateRoleDefinition(PSRoleDefinition roleDefinition)
                    at Microsoft.Azure.Commands.Resources.SetAzureRoleDefinitionCommand.ExecuteCmdlet()
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.<>c__3`1.<ExecuteSynchronouslyOrAsJob>b__3_0(T c)
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet, Action`1 executor)
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet)
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
Exception      : System.Collections.Generic.KeyNotFoundException
InvocationInfo : {Set-AzRoleDefinition}
Line           : Set-AzRoleDefinition -Role $role
Position       : At line:1 char:1
                 + Set-AzRoleDefinition -Role $role
                 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistoryId      : 5

The Azure PowerShell team is listening, please let us know how we are doing: https://aka.ms/azpssurvey?Q_CHL=ERROR.

DEBUG: 6:38:09 PM - [ConfigManager] Got [True] from [EnableDataCollection], Module = [], Cmdlet = [].
DEBUG: AzureQoSEvent: Module: Az.Accounts:2.8.0; CommandName: Resolve-AzError; PSVersion: 7.2.4; IsSuccess: True; Duration: 00:00:00.0164312
DEBUG: Finish sending metric.
DEBUG: 6:38:09 PM - ResolveError end processing.
jberry777 commented 2 years ago

Updating the custom role with a management group by overwriting the existing subscription value fails. However, adding a management group ID to the AssignableScopes array instead succeeds. Its effect is untested so it's unclear if this will work as intended. $role.AssignableScopes.Add(<managementGroupID>) instead of $role.AssignableScopes = <managementGroupID>