This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
PUT https://management.azure.com/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}?api-version=2023-04-01
URI Parameters
Name |
In |
Required |
Type |
Description |
policyAssignmentName
|
path |
True
|
string
pattern: ^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$
|
The name of the policy assignment.
|
scope
|
path |
True
|
string
|
The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'
|
api-version
|
query |
True
|
string
minLength: 1
|
The API version to use for this operation.
|
Request Body
Name |
Type |
Description |
identity
|
Identity
|
The managed identity associated with the policy assignment.
|
location
|
string
|
The location of the policy assignment. Only required when utilizing managed identity.
|
properties.definitionVersion
|
string
|
The version of the policy definition to use.
|
properties.description
|
string
|
This message will be part of response in case of policy violation.
|
properties.displayName
|
string
|
The display name of the policy assignment.
|
properties.enforcementMode
|
enforcementMode
|
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.
|
properties.nonComplianceMessages
|
NonComplianceMessage[]
|
The messages that describe why a resource is non-compliant with the policy.
|
properties.notScopes
|
string[]
|
The policy's excluded scopes.
|
properties.overrides
|
Override[]
|
The policy property value override.
|
properties.parameters
|
<string,
ParameterValuesValue>
|
The parameter values for the assigned policy rule. The keys are the parameter names.
|
properties.policyDefinitionId
|
string
|
The ID of the policy definition or policy set definition being assigned.
|
properties.resourceSelectors
|
ResourceSelector[]
|
The resource selector list to filter policies by resource properties.
|
Responses
Name |
Type |
Description |
201 Created
|
PolicyAssignment
|
Created - Returns information about the new policy assignment.
|
Other Status Codes
|
CloudError
|
Error response describing why the operation failed.
|
Security
azure_auth
Azure Active Directory OAuth2 Flow.
Type:
oauth2
Flow:
implicit
Authorization URL:
https://login.microsoftonline.com/common/oauth2/authorize
Scopes
Name |
Description |
user_impersonation
|
impersonate your user account
|
Examples
Create or update a policy assignment
Sample request
PUT https://management.azure.com/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/EnforceNaming?api-version=2023-04-01
{
"properties": {
"displayName": "Enforce resource naming rules",
"description": "Force resource names to begin with given DeptA and end with -LC",
"metadata": {
"assignedBy": "Special Someone"
},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
"parameters": {
"prefix": {
"value": "DeptA"
},
"suffix": {
"value": "-LC"
}
},
"nonComplianceMessages": [
{
"message": "Resource names must start with 'DeptA' and end with '-LC'."
}
]
}
}
import com.azure.core.management.serializer.SerializerFactory;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.resourcemanager.resources.fluent.models.PolicyAssignmentInner;
import com.azure.resourcemanager.resources.models.NonComplianceMessage;
import com.azure.resourcemanager.resources.models.ParameterValuesValue;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for PolicyAssignments Create.
*/
public final class Main {
/*
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/
* createPolicyAssignment.json
*/
/**
* Sample code: Create or update a policy assignment.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createOrUpdateAPolicyAssignment(com.azure.resourcemanager.AzureResourceManager azure)
throws IOException {
azure.genericResources().manager().policyClient().getPolicyAssignments().createWithResponse(
"subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "EnforceNaming",
new PolicyAssignmentInner().withDisplayName("Enforce resource naming rules").withPolicyDefinitionId(
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming")
.withParameters(mapOf("prefix", new ParameterValuesValue().withValue("DeptA"), "suffix",
new ParameterValuesValue().withValue("-LC")))
.withDescription("Force resource names to begin with given DeptA and end with -LC")
.withMetadata(SerializerFactory.createDefaultManagementSerializerAdapter()
.deserialize("{\"assignedBy\":\"Special Someone\"}", Object.class, SerializerEncoding.JSON))
.withNonComplianceMessages(Arrays.asList(new NonComplianceMessage()
.withMessage("Resource names must start with 'DeptA' and end with '-LC'."))),
com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armpolicy_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armpolicy"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/219b2e3ef270f18149774eb2793b48baacde982f/specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignment.json
func ExampleAssignmentsClient_Create_createOrUpdateAPolicyAssignment() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armpolicy.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
_, err = clientFactory.NewAssignmentsClient().Create(ctx, "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "EnforceNaming", armpolicy.Assignment{
Properties: &armpolicy.AssignmentProperties{
Description: to.Ptr("Force resource names to begin with given DeptA and end with -LC"),
DisplayName: to.Ptr("Enforce resource naming rules"),
Metadata: map[string]any{
"assignedBy": "Special Someone",
},
NonComplianceMessages: []*armpolicy.NonComplianceMessage{
{
Message: to.Ptr("Resource names must start with 'DeptA' and end with '-LC'."),
}},
Parameters: map[string]*armpolicy.ParameterValuesValue{
"prefix": {
Value: "DeptA",
},
"suffix": {
Value: "-LC",
},
},
PolicyDefinitionID: to.Ptr("/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming"),
},
}, nil)
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { PolicyClient } = require("@azure/arm-policy");
const { DefaultAzureCredential } = require("@azure/identity");
require("dotenv/config");
/**
* This sample demonstrates how to This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
*
* @summary This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignment.json
*/
async function createOrUpdateAPolicyAssignment() {
const scope = "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2";
const policyAssignmentName = "EnforceNaming";
const parameters = {
description: "Force resource names to begin with given DeptA and end with -LC",
displayName: "Enforce resource naming rules",
metadata: { assignedBy: "Special Someone" },
nonComplianceMessages: [
{ message: "Resource names must start with 'DeptA' and end with '-LC'." },
],
parameters: { prefix: { value: "DeptA" }, suffix: { value: "-LC" } },
policyDefinitionId:
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
};
const credential = new DefaultAzureCredential();
const client = new PolicyClient(credential);
const result = await client.policyAssignments.create(scope, policyAssignmentName, parameters);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"properties": {
"displayName": "Enforce resource naming rules",
"description": "Force resource names to begin with given DeptA and end with -LC",
"metadata": {
"assignedBy": "Special Someone"
},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
"definitionVersion": "1.*.*",
"notScopes": [],
"parameters": {
"prefix": {
"value": "DeptA"
},
"suffix": {
"value": "-LC"
}
},
"enforcementMode": "Default",
"scope": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2",
"nonComplianceMessages": [
{
"message": "Resource names must start with 'DeptA' and end with '-LC'."
}
]
},
"id": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/EnforceNaming",
"type": "Microsoft.Authorization/policyAssignments",
"name": "EnforceNaming"
}
Create or update a policy assignment with a system assigned identity
Sample request
PUT https://management.azure.com/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/EnforceNaming?api-version=2023-04-01
{
"location": "eastus",
"identity": {
"type": "SystemAssigned"
},
"properties": {
"displayName": "Enforce resource naming rules",
"description": "Force resource names to begin with given DeptA and end with -LC",
"metadata": {
"assignedBy": "Foo Bar"
},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
"parameters": {
"prefix": {
"value": "DeptA"
},
"suffix": {
"value": "-LC"
}
},
"enforcementMode": "Default"
}
}
import com.azure.core.management.serializer.SerializerFactory;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.resourcemanager.resources.fluent.models.PolicyAssignmentInner;
import com.azure.resourcemanager.resources.models.EnforcementMode;
import com.azure.resourcemanager.resources.models.Identity;
import com.azure.resourcemanager.resources.models.ParameterValuesValue;
import com.azure.resourcemanager.resources.models.ResourceIdentityType;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for PolicyAssignments Create.
*/
public final class Main {
/*
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/
* createPolicyAssignmentWithIdentity.json
*/
/**
* Sample code: Create or update a policy assignment with a system assigned identity.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createOrUpdateAPolicyAssignmentWithASystemAssignedIdentity(
com.azure.resourcemanager.AzureResourceManager azure) throws IOException {
azure.genericResources().manager().policyClient().getPolicyAssignments().createWithResponse(
"subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "EnforceNaming",
new PolicyAssignmentInner().withLocation("eastus")
.withIdentity(new Identity().withType(ResourceIdentityType.SYSTEM_ASSIGNED))
.withDisplayName("Enforce resource naming rules")
.withPolicyDefinitionId(
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming")
.withParameters(mapOf("prefix", new ParameterValuesValue().withValue("DeptA"), "suffix",
new ParameterValuesValue().withValue("-LC")))
.withDescription("Force resource names to begin with given DeptA and end with -LC")
.withMetadata(SerializerFactory.createDefaultManagementSerializerAdapter()
.deserialize("{\"assignedBy\":\"Foo Bar\"}", Object.class, SerializerEncoding.JSON))
.withEnforcementMode(EnforcementMode.DEFAULT),
com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armpolicy_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armpolicy"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/219b2e3ef270f18149774eb2793b48baacde982f/specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithIdentity.json
func ExampleAssignmentsClient_Create_createOrUpdateAPolicyAssignmentWithASystemAssignedIdentity() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armpolicy.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
_, err = clientFactory.NewAssignmentsClient().Create(ctx, "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "EnforceNaming", armpolicy.Assignment{
Identity: &armpolicy.Identity{
Type: to.Ptr(armpolicy.ResourceIdentityTypeSystemAssigned),
},
Location: to.Ptr("eastus"),
Properties: &armpolicy.AssignmentProperties{
Description: to.Ptr("Force resource names to begin with given DeptA and end with -LC"),
DisplayName: to.Ptr("Enforce resource naming rules"),
EnforcementMode: to.Ptr(armpolicy.EnforcementModeDefault),
Metadata: map[string]any{
"assignedBy": "Foo Bar",
},
Parameters: map[string]*armpolicy.ParameterValuesValue{
"prefix": {
Value: "DeptA",
},
"suffix": {
Value: "-LC",
},
},
PolicyDefinitionID: to.Ptr("/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming"),
},
}, nil)
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { PolicyClient } = require("@azure/arm-policy");
const { DefaultAzureCredential } = require("@azure/identity");
require("dotenv/config");
/**
* This sample demonstrates how to This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
*
* @summary This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithIdentity.json
*/
async function createOrUpdateAPolicyAssignmentWithASystemAssignedIdentity() {
const scope = "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2";
const policyAssignmentName = "EnforceNaming";
const parameters = {
description: "Force resource names to begin with given DeptA and end with -LC",
displayName: "Enforce resource naming rules",
enforcementMode: "Default",
identity: { type: "SystemAssigned" },
location: "eastus",
metadata: { assignedBy: "Foo Bar" },
parameters: { prefix: { value: "DeptA" }, suffix: { value: "-LC" } },
policyDefinitionId:
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
};
const credential = new DefaultAzureCredential();
const client = new PolicyClient(credential);
const result = await client.policyAssignments.create(scope, policyAssignmentName, parameters);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"properties": {
"displayName": "Enforce resource naming rules",
"description": "Force resource names to begin with given DeptA and end with -LC",
"metadata": {
"assignedBy": "Special Someone"
},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
"definitionVersion": "1.*.*",
"notScopes": [],
"parameters": {
"prefix": {
"value": "DeptA"
},
"suffix": {
"value": "-LC"
}
},
"enforcementMode": "Default",
"scope": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2"
},
"identity": {
"type": "SystemAssigned",
"principalId": "e6d23f8d-af97-4fbc-bda6-00604e4e3d0a",
"tenantId": "4bee2b8a-1bee-47c2-90e9-404241551135"
},
"location": "eastus",
"id": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/EnforceNaming",
"type": "Microsoft.Authorization/policyAssignments",
"name": "EnforceNaming"
}
Create or update a policy assignment with a user assigned identity
Sample request
PUT https://management.azure.com/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/EnforceNaming?api-version=2023-04-01
{
"location": "eastus",
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/testResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-identity": {}
}
},
"properties": {
"displayName": "Enforce resource naming rules",
"description": "Force resource names to begin with given DeptA and end with -LC",
"metadata": {
"assignedBy": "Foo Bar"
},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
"parameters": {
"prefix": {
"value": "DeptA"
},
"suffix": {
"value": "-LC"
}
},
"enforcementMode": "Default"
}
}
import com.azure.core.management.serializer.SerializerFactory;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.resourcemanager.resources.fluent.models.PolicyAssignmentInner;
import com.azure.resourcemanager.resources.models.EnforcementMode;
import com.azure.resourcemanager.resources.models.Identity;
import com.azure.resourcemanager.resources.models.IdentityUserAssignedIdentitiesValue;
import com.azure.resourcemanager.resources.models.ParameterValuesValue;
import com.azure.resourcemanager.resources.models.ResourceIdentityType;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for PolicyAssignments Create.
*/
public final class Main {
/*
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/
* createPolicyAssignmentWithUserAssignedIdentity.json
*/
/**
* Sample code: Create or update a policy assignment with a user assigned identity.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createOrUpdateAPolicyAssignmentWithAUserAssignedIdentity(
com.azure.resourcemanager.AzureResourceManager azure) throws IOException {
azure.genericResources().manager().policyClient().getPolicyAssignments().createWithResponse(
"subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "EnforceNaming",
new PolicyAssignmentInner().withLocation("eastus").withIdentity(new Identity()
.withType(ResourceIdentityType.USER_ASSIGNED)
.withUserAssignedIdentities(mapOf(
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/testResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-identity",
new IdentityUserAssignedIdentitiesValue())))
.withDisplayName("Enforce resource naming rules")
.withPolicyDefinitionId(
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming")
.withParameters(mapOf("prefix", new ParameterValuesValue().withValue("DeptA"), "suffix",
new ParameterValuesValue().withValue("-LC")))
.withDescription("Force resource names to begin with given DeptA and end with -LC")
.withMetadata(SerializerFactory.createDefaultManagementSerializerAdapter()
.deserialize("{\"assignedBy\":\"Foo Bar\"}", Object.class, SerializerEncoding.JSON))
.withEnforcementMode(EnforcementMode.DEFAULT),
com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armpolicy_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armpolicy"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/219b2e3ef270f18149774eb2793b48baacde982f/specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithUserAssignedIdentity.json
func ExampleAssignmentsClient_Create_createOrUpdateAPolicyAssignmentWithAUserAssignedIdentity() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armpolicy.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
_, err = clientFactory.NewAssignmentsClient().Create(ctx, "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "EnforceNaming", armpolicy.Assignment{
Identity: &armpolicy.Identity{
Type: to.Ptr(armpolicy.ResourceIdentityTypeUserAssigned),
UserAssignedIdentities: map[string]*armpolicy.UserAssignedIdentitiesValue{
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/testResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-identity": {},
},
},
Location: to.Ptr("eastus"),
Properties: &armpolicy.AssignmentProperties{
Description: to.Ptr("Force resource names to begin with given DeptA and end with -LC"),
DisplayName: to.Ptr("Enforce resource naming rules"),
EnforcementMode: to.Ptr(armpolicy.EnforcementModeDefault),
Metadata: map[string]any{
"assignedBy": "Foo Bar",
},
Parameters: map[string]*armpolicy.ParameterValuesValue{
"prefix": {
Value: "DeptA",
},
"suffix": {
Value: "-LC",
},
},
PolicyDefinitionID: to.Ptr("/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming"),
},
}, nil)
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { PolicyClient } = require("@azure/arm-policy");
const { DefaultAzureCredential } = require("@azure/identity");
require("dotenv/config");
/**
* This sample demonstrates how to This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
*
* @summary This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithUserAssignedIdentity.json
*/
async function createOrUpdateAPolicyAssignmentWithAUserAssignedIdentity() {
const scope = "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2";
const policyAssignmentName = "EnforceNaming";
const parameters = {
description: "Force resource names to begin with given DeptA and end with -LC",
displayName: "Enforce resource naming rules",
enforcementMode: "Default",
identity: {
type: "UserAssigned",
userAssignedIdentities: {
"/subscriptions/ae640e6bBa3e42569d622993eecfa6f2/resourceGroups/testResourceGroup/providers/MicrosoftManagedIdentity/userAssignedIdentities/testIdentity":
{},
},
},
location: "eastus",
metadata: { assignedBy: "Foo Bar" },
parameters: { prefix: { value: "DeptA" }, suffix: { value: "-LC" } },
policyDefinitionId:
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
};
const credential = new DefaultAzureCredential();
const client = new PolicyClient(credential);
const result = await client.policyAssignments.create(scope, policyAssignmentName, parameters);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"properties": {
"displayName": "Enforce resource naming rules",
"description": "Force resource names to begin with given DeptA and end with -LC",
"metadata": {
"assignedBy": "Special Someone"
},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
"definitionVersion": "1.*.*",
"notScopes": [],
"parameters": {
"prefix": {
"value": "DeptA"
},
"suffix": {
"value": "-LC"
}
},
"enforcementMode": "Default",
"scope": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2"
},
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/testResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-identity": {
"principalId": "e6d23f8d-af97-4fbc-bda6-00604e4e3d0a",
"clientId": "4bee2b8a-1bee-47c2-90e9-404241551135"
}
}
},
"location": "eastus",
"id": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/EnforceNaming",
"type": "Microsoft.Authorization/policyAssignments",
"name": "EnforceNaming"
}
Create or update a policy assignment with multiple non-compliance messages
Sample request
PUT https://management.azure.com/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/securityInitAssignment?api-version=2023-04-01
{
"properties": {
"displayName": "Enforce security policies",
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/securityInitiative",
"nonComplianceMessages": [
{
"message": "Resources must comply with all internal security policies. See <internal site URL> for more info."
},
{
"message": "Resource names must start with 'DeptA' and end with '-LC'.",
"policyDefinitionReferenceId": "10420126870854049575"
},
{
"message": "Storage accounts must have firewall rules configured.",
"policyDefinitionReferenceId": "8572513655450389710"
}
]
}
}
import com.azure.resourcemanager.resources.fluent.models.PolicyAssignmentInner;
import com.azure.resourcemanager.resources.models.NonComplianceMessage;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for PolicyAssignments Create.
*/
public final class Main {
/*
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/
* createPolicyAssignmentNonComplianceMessages.json
*/
/**
* Sample code: Create or update a policy assignment with multiple non-compliance messages.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createOrUpdateAPolicyAssignmentWithMultipleNonComplianceMessages(
com.azure.resourcemanager.AzureResourceManager azure) {
azure.genericResources().manager().policyClient().getPolicyAssignments().createWithResponse(
"subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "securityInitAssignment",
new PolicyAssignmentInner().withDisplayName("Enforce security policies").withPolicyDefinitionId(
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/securityInitiative")
.withNonComplianceMessages(Arrays.asList(new NonComplianceMessage().withMessage(
"Resources must comply with all internal security policies. See <internal site URL> for more info."),
new NonComplianceMessage().withMessage("Resource names must start with 'DeptA' and end with '-LC'.")
.withPolicyDefinitionReferenceId("10420126870854049575"),
new NonComplianceMessage().withMessage("Storage accounts must have firewall rules configured.")
.withPolicyDefinitionReferenceId("8572513655450389710"))),
com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armpolicy_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armpolicy"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/219b2e3ef270f18149774eb2793b48baacde982f/specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentNonComplianceMessages.json
func ExampleAssignmentsClient_Create_createOrUpdateAPolicyAssignmentWithMultipleNonComplianceMessages() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armpolicy.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
_, err = clientFactory.NewAssignmentsClient().Create(ctx, "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "securityInitAssignment", armpolicy.Assignment{
Properties: &armpolicy.AssignmentProperties{
DisplayName: to.Ptr("Enforce security policies"),
NonComplianceMessages: []*armpolicy.NonComplianceMessage{
{
Message: to.Ptr("Resources must comply with all internal security policies. See <internal site URL> for more info."),
},
{
Message: to.Ptr("Resource names must start with 'DeptA' and end with '-LC'."),
PolicyDefinitionReferenceID: to.Ptr("10420126870854049575"),
},
{
Message: to.Ptr("Storage accounts must have firewall rules configured."),
PolicyDefinitionReferenceID: to.Ptr("8572513655450389710"),
}},
PolicyDefinitionID: to.Ptr("/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/securityInitiative"),
},
}, nil)
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { PolicyClient } = require("@azure/arm-policy");
const { DefaultAzureCredential } = require("@azure/identity");
require("dotenv/config");
/**
* This sample demonstrates how to This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
*
* @summary This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentNonComplianceMessages.json
*/
async function createOrUpdateAPolicyAssignmentWithMultipleNonComplianceMessages() {
const scope = "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2";
const policyAssignmentName = "securityInitAssignment";
const parameters = {
displayName: "Enforce security policies",
nonComplianceMessages: [
{
message:
"Resources must comply with all internal security policies. See <internal site URL> for more info.",
},
{
message: "Resource names must start with 'DeptA' and end with '-LC'.",
policyDefinitionReferenceId: "10420126870854049575",
},
{
message: "Storage accounts must have firewall rules configured.",
policyDefinitionReferenceId: "8572513655450389710",
},
],
policyDefinitionId:
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/securityInitiative",
};
const credential = new DefaultAzureCredential();
const client = new PolicyClient(credential);
const result = await client.policyAssignments.create(scope, policyAssignmentName, parameters);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"properties": {
"displayName": "Enforce security policies",
"metadata": {
"assignedBy": "User 1"
},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/securityInitiative",
"definitionVersion": "1.*.*",
"notScopes": [],
"enforcementMode": "Default",
"scope": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2",
"nonComplianceMessages": [
{
"message": "Resources must comply with all internal security policies. See <internal site URL> for more info."
},
{
"message": "Resource names must start with 'DeptA' and end with '-LC'.",
"policyDefinitionReferenceId": "10420126870854049575"
},
{
"message": "Storage accounts must have firewall rules configured.",
"policyDefinitionReferenceId": "8572513655450389710"
}
]
},
"id": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/securityInitAssignment",
"type": "Microsoft.Authorization/policyAssignments",
"name": "securityInitAssignment"
}
Create or update a policy assignment with overrides
Sample request
PUT https://management.azure.com/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/CostManagement?api-version=2023-04-01
{
"properties": {
"displayName": "Limit the resource location and resource SKU",
"description": "Limit the resource location and resource SKU",
"metadata": {
"assignedBy": "Special Someone"
},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement",
"overrides": [
{
"kind": "policyEffect",
"value": "Audit",
"selectors": [
{
"kind": "policyDefinitionReferenceId",
"in": [
"Limit_Skus",
"Limit_Locations"
]
}
]
}
]
}
}
import com.azure.core.management.serializer.SerializerFactory;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.resourcemanager.resources.fluent.models.PolicyAssignmentInner;
import com.azure.resourcemanager.resources.models.OverrideKind;
import com.azure.resourcemanager.resources.models.OverrideModel;
import com.azure.resourcemanager.resources.models.Selector;
import com.azure.resourcemanager.resources.models.SelectorKind;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for PolicyAssignments Create.
*/
public final class Main {
/*
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/
* createPolicyAssignmentWithOverrides.json
*/
/**
* Sample code: Create or update a policy assignment with overrides.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createOrUpdateAPolicyAssignmentWithOverrides(
com.azure.resourcemanager.AzureResourceManager azure) throws IOException {
azure.genericResources().manager().policyClient().getPolicyAssignments().createWithResponse(
"subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "CostManagement",
new PolicyAssignmentInner().withDisplayName("Limit the resource location and resource SKU")
.withPolicyDefinitionId(
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement")
.withDescription("Limit the resource location and resource SKU")
.withMetadata(SerializerFactory.createDefaultManagementSerializerAdapter()
.deserialize("{\"assignedBy\":\"Special Someone\"}", Object.class, SerializerEncoding.JSON))
.withOverrides(Arrays.asList(new OverrideModel().withKind(OverrideKind.POLICY_EFFECT).withValue("Audit")
.withSelectors(Arrays.asList(new Selector().withKind(SelectorKind.POLICY_DEFINITION_REFERENCE_ID)
.withIn(Arrays.asList("Limit_Skus", "Limit_Locations")))))),
com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armpolicy_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armpolicy"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/219b2e3ef270f18149774eb2793b48baacde982f/specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithOverrides.json
func ExampleAssignmentsClient_Create_createOrUpdateAPolicyAssignmentWithOverrides() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armpolicy.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
_, err = clientFactory.NewAssignmentsClient().Create(ctx, "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "CostManagement", armpolicy.Assignment{
Properties: &armpolicy.AssignmentProperties{
Description: to.Ptr("Limit the resource location and resource SKU"),
DisplayName: to.Ptr("Limit the resource location and resource SKU"),
Metadata: map[string]any{
"assignedBy": "Special Someone",
},
Overrides: []*armpolicy.Override{
{
Kind: to.Ptr(armpolicy.OverrideKindPolicyEffect),
Selectors: []*armpolicy.Selector{
{
In: []*string{
to.Ptr("Limit_Skus"),
to.Ptr("Limit_Locations")},
Kind: to.Ptr(armpolicy.SelectorKindPolicyDefinitionReferenceID),
}},
Value: to.Ptr("Audit"),
}},
PolicyDefinitionID: to.Ptr("/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement"),
},
}, nil)
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { PolicyClient } = require("@azure/arm-policy");
const { DefaultAzureCredential } = require("@azure/identity");
require("dotenv/config");
/**
* This sample demonstrates how to This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
*
* @summary This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithOverrides.json
*/
async function createOrUpdateAPolicyAssignmentWithOverrides() {
const scope = "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2";
const policyAssignmentName = "CostManagement";
const parameters = {
description: "Limit the resource location and resource SKU",
displayName: "Limit the resource location and resource SKU",
metadata: { assignedBy: "Special Someone" },
overrides: [
{
kind: "policyEffect",
selectors: [
{
in: ["Limit_Skus", "Limit_Locations"],
kind: "policyDefinitionReferenceId",
},
],
value: "Audit",
},
],
policyDefinitionId:
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement",
};
const credential = new DefaultAzureCredential();
const client = new PolicyClient(credential);
const result = await client.policyAssignments.create(scope, policyAssignmentName, parameters);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"properties": {
"displayName": "Limit the resource location and resource SKU",
"description": "Limit the resource location and resource SKU",
"metadata": {
"assignedBy": "Special Someone"
},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement",
"definitionVersion": "1.*.*",
"notScopes": [],
"enforcementMode": "Default",
"scope": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2",
"overrides": [
{
"kind": "policyEffect",
"value": "Audit",
"selectors": [
{
"kind": "policyDefinitionReferenceId",
"in": [
"Limit_Skus",
"Limit_Locations"
]
}
]
}
]
},
"id": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/CostManagement",
"type": "Microsoft.Authorization/policyAssignments",
"name": "CostManagement"
}
Create or update a policy assignment with resource selectors
Sample request
PUT https://management.azure.com/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/CostManagement?api-version=2023-04-01
{
"properties": {
"displayName": "Limit the resource location and resource SKU",
"description": "Limit the resource location and resource SKU",
"metadata": {
"assignedBy": "Special Someone"
},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement",
"resourceSelectors": [
{
"name": "SDPRegions",
"selectors": [
{
"kind": "resourceLocation",
"in": [
"eastus2euap",
"centraluseuap"
]
}
]
}
]
}
}
import com.azure.core.management.serializer.SerializerFactory;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.resourcemanager.resources.fluent.models.PolicyAssignmentInner;
import com.azure.resourcemanager.resources.models.ResourceSelector;
import com.azure.resourcemanager.resources.models.Selector;
import com.azure.resourcemanager.resources.models.SelectorKind;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for PolicyAssignments Create.
*/
public final class Main {
/*
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/
* createPolicyAssignmentWithResourceSelectors.json
*/
/**
* Sample code: Create or update a policy assignment with resource selectors.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createOrUpdateAPolicyAssignmentWithResourceSelectors(
com.azure.resourcemanager.AzureResourceManager azure) throws IOException {
azure.genericResources().manager().policyClient().getPolicyAssignments().createWithResponse(
"subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "CostManagement",
new PolicyAssignmentInner().withDisplayName("Limit the resource location and resource SKU")
.withPolicyDefinitionId(
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement")
.withDescription("Limit the resource location and resource SKU")
.withMetadata(SerializerFactory.createDefaultManagementSerializerAdapter()
.deserialize("{\"assignedBy\":\"Special Someone\"}", Object.class, SerializerEncoding.JSON))
.withResourceSelectors(
Arrays.asList(new ResourceSelector().withName("SDPRegions")
.withSelectors(Arrays.asList(new Selector().withKind(SelectorKind.RESOURCE_LOCATION)
.withIn(Arrays.asList("eastus2euap", "centraluseuap")))))),
com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armpolicy_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armpolicy"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/219b2e3ef270f18149774eb2793b48baacde982f/specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithResourceSelectors.json
func ExampleAssignmentsClient_Create_createOrUpdateAPolicyAssignmentWithResourceSelectors() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armpolicy.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
_, err = clientFactory.NewAssignmentsClient().Create(ctx, "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "CostManagement", armpolicy.Assignment{
Properties: &armpolicy.AssignmentProperties{
Description: to.Ptr("Limit the resource location and resource SKU"),
DisplayName: to.Ptr("Limit the resource location and resource SKU"),
Metadata: map[string]any{
"assignedBy": "Special Someone",
},
PolicyDefinitionID: to.Ptr("/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement"),
ResourceSelectors: []*armpolicy.ResourceSelector{
{
Name: to.Ptr("SDPRegions"),
Selectors: []*armpolicy.Selector{
{
In: []*string{
to.Ptr("eastus2euap"),
to.Ptr("centraluseuap")},
Kind: to.Ptr(armpolicy.SelectorKindResourceLocation),
}},
}},
},
}, nil)
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { PolicyClient } = require("@azure/arm-policy");
const { DefaultAzureCredential } = require("@azure/identity");
require("dotenv/config");
/**
* This sample demonstrates how to This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
*
* @summary This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithResourceSelectors.json
*/
async function createOrUpdateAPolicyAssignmentWithResourceSelectors() {
const scope = "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2";
const policyAssignmentName = "CostManagement";
const parameters = {
description: "Limit the resource location and resource SKU",
displayName: "Limit the resource location and resource SKU",
metadata: { assignedBy: "Special Someone" },
policyDefinitionId:
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement",
resourceSelectors: [
{
name: "SDPRegions",
selectors: [{ in: ["eastus2euap", "centraluseuap"], kind: "resourceLocation" }],
},
],
};
const credential = new DefaultAzureCredential();
const client = new PolicyClient(credential);
const result = await client.policyAssignments.create(scope, policyAssignmentName, parameters);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"properties": {
"displayName": "Limit the resource location and resource SKU",
"description": "Limit the resource location and resource SKU",
"metadata": {
"assignedBy": "Special Someone"
},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement",
"definitionVersion": "1.*.*",
"notScopes": [],
"enforcementMode": "Default",
"scope": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2",
"resourceSelectors": [
{
"name": "SDPRegions",
"selectors": [
{
"kind": "resourceLocation",
"in": [
"eastus2euap",
"centraluseuap"
]
}
]
}
]
},
"id": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/CostManagement",
"type": "Microsoft.Authorization/policyAssignments",
"name": "CostManagement"
}
Create or update a policy assignment without enforcing policy effect during resource creation or update.
Sample request
PUT https://management.azure.com/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/EnforceNaming?api-version=2023-04-01
{
"properties": {
"displayName": "Enforce resource naming rules",
"description": "Force resource names to begin with given DeptA and end with -LC",
"metadata": {
"assignedBy": "Special Someone"
},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
"parameters": {
"prefix": {
"value": "DeptA"
},
"suffix": {
"value": "-LC"
}
},
"enforcementMode": "DoNotEnforce"
}
}
import com.azure.core.management.serializer.SerializerFactory;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.resourcemanager.resources.fluent.models.PolicyAssignmentInner;
import com.azure.resourcemanager.resources.models.EnforcementMode;
import com.azure.resourcemanager.resources.models.ParameterValuesValue;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Samples for PolicyAssignments Create.
*/
public final class Main {
/*
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/
* createPolicyAssignmentWithoutEnforcement.json
*/
/**
* Sample code: Create or update a policy assignment without enforcing policy effect during resource creation or
* update.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createOrUpdateAPolicyAssignmentWithoutEnforcingPolicyEffectDuringResourceCreationOrUpdate(
com.azure.resourcemanager.AzureResourceManager azure) throws IOException {
azure.genericResources().manager().policyClient().getPolicyAssignments().createWithResponse(
"subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "EnforceNaming",
new PolicyAssignmentInner().withDisplayName("Enforce resource naming rules").withPolicyDefinitionId(
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming")
.withParameters(mapOf("prefix", new ParameterValuesValue().withValue("DeptA"), "suffix",
new ParameterValuesValue().withValue("-LC")))
.withDescription("Force resource names to begin with given DeptA and end with -LC")
.withMetadata(SerializerFactory.createDefaultManagementSerializerAdapter()
.deserialize("{\"assignedBy\":\"Special Someone\"}", Object.class, SerializerEncoding.JSON))
.withEnforcementMode(EnforcementMode.DO_NOT_ENFORCE),
com.azure.core.util.Context.NONE);
}
// Use "Map.of" if available
@SuppressWarnings("unchecked")
private static <T> Map<String, T> mapOf(Object... inputs) {
Map<String, T> map = new HashMap<>();
for (int i = 0; i < inputs.length; i += 2) {
String key = (String) inputs[i];
T value = (T) inputs[i + 1];
map.put(key, value);
}
return map;
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
package armpolicy_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armpolicy"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/219b2e3ef270f18149774eb2793b48baacde982f/specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithoutEnforcement.json
func ExampleAssignmentsClient_Create_createOrUpdateAPolicyAssignmentWithoutEnforcingPolicyEffectDuringResourceCreationOrUpdate() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armpolicy.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
_, err = clientFactory.NewAssignmentsClient().Create(ctx, "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", "EnforceNaming", armpolicy.Assignment{
Properties: &armpolicy.AssignmentProperties{
Description: to.Ptr("Force resource names to begin with given DeptA and end with -LC"),
DisplayName: to.Ptr("Enforce resource naming rules"),
EnforcementMode: to.Ptr(armpolicy.EnforcementModeDoNotEnforce),
Metadata: map[string]any{
"assignedBy": "Special Someone",
},
Parameters: map[string]*armpolicy.ParameterValuesValue{
"prefix": {
Value: "DeptA",
},
"suffix": {
Value: "-LC",
},
},
PolicyDefinitionID: to.Ptr("/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming"),
},
}, nil)
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
const { PolicyClient } = require("@azure/arm-policy");
const { DefaultAzureCredential } = require("@azure/identity");
require("dotenv/config");
/**
* This sample demonstrates how to This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
*
* @summary This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group.
* x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithoutEnforcement.json
*/
async function createOrUpdateAPolicyAssignmentWithoutEnforcingPolicyEffectDuringResourceCreationOrUpdate() {
const scope = "subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2";
const policyAssignmentName = "EnforceNaming";
const parameters = {
description: "Force resource names to begin with given DeptA and end with -LC",
displayName: "Enforce resource naming rules",
enforcementMode: "DoNotEnforce",
metadata: { assignedBy: "Special Someone" },
parameters: { prefix: { value: "DeptA" }, suffix: { value: "-LC" } },
policyDefinitionId:
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
};
const credential = new DefaultAzureCredential();
const client = new PolicyClient(credential);
const result = await client.policyAssignments.create(scope, policyAssignmentName, parameters);
console.log(result);
}
To use the Azure SDK library in your project, see this documentation. To provide feedback on this code sample, open a GitHub issue
Sample response
{
"properties": {
"displayName": "Enforce resource naming rules",
"description": "Force resource names to begin with given DeptA and end with -LC",
"metadata": {
"assignedBy": "Special Someone"
},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
"definitionVersion": "1.*.*",
"notScopes": [],
"parameters": {
"prefix": {
"value": "DeptA"
},
"suffix": {
"value": "-LC"
}
},
"enforcementMode": "DoNotEnforce",
"scope": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2"
},
"id": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/EnforceNaming",
"type": "Microsoft.Authorization/policyAssignments",
"name": "EnforceNaming"
}
Definitions
Name |
Description |
CloudError
|
An error response from a policy operation.
|
createdByType
|
The type of identity that created the resource.
|
enforcementMode
|
The policy assignment enforcement mode. Possible values are Default and DoNotEnforce.
|
ErrorAdditionalInfo
|
The resource management error additional info.
|
ErrorResponse
|
Error Response
|
Identity
|
Identity for the resource. Policy assignments support a maximum of one identity. That is either a system assigned identity or a single user assigned identity.
|
NonComplianceMessage
|
A message that describes why a resource is non-compliant with the policy. This is shown in 'deny' error messages and on resource's non-compliant compliance results.
|
Override
|
The policy property value override.
|
OverrideKind
|
The override kind.
|
ParameterValuesValue
|
The value of a parameter.
|
PolicyAssignment
|
The policy assignment.
|
ResourceIdentityType
|
The identity type. This is the only required field when adding a system or user assigned identity to a resource.
|
ResourceSelector
|
The resource selector to filter policies by resource properties.
|
Selector
|
The selector expression.
|
SelectorKind
|
The selector kind.
|
systemData
|
Metadata pertaining to creation and last modification of the resource.
|
UserAssignedIdentities
|
The user identity associated with the policy. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
|
CloudError
Object
An error response from a policy operation.
Name |
Type |
Description |
error
|
ErrorResponse
|
Error Response
Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.)
|
createdByType
Enumeration
The type of identity that created the resource.
Value |
Description |
Application
|
|
Key
|
|
ManagedIdentity
|
|
User
|
|
enforcementMode
Enumeration
The policy assignment enforcement mode. Possible values are Default and DoNotEnforce.
Value |
Description |
Default
|
The policy effect is enforced during resource creation or update.
|
DoNotEnforce
|
The policy effect is not enforced during resource creation or update.
|
ErrorAdditionalInfo
Object
The resource management error additional info.
Name |
Type |
Description |
info
|
object
|
The additional info.
|
type
|
string
|
The additional info type.
|
ErrorResponse
Object
Error Response
Name |
Type |
Description |
additionalInfo
|
ErrorAdditionalInfo[]
|
The error additional info.
|
code
|
string
|
The error code.
|
details
|
ErrorResponse[]
|
The error details.
|
message
|
string
|
The error message.
|
target
|
string
|
The error target.
|
Identity
Object
Identity for the resource. Policy assignments support a maximum of one identity. That is either a system assigned identity or a single user assigned identity.
Name |
Type |
Description |
principalId
|
string
|
The principal ID of the resource identity. This property will only be provided for a system assigned identity
|
tenantId
|
string
|
The tenant ID of the resource identity. This property will only be provided for a system assigned identity
|
type
|
ResourceIdentityType
|
The identity type. This is the only required field when adding a system or user assigned identity to a resource.
|
userAssignedIdentities
|
UserAssignedIdentities
|
The user identity associated with the policy. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
|
NonComplianceMessage
Object
A message that describes why a resource is non-compliant with the policy. This is shown in 'deny' error messages and on resource's non-compliant compliance results.
Name |
Type |
Description |
message
|
string
|
A message that describes why a resource is non-compliant with the policy. This is shown in 'deny' error messages and on resource's non-compliant compliance results.
|
policyDefinitionReferenceId
|
string
|
The policy definition reference ID within a policy set definition the message is intended for. This is only applicable if the policy assignment assigns a policy set definition. If this is not provided the message applies to all policies assigned by this policy assignment.
|
Override
Object
The policy property value override.
Name |
Type |
Description |
kind
|
OverrideKind
|
The override kind.
|
selectors
|
Selector[]
|
The list of the selector expressions.
|
value
|
string
|
The value to override the policy property.
|
OverrideKind
Enumeration
The override kind.
Value |
Description |
policyEffect
|
It will override the policy effect type.
|
ParameterValuesValue
Object
The value of a parameter.
Name |
Type |
Description |
value
|
object
|
The value of the parameter.
|
PolicyAssignment
Object
The policy assignment.
Name |
Type |
Default value |
Description |
id
|
string
|
|
The ID of the policy assignment.
|
identity
|
Identity
|
|
The managed identity associated with the policy assignment.
|
location
|
string
|
|
The location of the policy assignment. Only required when utilizing managed identity.
|
name
|
string
|
|
The name of the policy assignment.
|
properties.definitionVersion
|
string
|
|
The version of the policy definition to use.
|
properties.description
|
string
|
|
This message will be part of response in case of policy violation.
|
properties.displayName
|
string
|
|
The display name of the policy assignment.
|
properties.effectiveDefinitionVersion
|
string
|
|
The effective version of the policy definition in use. This is only present if requested via the $expand query parameter.
|
properties.enforcementMode
|
enforcementMode
|
Default
|
The policy assignment enforcement mode. Possible values are Default and DoNotEnforce.
|
properties.latestDefinitionVersion
|
string
|
|
The latest version of the policy definition available. This is only present if requested via the $expand query parameter.
|
properties.metadata
|
object
|
|
The policy assignment metadata. Metadata is an open ended object and is typically a collection of key value pairs.
|
properties.nonComplianceMessages
|
NonComplianceMessage[]
|
|
The messages that describe why a resource is non-compliant with the policy.
|
properties.notScopes
|
string[]
|
|
The policy's excluded scopes.
|
properties.overrides
|
Override[]
|
|
The policy property value override.
|
properties.parameters
|
<string,
ParameterValuesValue>
|
|
The parameter values for the assigned policy rule. The keys are the parameter names.
|
properties.policyDefinitionId
|
string
|
|
The ID of the policy definition or policy set definition being assigned.
|
properties.resourceSelectors
|
ResourceSelector[]
|
|
The resource selector list to filter policies by resource properties.
|
properties.scope
|
string
|
|
The scope for the policy assignment.
|
systemData
|
systemData
|
|
The system metadata relating to this resource.
|
type
|
string
|
|
The type of the policy assignment.
|
ResourceIdentityType
Enumeration
The identity type. This is the only required field when adding a system or user assigned identity to a resource.
Value |
Description |
None
|
Indicates that no identity is associated with the resource or that the existing identity should be removed.
|
SystemAssigned
|
Indicates that a system assigned identity is associated with the resource.
|
UserAssigned
|
Indicates that a system assigned identity is associated with the resource.
|
ResourceSelector
Object
The resource selector to filter policies by resource properties.
Name |
Type |
Description |
name
|
string
|
The name of the resource selector.
|
selectors
|
Selector[]
|
The list of the selector expressions.
|
Selector
Object
The selector expression.
Name |
Type |
Description |
in
|
string[]
|
The list of values to filter in.
|
kind
|
SelectorKind
|
The selector kind.
|
notIn
|
string[]
|
The list of values to filter out.
|
SelectorKind
Enumeration
The selector kind.
Value |
Description |
policyDefinitionReferenceId
|
The selector kind to filter policies by the policy definition reference ID.
|
resourceLocation
|
The selector kind to filter policies by the resource location.
|
resourceType
|
The selector kind to filter policies by the resource type.
|
resourceWithoutLocation
|
The selector kind to filter policies by the resource without location.
|
systemData
Object
Metadata pertaining to creation and last modification of the resource.
Name |
Type |
Description |
createdAt
|
string
(date-time)
|
The timestamp of resource creation (UTC).
|
createdBy
|
string
|
The identity that created the resource.
|
createdByType
|
createdByType
|
The type of identity that created the resource.
|
lastModifiedAt
|
string
(date-time)
|
The timestamp of resource last modification (UTC)
|
lastModifiedBy
|
string
|
The identity that last modified the resource.
|
lastModifiedByType
|
createdByType
|
The type of identity that last modified the resource.
|
UserAssignedIdentities
Object
The user identity associated with the policy. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.