policy assignments principal id

Using Azure policies to audit and automate RBAC role assignments

Usually different RBAC role assignments in Azure might be inherited from subscription / management group level but there may come a time when that's just way too broad spectrum to give permissions to an AD user group.

policy assignments principal id

While it’s tempting to assign permissions on a larger scope, sometimes you might rather prefer to have only some of the subscription’s resource groups granted with a RBAC role with minimal permissions to accomplish the task at hand. In those scenarios you’ll usually end up with one of the following options to handle the role assignments:

  • Include the role assignments in your ARM templates / Terraform codes / Bicep templates
  • Manually add the role to proper resource groups

If neither these appeal to you, there’s a third option: define an Azure policy which identifies correct resource groups and then deploys RBAC role assignments automatically if conditions are met. This blog will go over with step-by-step instructions how to:

  • Create a custom Azure policy definition for assigning Contributor RBAC role for an Azure AD group
  • Create a custom RBAC role for policy deployments and add it to your policy definition
  • Create an assignment for the custom policy

The example scenario is very specific and the policy definition is created to match this particular scenario. You can use the solution provided in this post as a basis to create something that fits exactly to your needs.

Azure policies in brief

Azure policies are a handy way to add automation and audit functionality to your cloud subscriptions. The policies can be applied to make sure resources are created following the company’s cloud governance guidelines for resource tagging or picking the right SKUs for VMs as an example. Microsoft provides a lot of different type built-in policies that are pretty much ready for assignment. However, for specific needs you’ll usually end up creating a custom policy that better suits your needs.

Using Azure policies is divided into two main steps:

  • You need to define a policy which means creating a ruleset (policy rule) and actions (effect) to apply if a resource matches the defined rules.
  • Then you must assign the policy to desired scope (management group / subscription / resource group / resource level). Assignment scope defines the maximum level of scanning if resources match the policy criteria. Usually the preferable levels are management group / subscription.

Depending on how you prefer governing your environment, you can resolve to use individual policies or group multiple policies into initiatives . Initiatives help you simplify assignments by working with groups instead of individual assignments. It also helps with handling service principal permissions. If you create a policy for enforcing 5 different tags, you’ll end up with having five service principals with the same permissions if you don’t use an initiative that groups the policies into one.

Creating the policy definition for assignment of Contributor RBAC role

The RBAC role assignment can be done with policy that targets the wanted scope of resources through policy rules. So first we’ll start with defining some basic properties for our policy which tells the other users what this policy is meant for. Few mentions:

  • Policy type = custom . Everything that’s not built-in is custom.
  • Mode = all since we won’t be creating a policy that enforces tags or locations
  • Category can be anything you like. We’ll use “Role assignment” as an example

Now we have our policy’s base information set. It’s time to form a policy rule. The policy rule consists of two blocks: policyRule and then . First one is the actual rule definition and the latter is the definition of what should be done when conditions are met. We’ll want to target only a few specific resource groups so the scope can be narrowed down with tag evaluations and resource group name conventions. To do this let’s slap an allOf operator (which is kind of like the logical operator ‘and’) to the policy rule and set up the rules

As can be seen from the JSON, the policy is applied to a resource (or actually a resource group) if

  • It’s type of Microsoft.Resources/subscriptions/resourceGroups = the target resource is a resource group
  • It has a tag named RbacAssignment set to true
  • The resource group name starts with my-rg-prefix

In order for the policy to actually do something, an effect must be defined. Because we want the role assignment to be automated, the deployIfNotExists effect is perfect. Few mentions of how to set up an effect:

  • The most important stuff is in the details block
  • The type of the deployment and the scope of an existence check is Microsoft.Authorization/roleAssignments for RBAC role assignments
  • An existence condition is kind of an another if block: the policy rule checks if a resource matches the conditions which makes it applicable for the policy. Existence check then confirms if the requirements of the details are met. If not, an ARM template will be deployed to the scoped resource

The existence condition of then block in the code example below checks the role assignment for a principal id through combination of Microsoft.Authorization/roleAssignments/roleDefinitionId and Microsoft.Authorization/roleAssignments/principalId . Since we want to assign the policy to a subscription, roleDefinitionId path must include the /subscriptions/<your_subscription_id>/.. in order for the policy to work properly.

The last thing to add is the actual ARM template that will be deployed if existence conditions are not met. The template itself is fairly simple since it’s only containing the definitions for a RBAC role assignment.

And that’s it! Now we have the policy definition set up for checking and remediating default RBAC role assignment for our subscription. If the automated deployment feels too daunting, the effect can be swapped to auditIfNotExist version. That way you won’t be deploying anything automatically but you can simply audit all the resource groups in the scope for default RBAC role assignments.

That should be enough, right? Well it isn’t. Since we’re using ARM template deployment with our policy, we must add a role with privileges to create remediation tasks which essentially means we must add a role that has privileges to create and validate resource deployments. Azure doesn’t provide such policy with minimal privileges out-of-the-box since the scope that has all the permissions we need is Owner. We naturally don’t want to give Owner permissions to anything if we reeeeeally don’t have to. The solution: create a custom RBAC role for Azure Policy remediation tasks.

Create custom RBAC role for policy remediation

Luckily creating a new RBAC role for our needs is a fairly straightforward task. You can create new roles in Azure portal or with Powershell or Azure CLI. Depending on your desire and permissions to go around in Azure, you’ll want to create the new role into a management group or a subscription to contain it to a level where it is needed. Of course there’s no harm done to spread that role to wider area of your Azure environment, but for the sake of keeping everything tidy, we’ll create the new role to one subscription since it’s not needed elsewhere for the moment.

Note that the custom role only allows anyone to validate and create deployments. That’s not enough to actually do anything. You’ll need to combine the deployment role with a role that has permissions to do the stuff set in deployment. For RBAC role assignments you’d need to add “User Access Administrator” role to the deployer as well.

Here’s how to do it in Azure portal:

  • Go to your subscription listing in Azure, pick the subscription you want to add the role to and head on to Access control (IAM) tab.
  • From the top toolbar, click on the “Add” menu and select “Add custom role”.
  • Give your role a clear, descriptive name such as Least privilege deployer or something else that you think is more descriptive.
  • Add a description.
  • Add permissions Microsoft.Resources/deployments/validate/action and Microsoft.Resources/deployments/write to the role.
  • Set the assignable scope to your subscription.
  • Review everything and save.

After the role is created, check it’s properties and take note of the role id. Next we’ll need to update the policy definition made earlier in order to get the new RBAC role assigned to the service principal during policy initiative assignment.

So from the template, change this in effect block:

Assigning the created policy

Creating the policy definition is not enough for the policy to take effect. As mentioned before, the definition is merely a ruleset created for assigning the policy and does nothing without the policy assignment. Like definitions, assignments can be set to desired scope. Depending on your policy, you can set the policy for management group level or individual assignments to subscription level with property values that fit each individual subscription as needed.

Open Azure Policy and select “Assignment” from the left side menu. You can find “Assign policy” from the top toolbar. There’s a few considerations that you should go over when you’re assigning a policy:

  • The scope: always think about your assignment scope before blindly assigning policies that modify your environment.
  • Exclusion is a possibility, not a necessity. Should you re-evaluate the policy definition if you find yourself adding a lot of exclusions?
  • You can fix all the non-compliant resources with a remediation task after initial compliance scan

Remediation

  • If you have a policy that changes something either with modify of deployIfNotExists effect, you’ll be creating a service principal for implementing the changes when you assign the policy. Be sure to check the location (region) of the service principal that it matches your desired location.
  • If you select to create a remediation tasks upon assignment, it will implement the changes in policy to existing resources . So if you have doubts if the policy works as you desire, do not create a remediation task during assignment. Review the compliance results first, then create the remediation task if everything’s ok.

Non-compliance message

  • It’s usually a good idea to create a custom non-compliance message for your own custom definitions.

After you’ve set up all relevant stuff for the assignment and created it, it’s time to wait for the compliance checks to go through. When you’ve created an assignment, the first compliance check cycle is done usually within 30 minutes of the assignment creation. After the first cycle, compliance is evaluated once every 24 hours or whenever the assigned policy definitions are changed. If that’s not fast enough for you, you can always trigger an on-demand evaluation scan .

Orphaned Azure Security Principals Clean-up & Azure Policy Managed Identity Role Assignment Automation

policy assignments principal id

This blog covers 2 topics : (1) how you can automate clean-up of any orphaned security principal role assignments – shown as ‘identity not found’ role assignments.

policy assignments principal id

(2) Secondly, I am showing how you can implement a daily quality-assurance process for Azure Policy Managed Identity Role Assignment to enforce Azure Policy remediation is always working. It is important to run this with a defined frequency, as Azure Policy might stop to work, if role assignments are deleted or policy definition is changed after initial deployment.

policy assignments principal id

You can download the script on my github to implement both automations in your environment. I use the script as part of implementing a desired-state / quality-assurance process , to keep Azure “clean” without leftovers – and to ensure Azure Policy compliance enforcement is working as expected.

This blog also covers how you can extract most information from Azure Resource Graph .

(1) Automation of clean-up of unknown/orphaned security principals e.g. managed identities

You might recall orphaned security principals in the “old” days in Active Directory environments, when looking at e.g. NTFS permissions, Group Policy delegations, etc. You can also find such orphaned objects in Azure.

If you check Access Control (IAM) role assignments within the Azure portal, you might have noticed a security principal listed as “Identity not found” with an “Unknown” type .

This happens when a security principal was delegated role assignments inside Azure – but then the security principal was deleted BEFORE the role assignment was removed.

I will refer to this as a ‘ orphaned security principal ’.

policy assignments principal id

It is important to note, that a security principal can be any of these 4 types:

  • Service Principal
  • Managed Identity

This means, that if you delete the security principal before deleting the role assignment, you will see an orphaned security principal with “identity not found” (unknown). Below I have added a few real-world examples:

As you can see from the above examples, there are many situations, which will result in these orphaned security principals. If you are like me, wanting your Azure to be looking “clean”, you will want to automate clean-up of these objects.

How can I see the orphaned accounts ?

Currently, Azure Resource Graph doesn’t support showing Role Assignments, so the only way to detect these, is to traverse the resource tree (management group, subscription, resource groups) to detect orphaned accounts.

You can use Get-AzRoleAssignment to extract the information

NOTE : If you are using Get-AzRoleAssignment, but dont see your ‘unknown’ objects, this is typically caused by running an older version of Az.Resources, which is having bug.

Get-AzRoleAssignment gets basic directory object information from the API and queries further information about the directory object by either AAD or MSGraph api, depending on the version, you have installed.

  • In Az.Resources < 5.1.0, the Get-AzRoleAssignment command depends on the response from AAD graph. It detects the SP is not found and marks the object type as unknown.
  • In Az.Resources >=5.1.0, the cmdlet takes the information from MSGraph. In earlier versions, there was a bug, which was fixed in recent update.

Please run update-module Az.Resources (or update-module Az) to update your Az-modules to newest version.

Highlevel steps to delete orphaned Security Principals:

I use the following 3 steps to delete orphaned Security Principals :

  • You can do scoping on both management group or tenant-wide level.
  • Get-AzRoleAssignment -Scope $PolAssign | Where-Object { $_.ObjectType -eq ‘Unknown’ }
  • If objects are found, both object and location are added to $Orphaned_Accounts object
  • Deletion-process can be be done automatically – or a validation process can be added with a ticket for approval. If you want to delete the orphaned object, you will use the following cmdlet

policy assignments principal id

I run the script as a daily task to ensure the environment shines and don’t have any leftovers 😊

Query to extract scope from Azure Resource Graph

I use the following 3 queries to extract the management groups, subscriptions and resource groups using Azure Resource Graph

(2) Azure Policy Managed Identity Role Assignment Automation

The other maintenance task, which is covered by my script, automates addition of missing managed identity , needed to be able to remediate Azure Policies to enforce compliance on your Azure resources.

I can think of 3 scenarios, where I have seen the need to automate creation of a managed identity role delegation :

  • When you create a managed identity as part of a Azure policy assignment, Azure must be replicated before you can do a role delegation. If you deploy 200 policies, approx 10-15% of my policies happens to fail on the initial run due to this replication issue.
  • If you start by having a policy definition, which runs in audit -mode – and then later change it to deployIfNotExists or modify , then you need to a role delegation through a managed identity.
  • If an subscription owner by mistake deletes a managed identity needed to enforce Microsoft Defender for Cloud policies on subscription-level. Some of the settings needed to enforce Microsoft Defender for Cloud, are controlled by Azure Policies being deployed on subscription-level. They need a managed identity and role delegations to enforce configuration. Both User Access Administrators and Owners can delete managed identities.

Instead of relying entirely on script delay-functions, I have chosen to implement a quality-assurance process , which ensures all policies are having the required managed identities with the needed role permissions . Think of it as it will enforce a ‘desired-state’ using automation.

To stay compliant, I automate this process to run as part of a daily maintenance task, so my Azure policies can run successfully.

Azure Policies deep-dive

Resources that are non-compliant to policies with  deployIfNotExists  or  modify  effects can be put into a compliant state through  Remediation . Remediation is accomplished through  remediation tasks  that deploy the  deployIfNotExists  template or the  modify  operations of the assigned policy on your existing resources and subscriptions, whether that assignment is on a management group, subscription, resource group, or individual resource.

How remediation access control works

When Azure Policy starts a template deployment when evaluating  deployIfNotExists  policies or modifies a resource when evaluating  modify  policies, it does so using a  managed identity  that is associated with the policy assignment.

Policy assignments use  managed identities  for Azure resource authorization. You can use either a system-assigned managed identity that is created by the policy service or a user-assigned identity provided by the user.

The managed identity needs to be assigned the minimum role-based access control (RBAC) role(s) required to remediate resources.

If the managed identity is missing roles, an error is displayed in the portal during the assignment of the policy or an initiative.

When using the portal, Azure Policy automatically grants the managed identity the listed roles once assignment starts.

When using an Azure software development kit (SDK), the roles must manually be granted to the managed identity.

The  location  of the managed identity doesn’t impact its operation with Azure Policy.

NOTE : Changing a policy definition does not automatically update the assignment or the associated managed identity.

Remediation security can be configured through the following 4 steps:

(1) Configure the policy definition

As a prerequisite, the policy definition must define the roles that deployIfNotExists and modify  need to successfully deploy the content of the included template.

No action is required for a built-in policy definition because these roles are prepopulated.

For a custom policy definition, under the  details  property, add a  roleDefinitionIds  property. This property is an array of strings that match roles in your environment. For a full example, see the  deployIfNotExists example  or the  modify examples .

JSONCopy "details": { ... "roleDefinitionIds": [ "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleDefinitions/{roleGUID}", "/providers/Microsoft.Authorization/roleDefinitions/{builtinroleGUID}" ] }

The  roleDefinitionIds  property uses the full resource identifier and doesn’t take the short  roleName  of the role.

Permissions should be restricted to the smallest possible set when defining  roleDefinitionIds  within a policy definition or assigning permissions to a managed identity manually. See  managed identity best practice recommendations  for more best practices.

2) Configure the managed identity

Each Azure Policy assignment can be associated with only one managed identity. However, the managed identity can be assigned multiple roles. Configuration occurs in two steps: first create either a system-assigned or user-assigned managed identity, then grant it the necessary roles.

NOTE : When creating a managed identity through the portal, roles will be granted automatically to the managed identity. If  roleDefinitionIds  are later edited in the policy definition, the new permissions must be manually granted, even in the portal.

(3) Create the managed identity

When creating an assignment using the portal, Azure Policy can generate a system-assigned managed identity and grant it the roles defined in the policy definition’s  roleDefinitionIds . Alternatively, you can specify a user-assigned managed identity that receives the same role assignment.

To set a system-assigned managed identity in the portal:

  • On the  Remediation  tab of the create/edit assignment view, under  Types of Managed Identity , ensure that  System assigned managed identity  is selected.
  • Specify the location at which the managed identity is to be located.

To set a user-assigned managed identity in the portal:

  • On the  Remediation  tab of the create/edit assignment view, under  Types of Managed Identity , ensure that  User assigned managed identity  is selected.
  • Specify the scope where the managed identity is hosted. The scope of the managed identity does not have to equate to the scope of the assignment, but it must be in the same tenant.

Under  Existing user assigned identities , select the managed identity.

(4) Grant permissions to the managed identity through defined roles

If the managed identity does not have the permissions needed to execute the required remediation task, it will be granted permissions  automatically  only through the portal. You may skip this step if creating a managed identity through the portal.

For all other methods, the assignment’s managed identity must be manually granted access through the addition of roles, or else the remediation deployment will fail.

Example scenarios that require manual permissions:

  • If the assignment is created through an Azure software development kit (SDK)
  • If a resource modified by  deployIfNotExists  or  modify  is outside the scope of the policy assignment
  • If the template accesses properties on resources outside the scope of the policy assignment

There are two ways to grant an assignment’s managed identity the defined roles using the portal: by using  Access control (IAM)  or by editing the policy or initiative assignment and selecting  Save .

To add a role to the assignment’s managed identity, follow these steps:

  • Launch the Azure Policy service in the Azure portal by selecting  All services , then searching for and selecting  Policy .
  • Select  Assignments  on the left side of the Azure Policy page.
  • Locate the assignment that has a managed identity and select the name.
  • Find the  Assignment ID  property on the edit page. The assignment ID will be something like:

The name of the managed identity is the last portion of the assignment resource ID, which is 2802056bfc094dfb95d4d7a5 in this example. Copy this portion of the assignment resource ID.

  • Navigate to the resource or the resources parent container (resource group, subscription, management group) that needs the role definition manually added.
  • Select the  Access control (IAM)  link in the resources page and then select  + Add role assignment  at the top of the access control page.
  • Select the appropriate role that matches a  roleDefinitionId  from the policy definition. Leave  Assign access to  set to the default of ‘Azure AD user, group, or application’. In the  Select  box, paste or type the portion of the assignment resource ID located earlier. Once the search completes, select the object with the same name to select ID and select  Save .

4 thoughts on “Orphaned Azure Security Principals Clean-up & Azure Policy Managed Identity Role Assignment Automation”

Great script – thanks.

Is there any reason you’ve grouped these two tasks together in one script rather than creating two separate scripts to do the tasks separately?

Regards Jeff

Good comment. Orinally I saw this problem related to managed identies that was deleted so it was my script for managed identity management (incl policy managed identity). But I realized that orphaned managed identies could happend to any type of security principle but I newer separated the script apart. But the structure with the scoping headers and the 2 groupings easily should allow you to separate them.

Cool post, Morten. Thanks a lot! Christian

  • Pingback: Ctrl+Alt+Azure | 191 - Prompt engineering techniques with ChatGPT and Azure OpenAI

Leave a Reply Cancel reply

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

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

azurerm_policy_assignment fails to remediate resources correctly #14399

@Mahir-Isikli

Mahir-Isikli commented Nov 30, 2021

  • 👍 7 reactions

@aristosvo

aristosvo commented Nov 30, 2021

Sorry, something went wrong.

Mahir-Isikli commented Dec 9, 2021

@github-actions

This comment has been minimized.

@jraggett

aristosvo commented Feb 2, 2022 • edited

Jraggett commented feb 2, 2022.

@krowlandson

krowlandson commented Feb 15, 2022

@rks040888

rks040888 commented Apr 19, 2022

Mahir-isikli commented apr 20, 2022.

@Patrick-Eichhorn

Patrick-Eichhorn commented Jun 10, 2022

@gettek

gettek commented Aug 22, 2022 • edited

@krowlandson

jsredmond commented Mar 5, 2024

No branches or pull requests

@aristosvo

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

policy assignments principal id

This browser is no longer supported.

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

Enable VM insights by using Azure Policy

  • 7 contributors

Azure Policy lets you set and enforce requirements for all new resources you create and resources you modify. VM insights policy initiatives, which are predefined sets of policies created for VM insights, install the agents required for VM insights and enable monitoring on all new virtual machines in your Azure environment.

This article explains how to enable VM insights for Azure virtual machines, virtual machine scale sets, and hybrid virtual machines connected with Azure Arc by using predefined VM insights policy initiates.

For information about how to use Azure Policy with Azure virtual machine scale sets and how to work with Azure Policy directly to enable Azure virtual machines, see Deploy Azure Monitor at scale using Azure Policy .

VM insights initiatives

VM insights policy initiatives install Azure Monitor Agent and the Dependency agent on new virtual machines in your Azure environment. Assign these initiatives to a management group, subscription, or resource group to install the agents on Windows or Linux Azure virtual machines in the defined scope automatically.

The initiatives apply to new machines you create and machines you modify, but not to existing VMs.

The legacy Log Analytics agent will be deprecated by August 2024 . After this date, Microsoft will no longer provide any support for the Log Analytics agent. Migrate to Azure Monitor agent before August 2024 to continue ingesting data.

Support for custom images

Azure Monitor Agent-based VM insights policy and initiative definitions have a scopeToSupportedImages parameter that's set to true by default to enable onboarding Dependency Agent on supported images only. Set this parameter to false to allow onboarding Dependency Agent on custom images.

Assign a VM insights policy initiative

To assign a VM insights policy initiative to a subscription or management group from the Azure portal:

Search for and open Policy .

Select Assignments > Assign initiative .

Screenshot that shows the Policy Assignments screen with the Assign initiative button highlighted.

The Assign initiative screen appears.

Screenshot that shows Assign initiative.

Configure the initiative assignment:

In the Scope field, select the management group or subscription to which you'll assign the initiative.

(Optional) Select Exclusions to exclude specific resources from the initiative assignment. For example, if your scope is a management group, you might specify a subscription in that management group to be excluded from the assignment.

Select the ellipsis ( ... ) next to Initiative assignment to start the policy definition picker. Select one of the VM insights initiatives.

(Optional) Change the Assignment name and add a Description .

On the Parameters tab, select a Log Analytics workspace to which all virtual machines in the assignment will send data. For virtual machines to send data to different workspaces, create multiple assignments, each with their own scope.

Screenshot that shows a workspace.

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/workspaces/read' over scope ...

Select Review + create to review the initiative assignment details. Select Create to create the assignment.

Don't create a remediation task at this point because you'll probably need multiple remediation tasks to enable existing virtual machines. For more information about how to create remediation tasks, see Remediate compliance results .

Review compliance for a VM insights policy initiative

After you assign an initiative, you can review and manage compliance for the initiative across your management groups and subscriptions.

To see how many virtual machines exist in each of the management groups or subscriptions and their compliance status:

Search for and open Azure Monitor .

Select Virtual machines > Overview > Other onboarding options . Then under Enable using policy , select Enable .

Screenshot that shows other onboarding options page of VM insights with the Enable using policy option.

The Azure Monitor for VMs Policy Coverage page appears.

Screenshot that shows the VM insights Azure Monitor for VMs Policy Coverage page.

The following table describes the compliance information presented on the Azure Monitor for VMs Policy Coverage page.

Select the ellipsis ( ... ) > View Compliance .

Screenshot that shows View Compliance.

The Compliance page appears. It lists assignments that match the specified filter and indicates whether they're compliant.

Screenshot that shows Policy compliance for Azure VMs.

Select an assignment to view its details. The Initiative compliance page appears. It lists the policy definitions in the initiative and whether each is in compliance.

Screenshot that shows Compliance details.

Policy definitions are considered noncompliant if:

  • Azure Monitor Agent, the Log Analytics agent, or the Dependency agent aren't deployed. Create a remediation task to mitigate.
  • VM image (OS) isn't identified in the policy definition. Policies can only verify well-known Azure VM images. Check the documentation to see whether the VM OS is supported.
  • Some VMs in the initiative scope are connected to a Log Analytics workspace other than the one that's specified in the policy assignment.

Select a policy definition to open the Policy compliance page.

Create a remediation task

If your assignment doesn't show 100% compliance, create remediation tasks to evaluate and enable existing VMs. You'll most likely need to create multiple remediation tasks, one for each policy definition. You can't create a remediation task for an initiative.

To create a remediation task:

On the Initiative compliance page, select Create Remediation Task .

Screenshot that shows Policy compliance details.

The New remediation task page appears.

Screenshot that shows the New remediation task page.

Review Remediation settings and Resources to remediate and modify as necessary. Then select Remediate to create the task.

After the remediation tasks are finished, your VMs should be compliant with agents installed and enabled for VM insights.

Track remediation tasks

To track the progress of remediation tasks, on the Policy menu, select Remediation and select the Remediation tasks tab.

Screenshot that shows the Policy Remediation page for Monitor | Virtual Machines.

Learn how to:

  • View VM insights Map to see application dependencies.
  • View Azure VM performance to identify bottlenecks and overall utilization of your VM's performance.

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

avatar

Manage Azure Role Assignments Like a Pro with PowerShell

Azure Governance Future Trends and Predictions - AzureIs.Fun

Today’s blog post is a little bit different. I have a couple of examples of how you can use PowerShell snippets and simple commandlets to get or set role assignmnets in your Azure Subscriptions.

PowerShell examples for managing Azure Role assignments

List all role assignments in a subscription, get all role assignments for a specific resource group, get all role assignments for a specific user, add a role assignment to a user, remove a role assignment for a user, remove all role assignments for a specific user, list all built-in roles, list all custom roles, create a custom role, update a custom role, delete a custom role, list all users or groups assigned to a specific role, list all permissions granted by a specific role, list all resource groups that a user has access to, create a role assignment for a service principal, powershell script to manage azure role assignments.

And now there is a script that combines some of these examples into one usable function:

I hope this was useful. Let me know if you liked the format of this blog and if you want me to include more of these examples.

Vukasin Terzic

Recent Update

  • Writing your first Azure Terraform Configuration
  • Transition from ARM Templates to Terraform with AI
  • Getting started with Terraform for Azure
  • Terraform Configuration Essentials: File Types, State Management, and Provider Selection
  • Dynamically Managing Azure NSG Rules with PowerShell

Trending Tags

Retrieve azure resource group cost with powershell api.

The Future Of Azure Governance: Trends and Predictions

Further Reading

In my previous blog posts, I wrote about how simple PowerShell scripts can help speed up daily tasks for Azure administrators, and how you can convert them to your own API. One of these tasks is...

Azure Cost Optimization: 30 Ways to Save Money and Increase Efficiency

As organizations continue to migrate their applications and workloads to the cloud, managing and controlling cloud costs has become an increasingly critical issue. While Azure provides a robust s...

Custom PowerShell API for Azure Naming Policy

To continue our PowerShell API series, we have another example of a highly useful API that you can integrate into your environment. Choosing names for Azure resources can be a challenging task. ...

IMAGES

  1. Elegant School Principal ID Card Template in Publisher, Illustrator

    policy assignments principal id

  2. Policy Assignments

    policy assignments principal id

  3. Deploying Custom Teams Group Policy Assignments

    policy assignments principal id

  4. School Principal ID Cards/Badges for Word

    policy assignments principal id

  5. Quickstart: New policy assignment with portal

    policy assignments principal id

  6. Role Assignments

    policy assignments principal id

VIDEO

  1. Edu514 teaching of social studies assignment 1 solution fall 2023 by nadia khan online academy

  2. Assignment Abroad Times 10th January 2024

  3. NPTEL Week 5 Introduction to Programming in C Assignment Answers

  4. MPSE 001 Solved Assignment 2023 24 IGNOU MPSE 01 SOLVED ASSIGNMENT 2023 24 IN HINDI MPS 2ND YEAR

  5. MSCB gave in writing that they don’t need Enron power, says Dr. Madhav Godbole

  6. NWACC--PLSC 2003: American National Government: Lecture on Syllabus (Part-1)

COMMENTS

  1. Details of the policy assignment structure

    The policy assignment can determine the values of parameters for that group of resources at assignment time, making it possible to reuse policy definitions that address the same resource properties with different needs for compliance. Note. For more information on Azure Policy scope, see Understand scope in Azure Policy.

  2. Microsoft.Authorization/policyAssignments

    The location of the policy assignment. Only required when utilizing managed identity. string: parent_id: The ID of the resource to apply this extension resource to. string (required) identity: The managed identity associated with the policy assignment. Identity: properties: Properties for the policy assignment. PolicyAssignmentProperties

  3. Policy Assignments

    The principal ID of the resource identity. This property will only be provided for a system assigned identity. tenantId string ... The ID of the policy assignment. identity Identity. The managed identity associated with the policy assignment. location string

  4. Change Azure Policy assignment's system assigned managed identity

    When Azure Policy starts a template deployment when evaluating deployIfNotExists policies or modifies a resource when evaluating modify policies, it does so using a managed identity that is associated with the policy assignment. Policy assignments use managed identities for Azure resource authorization. You can use either a system-assigned managed identity that is created by the policy service ...

  5. Using Azure policies to audit and automate RBAC role assignments

    After the role is created, check it's properties and take note of the role id. Next we'll need to update the policy definition made earlier in order to get the new RBAC role assigned to the service principal during policy initiative assignment. So from the template, change this in effect block:

  6. azurerm_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.. Timeouts. The timeouts block allows you to specify timeouts for certain actions:. create - (Defaults to 30 minutes) Used when creating the Policy Assignment for this Resource.

  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. Get all role assignments of an Azure AD Principal

    az role assignment list --all --assignee <Pricipal_ID> ... To do the same for SP(service principals) you can get the azuread application and match the object ID of the service principal for the application and get the PIM. 2.Unfortunately without iterations there is no direct way to get this. ... Temporary policy: Generative AI (e.g., ChatGPT ...

  9. Azure Policy Recommended Practices

    Note 2: You must set the default location for new subscriptions in a MG at or below the scope where the security-oriented Policy Assignments are deployed to prevent rogue subscriptions from bypassing your security controls enforcement with Azure Policy. Policy Assignments. Policies are inert elements in Azure until you create a Policy ...

  10. Azure Policy Subscription Policy Assignment

    Parameters. The following arguments are supported: name - (Required) The name which should be used for this Policy Assignment. Changing this forces a new 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.

  11. Deploy and Assign Azure Policy via Azure DevOps Pipelines

    Select the Role assignments tab, and then click +Add > Add role assignment.. In the Add role assignment blade, you need to choose the 'Resource Policy Contributor' role.. Next, leave the 'Assign access to' as default because we want to choose a service principal, then search for your DevOps service principal that you'd like to permit to, and then click 'Save' as shown in the ...

  12. Orphaned Azure Security Principals Clean-up & Azure Policy Managed

    This blog covers 2 topics : (1) how you can automate clean-up of any orphaned security principal role assignments - shown as 'identity not found' role assignments. (2) Secondly, I am showing how you can implement a daily quality-assurance process for Azure Policy Managed Identity Role Assignment to enforce Azure Policy remediation is always working.

  13. 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.

  14. azurerm_policy_assignment fails to remediate resources correctly

    When the policy assignment is made, a managed identity should be created and granted permission with the explicit role assignment to deploy missing resources with a policy remediation in line with the deployIfNotExists condition. ... to the policy assignment's principal ID. ", "assignPermissions": true} }

  15. Azure Policy Assignment

    Parameters. 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.

  16. Azure Policy

    Managing Azure Policies through Python SDK. Azure Policy helps to enforce organizational standards and to assess compliance at-scale. It also helps to bring your resources to compliance through bulk remediation for existing resources and automatic remediation for added resources. Common use cases for Azure Policy include implementing governance ...

  17. How do you turn a principal_id into a username using the Azure Python

    I'm able to pull a list of role assignments using the following: authorizationClient = AuthorizationManagementClient(credential, subscription_id) roles = authorizationClient.role_assignments.list() This works, and I get a list of dicts that seems to have every piece of info I need except the principal_name. Example response:

  18. Policy Assignments

    Creates or updates a policy assignment. This operation creates or updates the policy assignment with the given ID. Policy assignments made on a scope apply to all resources contained in that scope. For example, when you assign a policy to a resource group that policy applies to all resources in the group. Policy assignment IDs have this format ...

  19. Enable VM insights by using Azure Policy

    Search for and open Policy. Select Assignments > Assign initiative. The Assign initiative screen appears. Configure the initiative assignment: ... grant Log Analytics Contributor permissions to the policy assignment's principal ID. Otherwise, you might get a deployment failure like:

  20. can't use log analytics workspace in a different subscription

    for var.log_analytics_workspace_ID, if i use the workspace id that is in the same subscription as the policy, it would work fine. but If I use a workspace ID from a different subscription, after deployment, the workspace field will be blank. also for. resource "azurerm_role_assignment" "vm_policy_msi_assignment"

  21. Manage Azure Role Assignments Like a Pro with PowerShell

    Learn how to manage Azure Role assignments using PowerShell snippets and simple commandlets. Discover examples for listing all role assignments, adding and removing assignments for users or service principals, creating custom roles, and more. Plus, check out a script that combines some of these examples into a single function. Written by Vukasin Terzic.