Assignment scopes and excluded scopes

  • CSV Assignment Parameters
  • Policy Exemptions

Policy Assignments

This chapter describes how Policy Assignments are handled by EPAC. Policy Assignments are the actual assignments of Policies and Policy Sets to scopes in Azure

Assignment JSON structure

Assignment JSON is hierarchical for efficient definitions, avoiding duplication (copy/paste) of JSON. Each branch of the tree is cumulative. Each tree node must include a nodeName - an arbitrary string exclusively used by EPAC to display an error location. EPAC concatenates a leading / and the nodeName entries encountered in the tree to create a "breadcrumbs" trail; therefore, we recommend that you use / to help separate the concatenated nodeName . The following partial and invalid assignment tree would create this error message.

Assignment File Overview Diagram

JSON Schema

The GitHub repo contains a JSON schema which can be used in tools such as VS Code to provide code completion.

To utilize the schema add a $schema tag to the JSON file.

  • Every tree branch must accumulate a definitionEntry (or definitionEntryList ), Assignment naming ( name and displayName ) and scope element.
  • The elements parameters , overrides , resourceSelectors , notScope , enforcementMode , metadata , userAssignedIdentity , managedIdentityLocations , additionalRoleAssignments and nonComplianceMessages are optional.
  • For Policy Sets with large numbers of included Policies you should use a spreadsheet (CSV file) to manage effects (parameterized or effect overrides ), parameters and optional nonComplianceMessages . We recommend the CSV approach for Policy Sets with more than 10 included Policies.
  • EPAC continues to support deprecated elements initiativeId , initiativeName and ignoreBranch , Consider using their replacements policySetId , policySetName and enforcementMode instead.
  • Role Assignments for user-assigned Managed Identities (UAMI) are not managed by EPAC, and will not generate a roles-plan.json file.
  • additionalRoleAssignments are used when a resource required is not in the current scope. For example, a Policy Assignment that requires a Event Hub to be managed in a subscription not contained in the current management group.

The tree is not required to be balanced. The number of levels is not restricted; however, anything beyond 3 levels is unnecessary in real scenarios and would be difficult to read and manage as the depth increases.

Assignment Element and Metadata

Each Assignment is required to have a name which is used in it's resource id. EPAC also requires a displayName . The description is optional. For the allowed location assignment you specify the component with:

Multiple assignment naming components in a tree branch are string concatenated for each of the three fields.

Azure has a limit of 24 characters for the concatenated name string. EPAC displays an error if this limit is exceeded. Azure also has a limit of 128 characters for displayName and 512 characters for description (For additional information see Assignment Structure: Display name and description ).

Defining metadata

metadata is sometimes used to assign categories for changes. Do NOT specify EPAC-reserved elements roles and pacOwnerId . For the final metadata EPAC creates the union of instances in the entire tree branch.

Not recommended : Adding assignedBy to the metadata overrides the deployedBy value from the global-settings.jsonc file normally used for assignedBy . It defaults to "epac/$pacOwnerId/$pacSelector" .

Metadata for Role Assignments

Role assignments do not contain a metadata field. Instead, the description field is used to populate the deployedBy value. The description field is populated with the Policy Assignment Id, reason and deployedBy value. This is useful for tracking the source of the Role Assignment.

Reasons is one of:

  • Role Assignment required by Policy - Policy definition(s) specify the required Role Definition Ids.
  • additional Role Assignment - from filed "additionalRoleAssignments" in the Policy Assignment file.
  • additional cross tenant Role Assignment - from filed "additionalRoleAssignments" with crossTenant set to $true in the Policy Assignment file.

Assigning Policy Sets or Policies

Assigning a single policy or policy set.

Each assignment assigns either a Policy or Policy Set. In EPAC this is done with a definitionEntry or a definitionEntryList . Exactly one occurrence must exist in any collated tree branch. For each entry, you need to specify one of the following:

  • policyName - custom Policy. Specifying just the name allows EPAC to inject the correct definition scope.
  • policySetName - custom Policy Set. Specifying just the name allows EPAC to inject the correct definition scope
  • policyId - resource id for builtin Policy.
  • policySetId - resource id for builtin Policy Set.

displayName is an optional field to document the entry if the Policy name is a GUID. Builtin Policies and Policy Sets use a GUID.

Assigning multiple Policies or Policy Sets

Using definitionEntryList allows you to save on copy/paste tree branches. Without it, the number of branches would need to be duplicated as many times as the list has entries.

Each entry in the list creates an Assignment at each leaf of the tree. Since assignments must have unique names at a specific scope, the Assignment naming component must be amended for each list entry. In this sub-component you can decide if you want to concatenate the string by appending or prepending them by specifying append boolean value.

In the above example one of the children (leaf node) has the following Assignment name.

This example generates two assignments at the "prod" leaf per scope:

  • /providers/Microsoft.Management/managementGroups/ Contoso-Prod /providers/Microsoft.Authorization/policyAssignments/ pr-asb
  • displayName = "Prod Azure Security Benchmark"
  • description = "Prod Environment controls enforcement with Azure Security Benchmark Initiative."
  • /providers/Microsoft.Management/managementGroups/ Contoso-Prod /providers/Microsoft.Authorization/policyAssignments/ pr-nist-800-53-r5
  • displayName = "Prod NIST SP 800-53 Rev. 5"
  • description = "Prod Environment controls enforcement with NIST SP 800-53 Rev. 5 Initiative."

scope is required exactly once in each tree branch. Excluded scopes ( notScope ) are cumulative from global-settings.json and the entire tree branch; however, once a scope is defined notScope may not be defined at any child node.

Both scope and notScope are specific to an EPAC Environment using the pacSelector name , e.g., epac-dev and tenant .

notScope works the same. In addition "*" means all EPAC Environments.

Managed Identities and role assignments

Policies with a DeployIfNotExists or Modify effect need a Managed Identity (MI) and role assignments to execute remediation task. EPAC calculates the necessary role assignments based on the roleDefinitionIds in the Policy definition. By default EPAC uses a system-assigned Manged Identity. The team maintaining EPAC recommend system-assigned identities; however, your organization may have role assignment reasons to use user-assigned Managed Identities.

Defining managedIdentityLocations

Policy assignments requiring a Managed Identity (system-assigned or user-assigned) require a location managedIdentityLocations . You must specify the location based on EPAC Environment or use "*" to use the same location for all of the EPAC Environments. You can specify them in global-settings.jsonc or at any node in the tree. The last (closest to the leaf node) is the one chosen if multiple managedIdentityLocations entries are encountered in a tree branch.

Defining optional additionalRoleAssignments

In some scenarios you will need additionalRoleAssignments ; e.g., for diagnostics settings to Event Hubs, the target resource might be in a different Management Group and therefore the Managed Identity requires additional role assignments. You must specify the additionalRoleAssignments based on EPAC Environment or use "*" to use the same additionalRoleAssignments for all of the EPAC Environments. If the pacEnvironment under deployment is specified in the additionalRoleAssignments, the "*" assignments will be ignored.

If the additional assignment is to made to a managing tenant in the sceenario where the pacEnvironment under deployment is a manganged (lighthouse) tenant, you must specify ""crossTenant": true" for that assignment. Ensure all necessary ABAC permissions are in place for the executing SPN.

User-assigned Managed Identities

Azure Policy can use a user-defined Managed Identity and EPAC allows you to use this functionality. You must specify the user-defined Managed Identity based on EPAC Environment or use "*" to use the same identity for all of the EPAC Environments (only possible in single tenant scenarios). Within each EPAC Environment entry, you can specify just the URI string indicating to use the same identity even if we are using a definitionEntryList , or in the case of a definitionEntryList can assign a different identity based on the definitionEntryList by specifying a matching policyName , policyId , policySetName or policySetId .

Defining parameters , overrides and nonComplianceMessages

Utilizing a csv file to define parameters , overrides and noncompliancemessages.

Assigning single or multiple security and compliance focused Policy Sets (Initiatives), such as Microsoft cloud security benchmark, NIST 800-53 R5, PCI, NIST 800-171, etc, with just JSON parameters becomes very complex fast. Add to this the complexity of overriding the effect if it is not surfaced as a parameter in the Policy Set . Finally, adding the optional nonComplianceMessages further increases the complexity.

To address the problem of reading and maintaining hundreds or thousands of JSON lines, EPAC can use the content of a spreadsheet (CSV) to create parameters , overrides and optionally nonComplianceMessages for a single Policy assignment definitionEntry or multiple Policy definitions ( definitionEntryList ).

This approach is best for large Policy Sets such as Azure Security Benchmark, NIST 800-53, etc. Smaller Policy Sets should still be handled with JSON parameters , overrides and nonComplianceMessages .

Implement these steps as documented in Managing Policy Assignment Parameters with a CSV file .

  • Generate the CSV file form your already deployed Assignment(s) or Policy Set(s).
  • Modify the effect and parameter columns for each type of environment types you will use.
  • Modify the Policy Assignment file to reference the CSV file and the column prefix.
  • Update the CSV file with the new effect and parameter values.

Defining parameters with JSON

parameters have a simplified JSON structure. You do not need the additional value indirection Azure requests (EPAC will inject that indirection).

Too enable definitionEntryList , parameters not present in the Policy or Policy Set definition are quietly ignored.

Advanced Elements

Defining overrides with json.

overrides are in the same format as documented by Azure . They are cumulative in each tree branch. The selectors element is only used for Assignments of Policy Sets. They are not valid for Assignments of a single Policy.

If using definitionEntryList , you must add the policyName , policyId , policySetName or policySetId as used in the definitionEntryList item.

Defining nonComplianceMessages with JSON

Assign a non-compliance message to the assignment, or individual non-compliance messages if the assignment is for an Policy Set. This value is an array of objects - each containing a message, and in the case of an initiative a policyDefinitionReferenceId. See this link for details.

If you use single definitionEntry , place them normally. If you use a definitionEntryList place them in the respective list entry.

Defining resourceSelectors

resourceSelectors may appear anywhere in the tree and are cumulative in any branch. They follow the standard Azure Format .

Defining enforcementMode

enforcementMode is similar to the deprecated ignoreBranch ; it deploys the assignment and sets the assignment to Default or DoNotEnforce . DoNotEnforce allows a what-if analysis. enforcementMode may appear anywhere in the tree. Definitions at a child override the previous setting.

Example assignment files

Simple policy assignment (allowed locations).

In the simple case an assignment is a single node with no difference in assignment , parameters , and definitionEntry across multiple scopes. In many scenarios "Allowed Locations" is such a simple Assignment. Such Assignments do not have child nodes, just the root node. Example

  • nodeName is required for error messages; it's value is immaterial. EPAC concatenates them in the current tree branch.
  • definitionEntry specifies that the custom Policy Set general-allowed-locations-policy-set from our starter kit. displayName has no meaning - it is for readability and in this instance is superfluous.
  • assignment fields name , displayName and description are used when creating the assignment.
  • This assignment has no metadata . You don't need an empty collection. EPAC will add pacOwnerId and roles metadata . Do not add them manually.
  • enforcementMode is set to default - it is superfluous.
  • parameters are obvious. Note: you don't add the value layer Azure inserts - EPAC takes care of that.
  • During Policy resource development (called epac-dev ) the Assignment is deployed to an EPAC development Management Group Epac-Mg-1 .
  • During Policy prod deployments ( tenant -wide), it is deployed to the tenant Management Group Epac-Mg-1 .
  • No notScope entries are specified.

Security-Focused Policy Assignment with JSON parameters

  • In the following example we named our root node ( nodeName ) /security/ . Since it is only used in case of error messages produced by EPAC during planning it's actual value doesn't matter as long as it's unique.
  • We use a definitionEntryList to create two assignments at every leaf (six assignments total).
  • For assignment string concatenation we append the strings in the definitionEntryList to the strings in the child nodes. You can see this best when you look at the description string in the child nodes. It will form a sentence when concatenated by append ing the definitionEntryList assignment field description .
  • The parameters specified in the children are specific to the IaC environment types and their scope . Note: a real assignment would define many more parameters. The set here is abbreviated since the actual set could easily exceed a hundred entries for each of the IaC environments. We'll see in the next example how to simplify large Policy Set parameters with a CSV file.

Inverted Policy Assignment (Tag Inheritance and Required Tags)

As mentioned above sometimes it is advantageous (to reduce the number of repetitions) to turn a definition on its head:

  • Common parameters , scope , definitionEntryList (with two Policies) at the root ( nodeName is /Tags/ ).
  • Start of the assignment strings ( append is defaulted to false ). Again look at description which will be a concatenated sentence.
  • The children define the tagName parameter and the second part of the strings for assignment . The set of parameters is the union of the root node and the child node.
  • This creates six Assignments (number of Policies assigned times number of children).

Non-Compliance Messages in a Policy Definition Assignment

Non-compliance messages in a policy set definition assignment, non-compliance messages in a policy set definition assignment with a definitionentrylist.

Azure Greg

  • Live Stream Availability

policy assignments principal id

Bicep Access policies and Managed Identity

In this post I cover off access policies in KeyVault and also User Assigned Managed Identity using Bicep. If you are doing anything with Bicep then this is still the best resource I have found – https://github.com/Azure/ResourceModules/ – it shows you how to do it, but you need to figure it out from there but its still got a LOT of how to go about stuff in Bicep.

Access Policies in Bicep When you create a KeyVault you have to give people / accounts access to be able to use KeyValut in Azure. Within the portal you need to go to the following areas:-

policy assignments principal id

So in order to give applications and users access we add access policies. Now if you look up the Microsoft docs page for this, you’ll more than likely end up here:- https://docs.microsoft.com/en-us/azure/templates/microsoft.keyvault/vaults/accesspolicies?tabs=bicep

policy assignments principal id

This kind of page isn’t going to help you very much, infact its not going to help you. These types of pages in Microsoft docs are, I would say close to pointless to be honest. I found a page that you can compare it to that covers what I think we need to see more of in the way of docs when it comes to Microsoft docs. Compare the docs page to this wonderful blog post:- https://ochzhen.com/blog/key-vault-access-policies-using-azure-bicep

Its covering everything your ever going to need to know in a simple blog post which also has this layout:-

policy assignments principal id

Why is this so good im my opinion?, its telling me all about what I need to know about access policies, its explaining it all and has really useful samples – the docs need explanations and real world examples, the examples they give are normally far too basic imo. Managed Identity in Bicep First thing to say is that Managed Identity in Azure has its own are in the Azure Portal, wut? yeah its been here a while now 🙂

policy assignments principal id

Ok so you do you want to use a System assigned Managed Identity or a User Assigned Managed Identity? – Please, learn this by watching this video to learn about both – https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview

I always opt for User Assigned Managed Identity and I want to use this to access my Azure resources and I use this so that my nice new docker container which is now in container instances can make use of the User Assigned Managed Identity to go to keyvault and get secrets (as an example). So within my new User Assigned Managed Identity I can add Azure Role Assignments like so:-

policy assignments principal id

Here I am giving Owner rights on the Resource Group and KeyVault Admin access to my Managed Identity as examples.

What does this look like in Bicep? To create a User Assigned Managed Identity you can do it very easily :-

policy assignments principal id

And then to add Role Assignments and use existing definitions you can do the following:-

policy assignments principal id

Full code can be found here:- https://gist.github.com/gsuttie/3ab106252faf6ef7726441f70d611c7d

So there is an issue/bug with doing this, let me explain. In the example above I create a User Assigned Managed Identity and then add 2 Azure Role assignments to the managed identity. If i delete the managed Identity I end up with the following:-

policy assignments principal id

The roel assignment remains – meaning if I run my Bicep code again it wont work and gives me an error – something like this:- “RoleAssignmentUpdateNotPermitted”, “message”: “Tenant ID, application ID, principal ID, and scope are not allowed to be updated.” I hope this blog post makese sense and is helpful to someone. Don’t forget to subscribe to my   YouTube Channel .

Share this:

2 responses to bicep access policies and managed identity.

' src=

For a nice easy way to clean up the IAM after a managed identity has been removed check out https://jloudon.com/cloud/Removing-Unknown-Azure-RBAC-Role-Assignments-with-PowerShell/

[…] Bicep Access policies and Managed Identity (Gregor Suttie) […]

Leave a Reply Cancel reply

policy assignments principal id

  • Follow on Feedspot

policy assignments principal id

  • .Net Exams (2)
  • API Management (2)
  • Aspect Oriented Programming (3)
  • Azure (116)
  • Azure Exams (4)
  • AzureDevOps (31)
  • Best Practices (26)
  • Blogtober2018 (9)
  • Book Reviews (7)
  • Cloud Computing (15)
  • Community (6)
  • Continuous Deployment (8)
  • Dependency Injection (3)
  • Entity Framework (3)
  • Events (12)
  • ExpertsLiveEU (1)
  • GitHubActions (5)
  • Interview Questions (1)
  • JavaScript (3)
  • KnockoutJS (8)
  • Logic Apps (2)
  • Octopus Deploy (4)
  • Pluralsight (7)
  • PowerShell (8)
  • PowerToys (1)
  • Pro Tips (19)
  • Productivity (18)
  • RavenDB (20)
  • RedGate (8)
  • Serverless (1)
  • SignalR (4)
  • SlowCheetah (1)
  • SQL Server (1)
  • StudyGuides (1)
  • TeamCity (4)
  • Testing (5)
  • Training (44)
  • Uncategorized (48)
  • Visual Studio (1)

Certifications and Awards

This slideshow requires JavaScript.

Recent Posts

Azure Advisor workbook hidden gems

  • Implementing TDE in Azure SQL with Custom Managed Keys from Azure Key Vault 11 August 2024 1 Comment

Azure Spring Clean March 2024

Copyright © 2019-2024 Azure Greg | Powered by WordPress

Discover more from Azure Greg

Subscribe now to keep reading and get access to the full archive.

Type your email…

Continue reading

Azure Policy Assignment

This page shows how to write Terraform and Azure Resource Manager for Policy Assignment and write them securely.

Review your .tf file for Azure best practices

Shisho Cloud, our free checker to make sure your Terraform configuration follows best practices, is available (beta).

azurerm_resource_policy_assignment (Terraform)

The Assignment in Policy can be configured in Terraform with the resource name azurerm_resource_policy_assignment . The following sections describe 1 example of how to use the resource and its parameters.

  • Example Usage from GitHub

Review your Terraform file for Azure best practices

The following arguments are supported:

name - (Required) The name which should be used for this Policy Assignment. Changing this forces a new Resource Policy Assignment to be created.

policy_definition_id - (Required) The ID of the Policy Definition or Policy Definition Set. Changing this forces a new Policy Assignment to be created.

resource_id - (Required) The ID of the Resource (or Resource Scope) where this should be applied. Changing this forces a new Resource Policy Assignment to be created.

To create a Policy Assignment at a Management Group use the azurerm_management_group_policy_assignment resource, for a Resource Group use the azurerm_resource_group_policy_assignment and for a Subscription use the azurerm_subscription_policy_assignment resource.

description - (Optional) A description which should be used for this Policy Assignment.

display_name - (Optional) The Display Name for this Policy Assignment.

enforce - (Optional) Specifies if this Policy should be enforced or not?

identity - (Optional) An identity block as defined below.

- > Note: The location field must also be specified when identity is specified.

location - (Optional) The Azure Region where the Policy Assignment should exist. Changing this forces a new Policy Assignment to be created.

metadata - (Optional) A JSON mapping of any Metadata for this Policy.

not_scopes - (Optional) Specifies a list of Resource Scopes (for example a Subscription, or a Resource Group) within this Management Group which are excluded from this Policy.

parameters - (Optional) A JSON mapping of any Parameters for this Policy. Changing this forces a new Management Group Policy Assignment to be created.

A identity block supports the following:

  • type - (Optional) The Type of Managed Identity which should be added to this Policy Definition. The only possible value is SystemAssigned .

In addition to the Arguments listed above - the following Attributes are exported:

  • id - The ID of the Resource Policy Assignment.

The identity block exports the following:

principal_id - The Principal ID of the Policy Assignment for this Resource.

tenant_id - The Tenant ID of the Policy Assignment for this Resource.

>> from Terraform Registry

  • Explanation in Terraform Registry
Manages a Policy Assignment to a Resource.

Microsoft.Authorization/policyAssignments (Azure Resource Manager)

The policyAssignments in Microsoft.Authorization can be configured in Azure Resource Manager with the resource name Microsoft.Authorization/policyAssignments . The following sections describe how to use the resource and its parameters.

The Other Related Azure Policy Resources

Azure Policy Configuration Policy Assignment

Azure Policy Definition

Azure Policy Policy Assignment

Azure Policy Remediation

Azure Policy Resource Group Policy Assignment

Azure Policy Set Definition

Azure Policy Subscription Policy Assignment

Azure Policy Virtual Machine Configuration Assignment

  • Frequently asked questions

What is Azure Policy Assignment?

Azure Policy Assignment is a resource for Policy of Microsoft Azure. Settings can be wrote in Terraform.

Where can I find the example code for the Azure Policy Assignment?

For Terraform, the floriandorau/opa-aks source code example is useful. See the Terraform Example section for further details.

For Azure Resource Manager, the lolittle/azure , microsoft/azure_arc and karlochacon/my-arc-repo source code examples are useful. See the Azure Resource Manager Example section for further details.

Automate config file reviews on your commits

Fix issues in your infrastructure as code with auto-generated patches.

Table of Contents

policy assignments principal id

Jason Masten

A personal brain dump of information technology problems & solutions, azure deployment error “tenant id, application id, principal id, and scope are not allowed to be updated.”.

When deploying a role assignment using an ARM template, you receive the error below:

Update your role assignment name (aka GUID) to a value that hasn’t been used previously to deploy a role assignment.

Explanation

Recently I was testing out some code and it was re-used from another solution. When I went to deploy the code, in the same subscription, I received the following error: “Tenant ID, application ID, principal ID, and scope are not allowed to be updated.” The code in question contained a role assignment resource with a static GUID for the name. After testing and isolating the code, I realized the issue was the name of the role assignment resource.

Now, like me, you may make the mistake of using the “newGuid” function to name your role assignments. What could go wrong? The name is now unique now, right? Well each time you deploy your ARM template, a new GUID is created for the resource. That doesn’t work. Once you create a role assignment with a specific GUID, any updates or redeployments will require the same name, aka GUID.

In steps the “guid” function. This function uses a hash to create the GUID based on input that is provided. So, for my scenario, I provided the name of my WVD application group, which is unique across my subscription, and that guaranteed my GUID will be unique yet consistent every time I deploy this ARM template. This is the best practice for creating role assignments with ARM templates. Find a value that is unique and won’t be used elsewhere so your deployments will be idempotent.

Share this:

7 thoughts on “ azure deployment error “tenant id, application id, principal id, and scope are not allowed to be updated.” ”.

Add Comment

How do you implement the newGuid function I had read the documantation but is not clear for me… https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions-string#newguid

Hi Karen, use the “guid” function, not the “newGuid” function. “guid” is idempotent and “newGuid” is not. That’s important so you can redeploy your solution if there is an error or update to the template. If you don’t care about idempotency, per the documentation you can use the “newGuid” function within an expression for the default value of a parameter. Like so: { “$schema”: “https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#”, “contentVersion”: “1.0.0.0”, “parameters”: { “guidValue”: { “type”: “string”, “defaultValue”: “[newGuid()]” } }, “resources”: [ ], “outputs”: { “guidOutput”: { “type”: “string”, “value”: “[parameters(‘guidValue’)]” } } }

Hi Jason, I’ experiencing the same problem after I redeployed my template. the error is : “details”:[{“code”:”BadRequest”,”message”:”{\r\n \”error\”: {\r\n \”code\”: \”RoleAssignmentUpdateNotPermitted\”,\r\n \”message\”: \”Tenant ID, application ID, principal ID, and scope are not allowed to be updated.\”\r\n }\r\n}”},{“code”:”BadRequest”

I checked my template and I’m using guid function : { “type”: “Microsoft.Authorization/roleAssignments”, “apiVersion”: “2020-04-01-preview”, “name”: “[guid(‘storageBlobRoleAssignmentName’, parameters(‘storageAccountName’))]”, “dependsOn”: [ “[variables(‘eventGridDeploymentName’)]”, “[resourceId(‘Microsoft.Web/sites’, parameters(‘functionAppName’))]” ], “properties”: { “roleDefinitionId”: “[variables(‘storageBlobDataContributor’)]”, “principalId”: “[reference(resourceId(‘Microsoft.Web/sites’, parameters(‘functionAppName’)),’2019-08-01′, ‘full’).identity.principalId]”, “principalType”: “ServicePrincipal” }, “scope”: “[concat(‘Microsoft.Storage/storageAccounts’, ‘/’, parameters(‘storageAccountName’))]” },

any suggestion how to fix this error?

Al Chab, that can happen if you have an orphaned role assignment. I would validate the RBAC assignments at that scope. Delete any that that are missing the principal info.

I have a problem when assigning roles to a subscription. I have a function that set owner to a subscription. I In some subscriptions it works and in others I get the following error:

“` { “error”: { “code”: “RoleAssignmentUpdateNotPermitted”, “message”: “Tenant ID, application ID, principal ID, and scope are not allowed to be updated.” } } “`

I could not find a reason why this is happening. I using msal library in javascript.

my request is:

“` headers: { Authorization: `Bearer ${token}`, ‘Content-Type’: ‘application/json’, }

url: https://management.azure.com/subscriptions/ {subId}/providers/Microsoft.Authorization/roleAssignments/{roleIdOfOwner}?api-version=’2017-05-01′

body: { properties: { roleDefinitionId: subscriptions/{subId}/providers/Microsoft.Authorization/roleDefinitions/{roleIdOfOwner}, principalId: {principalId of the user} }

Dan, it looks like you are making a REST API call. Here is the reference for that: https://docs.microsoft.com/en-us/azure/role-based-access-control/role-assignments-rest . In the URL for the REST API call, the GUID for the “roleAssignmentId” should be unique for each assignment per scope, principal, and role. That’s referenced in step 2 in the URL I provided above. If an assignment has been orphaned, the principal has been deleted but not the assignment or scope, then you should clean those up.

This issue puzzled me as I was using a guid, but is was based on the SP so when used again it failed..but your fix helped. Just wanted you to know I appreciate you!! Thank you

Leave a comment Cancel reply

' src=

  • Already have a WordPress.com account? Log in now.
  • Subscribe Subscribed
  • Copy shortlink
  • Report this content
  • View post in Reader
  • Manage subscriptions
  • Collapse this bar

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Policy assignments do not create role assignments for the managed identity; deployIfNotExist actions fail #17988

@schwarzzz

schwarzzz commented Aug 13, 2022

to the original issue to help the community and maintainers prioritize this request

1.2.7

3.18.0

azurerm_resource_group_policy_assignment, azurerm_subscription_policy_assignment

"azurerm" { features { } } data "azurerm_subscription" "current" { } # Deploy - Configure diagnostic settings for Azure Key Vault to Log Analytics workspace data "azurerm_policy_definition" "kv" { name = "951af2fa-529b-416e-ab6e-066fd85ac459" } resource "azurerm_resource_group" "target" { name = "rg-policy-assignment-test" location = "westeurope" } resource "azurerm_log_analytics_workspace" "instance" { name = "log-testtfpolassignment" location = azurerm_resource_group.target.location resource_group_name = azurerm_resource_group.target.name sku = "PerGB2018" retention_in_days = 30 } resource "azurerm_resource_group_policy_assignment" "assignment" { name = "assignment" location = azurerm_resource_group.target.location resource_group_id = azurerm_resource_group.target.id policy_definition_id = data.azurerm_policy_definition.kv.id identity { type = "SystemAssigned" } parameters = <<PARAMS { "logAnalytics": { "value": "${azurerm_log_analytics_workspace.instance.id}" } } PARAMS }

The policy assignment's managed identity should have the roles assigned, as specified in the policy definition.
A deployIfNotExists policy action on a matching resource should succeed.

The policy assignment's managed identity does not have any roles assigned.
A deployIfNotExists policy action fails with error message:

Go to the portal and navigate to the created assignment (Policy -Assignments - assignment - Managed Identity). The list under "Permissions - Roles" shows "No results."

Assign the exact same policy using the same user account to the same scope via the portal (select the log analytics workspace, scope and location, leave all other settings on default) and check the created assignment in the portal: The list under "Permissions - Roles" will show the roles specified in the policy definition.

@schwarzzz

wuxu92 commented Aug 16, 2022

hi thanks for your feedback, here is some information from my understanding.

in terraform, we need to specify the role assignments as below, so we can manage all the roles assigned to the principal

, where does this message show up and how can I find it(i didn't see it in my azure portal ')

please ping me if there are any further questions.

Sorry, something went wrong.

schwarzzz commented Aug 17, 2022

, thank you for your response.

I got it - and now, that I did some more research, I also found the respective statement in the Azure documentation.

So sorry for raising this issue in the first place.

However, I have one concern with the proposed solution: The required roles need to be specified twice: In the policy definition ( ) and the terraform code. Lets assume I have a custom policy and modify it over time. I might need to add a role and then there is the chance that I forget to add it to the assignment code as well.

Do you think it be feasible/reasonable to add the role definition IDs to the 's arguments?

Then it would be possible to write something like:

No need to manually specify the elements for the role definition...

  • đź‘Ť 1 reaction

wuxu92 commented Aug 17, 2022

that sounds reasonable but the azurerm_policy_definition resource does not expose the role_ids for now. could you please raise a issue to request this feature then we can discuss the possibility and schedule there, and then we can close this issue here?

@github-actions

github-actions bot commented Sep 17, 2022

I'm going to lock this issue because it has been closed for ⏳. This helps our maintainers find and focus on the active issues.
If you have found a problem that seems similar to this, please open a new issue and complete the issue template so we can capture all the details necessary to investigate further.

@catriona-m

No branches or pull requests

@wuxu92

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Understand Azure role assignments

  • 3 contributors

Role assignments enable you to grant a principal (such as a user, a group, a managed identity, or a service principal) access to a specific Azure resource. This article describes the details of role assignments.

Role assignment

Access to Azure resources is granted by creating a role assignment, and access is revoked by removing a role assignment.

A role assignment has several components, including:

  • The principal , or who is assigned the role.
  • The role that they're assigned.
  • The scope at which the role is assigned.
  • The name of the role assignment, and a description that helps you to explain why the role has been assigned.

For example, you can use Azure RBAC to assign roles like:

  • User Sally has owner access to the storage account contoso123 in the resource group ContosoStorage .
  • Everybody in the Cloud Administrators group in Microsoft Entra ID has reader access to all resources in the resource group ContosoStorage .
  • The managed identity associated with an application is allowed to restart virtual machines within Contoso's subscription.

The following shows an example of the properties in a role assignment when displayed using Azure PowerShell :

The following shows an example of the properties in a role assignment when displayed using the Azure CLI , or the REST API :

The following table describes what the role assignment properties mean.

Property Description

The name of the role assignment, which is a globally unique identifier (GUID).

The unique ID of the role assignment, which includes the name.

The Azure resource identifier that the role assignment is scoped to.

The unique ID of the role.

The name of the role.

The Microsoft Entra object identifier for the principal who has the role assigned.

The type of Microsoft Entra object that the principal represents. Valid values include , , and .
For role assignments for users, the display name of the user.

The unique principal name (UPN) of the user, or the name of the application associated with the service principal.

The description of the role assignment.

Condition statement built using one or more actions from role definition and attributes.

The condition version number. Defaults to 2.0 and is the only supported version.

Not implemented.

When you create a role assignment, you need to specify the scope at which it's applied. The scope represents the resource, or set of resources, that the principal is allowed to access. You can scope a role assignment to a single resource, a resource group, a subscription, or a management group.

Use the smallest scope that you need to meet your requirements.

For example, if you need to grant a managed identity access to a single storage account, it's good security practice to create the role assignment at the scope of the storage account, not at the resource group or subscription scope.

For more information about scope, see Understand scope .

Role to assign

A role assignment is associated with a role definition. The role definition specifies the permissions that the principal should have within the role assignment's scope.

You can assign a built-in role definition or a custom role definition. When you create a role assignment, some tooling requires that you use the role definition ID while other tooling allows you to provide the name of the role.

For more information about role definitions, see Understand role definitions .

Principals include users, security groups, managed identities, workload identities, and service principals. Principals are created and managed in your Microsoft Entra tenant. You can assign a role to any principal. Use the Microsoft Entra ID object ID to identify the principal that you want to assign the role to.

When you create a role assignment by using Azure PowerShell, the Azure CLI, Bicep, or another infrastructure as code (IaC) technology, you specify the principal type . Principal types include User , Group , and ServicePrincipal . It's important to specify the correct principal type. Otherwise, you might get intermittent deployment errors, especially when you work with service principals and managed identities.

A role assignment's resource name must be a globally unique identifier (GUID).

Role assignment resource names must be unique within the Microsoft Entra tenant, even if the scope of the role assignment is narrower.

When you create a role assignment by using the Azure portal, Azure PowerShell, or the Azure CLI, the creation process gives the role assignment a unique name for you automatically.

If you create a role assignment by using Bicep or another infrastructure as code (IaC) technology, you need to carefully plan how you name your role assignments. For more information, see Create Azure RBAC resources by using Bicep .

Resource deletion behavior

When you delete a user, group, service principal, or managed identity from Microsoft Entra ID, it's a good practice to delete any role assignments. They aren't deleted automatically. Any role assignments that refer to a deleted principal ID become invalid.

If you try to reuse a role assignment's name for another role assignment, the deployment will fail. This issue is more likely to occur when you use Bicep or an Azure Resource Manager template (ARM template) to deploy your role assignments, because you have to explicitly set the role assignment name when you use these tools. To work around this behavior, you should either remove the old role assignment before you recreate it, or ensure that you use a unique name when you deploy a new role assignment.

Description

You can add a text description to a role assignment. While descriptions are optional, it's a good practice to add them to your role assignments. Provide a short justification for why the principal needs the assigned role. When somebody audits the role assignments, descriptions can help to understand why they've been created and whether they're still applicable.

Some roles support role assignment conditions based on attributes in the context of specific actions. A role assignment condition is an additional check that you can optionally add to your role assignment to provide more fine-grained access control.

For example, you can add a condition that requires an object to have a specific tag for the user to read the object.

You typically build conditions using a visual condition editor, but here's what an example condition looks like in code:

The preceding condition allows users to read blobs with a blob index tag key of Project and a value of Cascade .

For more information about conditions, see What is Azure attribute-based access control (Azure ABAC)?

Integration with Privileged Identity Management (Preview)

Azure role assignment integration with Privileged Identity Management is currently in PREVIEW. See the Supplemental Terms of Use for Microsoft Azure Previews for legal terms that apply to Azure features that are in beta, preview, or otherwise not yet released into general availability.

If you have a Microsoft Entra ID P2 or Microsoft Entra ID Governance license, Microsoft Entra Privileged Identity Management (PIM) is integrated into role assignment steps. For example, you can assign roles to users for a limited period of time. You can also make users eligible for role assignments so that they must activate to use the role, such as request approval. Eligible role assignments provide just-in-time access to a role for a limited period of time. You can't create eligible role assignments for applications, service principals, or managed identities because they can't perform the activation steps. You can create eligible role assignments at management group, subscription, and resource group scope, but not at resource scope. This capability is being deployed in stages, so it might not be available yet in your tenant or your interface might look different.

The assignment type options available to you might vary depending or your PIM policy. For example, PIM policy defines whether permanent assignments can be created, maximum duration for time-bound assignments, roles activations requirements (approval, multifactor authentication, or Conditional Access authentication context), and other settings. For more information, see Configure Azure resource role settings in Privileged Identity Management .

If you don't want to use the PIM functionality, select the Active assignment type and Permanent assignment duration options. These settings create a role assignment where the principal always has permissions in the role.

Screenshot of Add role assignment with Assignment type options displayed.

To better understand PIM, you should review the following terms.

Term or concept Role assignment category Description
eligible Type A role assignment that requires a user to perform one or more actions to use the role. If a user has been made eligible for a role, that means they can activate the role when they need to perform privileged tasks. There's no difference in the access given to someone with a permanent versus an eligible role assignment. The only difference is that some people don't need that access all the time.
active Type A role assignment that doesn't require a user to perform any action to use the role. Users assigned as active have the privileges assigned to the role.
activate The process of performing one or more actions to use a role that a user is eligible for. Actions might include performing a multifactor authentication (MFA) check, providing a business justification, or requesting approval from designated approvers.
permanent eligible Duration A role assignment where a user is always eligible to activate the role.
permanent active Duration A role assignment where a user can always use the role without performing any actions.
time-bound eligible Duration A role assignment where a user is eligible to activate the role only within start and end dates.
time-bound active Duration A role assignment where a user can use the role only within start and end dates.
just-in-time (JIT) access A model in which users receive temporary permissions to perform privileged tasks, which prevents malicious or unauthorized users from gaining access after the permissions have expired. Access is granted only when users need it.
principle of least privilege access A recommended security practice in which every user is provided with only the minimum privileges needed to accomplish the tasks they're authorized to perform. This practice minimizes the number of Global Administrators and instead uses specific administrator roles for certain scenarios.

For more information, see What is Microsoft Entra Privileged Identity Management? .

  • Delegate Azure access management to others
  • Steps to assign an Azure role

Was this page helpful?

Additional resources

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Unable to remove a deleted identity "Service Principle" at root scope "/"

I have tried to remove the Service Principle role assignment by running:

az role assignment delete --assignee *** --scope "/" --role "Owner"

but I'm receiving this error:

"Cannot find user or service principal in graph database for ***. If the assignee is an appId, make sure the corresponding service principal is created with 'az ad sp create --id *** "

So then I try to create a SP by giving it the same id and I get:

"The appId *** of the service principal does not reference a valid application object."

Has anyone experienced this before, any assistance would be appreciated

  • azure-active-directory
  • azure-service-principal

Cyborganizer's user avatar

  • check if there is an existing service principal with the appId you're trying to use. should be: | az ad sp list --filter "appId eq 'APP_ID'" If you see the service principal in the list, it should reference a valid application object. If it doesn't, you may need to delete the incorrect service principal and create a new one. –  Ziya Mert Karakas Commented Sep 4, 2023 at 0:30

The error usually occurs if you are passing wrong ID value for --assignee parameter while deleting role assignment.

I have one service principal assigned with Owner role under subscription scope like this:

enter image description here

When I tried to delete role assignment by passing App registration's Object ID, I too got same error as below:

enter image description here

To resolve the error, make sure to pass service principal's Object ID that can be found in Enterprise applications with same application name.

You can also run below CLI command to get service principal's Object ID:

enter image description here

When I ran same command by passing service principal's Object ID, role assignment deleted successfully like below:

enter image description here

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged azure-active-directory azure-service-principal or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Why was Panama Railroad in poor condition when US decided to build Panama Canal in 1904?
  • Paying a parking fine when I don't trust the recipient
  • Working principle of the Zener diode acting as a voltage regulator in a circuit
  • How do you ensure that calendar invites won't be moved out of your inbox when your rules are executed?
  • Engaging students in the beauty of mathematics
  • How would platypus evolve some sort of digestive acid?
  • A journal has published an AI-generated article under my name. What to do?
  • using git autobackup with shell script
  • How to split a plane into n-gon mesh as defined by the voronoi color texture?
  • How did NASA figure out when and where the Apollo capsule would touch down on the ocean?
  • If Act A repeals another Act B, and Act A is repealed, what happens to the Act B?
  • What would the natural diet of Bigfoot be?
  • What film is it where the antagonist uses an expandable triple knife?
  • Example of two dinatural transformations between finite categories that do not compose
  • Does my employer contributions count towards the Roth limit of $7k?Roth contributions
  • Why are some Cloudflare challenges CPU intensive?
  • Would it be illegal for Companies House to require a response to a letter on registration?
  • Is this map real?
  • How can a microcontroller (such as an Arduino Uno) that requires 7-21V input voltage be powered via USB-B which can only run 5V?
  • How can I analyze the anatomy of a humanoid species to create sounds for their language?
  • How can I remove this towel rail mount from my wall?
  • BASH - Find file with regex - Non-recursively delete number-only filenames in directory
  • cat file contents to clipboard over ssh and across different OS
  • For glacier winds to exist, are circulation cells needed?

policy assignments principal id

COMMENTS

  1. Details of the policy assignment structure

    This segment of the policy assignment provides the values for the parameters defined in the policy definition or initiative definition. This design makes it possible to reuse a policy or initiative definition with different resources, but check for different business values or outcomes. "prefix": {. "value": "DeptA".

  2. Policy Assignments

    The display name of the policy assignment. properties.enforcementMode enforcement Mode. Default The policy assignment enforcement mode. Possible values are Default and DoNotEnforce. properties.metadata object The policy assignment metadata. Metadata is an open ended object and is typically a collection of key value pairs.

  3. What should be principal id while assigning role access to App?

    1. You need to use the object ID, not the application ID. role_definition_name = "Storage Blob Data Contributor". principal_id = module.ad_application.object_id. scope = module.storage_account.id. I don't know what you have in that module, so I cannot tell if it has the key like this.

  4. Policy Assignment Files

    Generate the CSV file form your already deployed Assignment (s) or Policy Set (s). Modify the effect and parameter columns for each type of environment types you will use. Modify the Policy Assignment file to reference the CSV file and the column prefix. Update the CSV file with the new effect and parameter values.

  5. Bicep Access policies and Managed Identity

    Access Policies in Bicep. When you create a KeyVault you have to give people / accounts access to be able to use KeyValut in Azure. Within the portal you need to go to the following areas:-. So in order to give applications and users access we add access policies. Now if you look up the Microsoft docs page for this, you'll more than likely ...

  6. Microsoft.Authorization policyAssignments

    The display name of the policy assignment. string: enforcementMode: The policy assignment enforcement mode. Possible values are Default and DoNotEnforce. 'Default' 'DoNotEnforce' metadata: The policy assignment metadata. Metadata is an open ended object and is typically a collection of key value pairs. For Bicep, you can use the any() function.

  7. Azure Policy Policy Assignment

    Parameters. The following arguments are supported: management_group_id - (Required) The ID of the Management Group. Changing this forces a new Policy Assignment to be created. name - (Required) The name which should be used for this Policy Assignment. Changing this forces a new Policy Assignment to be created.

  8. Azure Policy Assignment

    location - (Optional) The Azure Region where the Policy Assignment should exist. Changing this forces a new Policy Assignment to be created. metadata - (Optional) A JSON mapping of any Metadata for this Policy. not_scopes - (Optional) Specifies a list of Resource Scopes (for example a Subscription, or a Resource Group) within this Management ...

  9. [Examples] Configure Policy UserAssignedIdentity

    In your lib directory create a policy_assignments subdirectory if you don't already have one. You can learn more about archetypes and custom libraries in this article.. NOTE: Creating a policy_assignments subdirectory is a recommendation only. If you prefer not to create one or to call it something else, the role assignment will still work.

  10. Policy Assignments

    Retrieves all policy assignments that apply to a subscription. This operation retrieves the list of all policy assignments associated with the given subscriptio ... The principal ID of the resource identity. This property will only be provided for a system assigned identity ... The ID of the policy assignment. identity Identity. The managed ...

  11. az policy assignment

    Copy. Open Cloud Shell. az policy assignment create --name myPolicy --policy {PolicyName} --mi-system-assigned --location eastus. Create a resource policy assignment with a system assigned identity. The identity will have 'Contributor' role access to the subscription. Azure CLI.

  12. Azure Deployment Error "Tenant ID, application ID, principal ID, and

    In the URL for the REST API call, the GUID for the "roleAssignmentId" should be unique for each assignment per scope, principal, and role. That's referenced in step 2 in the URL I provided above. If an assignment has been orphaned, the principal has been deleted but not the assignment or scope, then you should clean those up. Like Like

  13. Quickstart: New policy assignment with portal

    Clean up resources. To remove the assignment created, follow these steps: Select Compliance (or Assignments) in the left side of the Azure Policy page and locate the Audit VMs that do not use managed disks policy assignment you created.. Right-click the Audit VMs that do not use managed disks policy assignment and select Delete assignment.. Next steps. In this quickstart, you assigned a policy ...

  14. Enable VM insights by using Azure Policy

    Note. If you select a workspace that's not within the scope of the assignment, grant Log Analytics Contributor permissions to the policy assignment's principal ID. Otherwise, you might get a deployment failure like: The client '343de0fe-e724-46b8-b1fb-97090f7054ed' with object id '343de0fe-e724-46b8-b1fb-97090f7054ed' does not have authorization to perform action 'microsoft.operationalinsights ...

  15. Policy assignments do not create role assignments for the ...

    Is there an existing issue for this? I have searched the existing issues; Community Note. Please vote on this issue by adding a đź‘Ť reaction to the original issue to help the community and maintainers prioritize this request; Please do not leave "+1" or "me too" comments, they generate extra noise for issue followers and do not help prioritize the request

  16. Understand Azure role assignments

    Any role assignments that refer to a deleted principal ID become invalid. If you try to reuse a role assignment's name for another role assignment, the deployment will fail. ... PIM policy defines whether permanent assignments can be created, maximum duration for time-bound assignments, roles activations requirements (approval, multifactor ...

  17. terraform

    principal_id = each.key. } With above code I can add the role assignments like reader and storage-blob-data-reader to the service principal id. Console: Portal: The role definition name should not be list. If you need to add assign another user, you can create separate variable and assign to them.

  18. azure active directory

    az role assignment delete --assignee *** --scope "/" --role "Owner" but I'm receiving this error: "Cannot find user or service principal in graph database for ***. If the assignee is an appId, make sure the corresponding service principal is created with 'az ad sp create --id *** "So then I try to create a SP by giving it the same id and I get: