此操作使用给定的范围和名称创建或更新策略分配。 策略分配适用于其范围内包含的所有资源。 例如,在资源组范围内分配策略时,该策略将应用于该组中的所有资源。
PUT https://management.azure.com/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}?api-version=2023-04-01
URI 参数
名称 |
在 |
必需 |
类型 |
说明 |
policyAssignmentName
|
path |
True
|
string
pattern: ^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$
|
策略分配的名称。
|
scope
|
path |
True
|
string
|
策略分配的范围。 有效范围包括:管理组(格式:'/providers/Microsoft.Management/managementGroups/{managementGroup}')、订阅(格式:'/subscriptions/{subscriptionId}')、资源组(格式:'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', 或资源(格式:'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'
|
api-version
|
query |
True
|
string
minLength: 1
|
用于此操作的 API 版本。
|
请求正文
名称 |
类型 |
说明 |
identity
|
Identity
|
与策略分配关联的托管标识。
|
location
|
string
|
策略分配的位置。 仅当使用托管标识时才需要。
|
properties.definitionVersion
|
string
|
要使用的策略定义的版本。
|
properties.description
|
string
|
如果发生策略冲突,此消息将是响应的一部分。
|
properties.displayName
|
string
|
策略分配的显示名称。
|
properties.enforcementMode
|
enforcementMode
|
策略分配强制模式。 可能的值为 Default 和 DoNotEnforce。
|
properties.metadata
|
object
|
策略分配元数据。 元数据是一个开放结束的对象,通常是键值对的集合。
|
properties.nonComplianceMessages
|
NonComplianceMessage[]
|
描述资源不符合策略的原因的消息。
|
properties.notScopes
|
string[]
|
策略的排除范围。
|
properties.overrides
|
Override[]
|
策略属性值重写。
|
properties.parameters
|
<string,
ParameterValuesValue>
|
分配的策略规则的参数值。 键是参数名称。
|
properties.policyDefinitionId
|
string
|
要分配的策略定义或策略集定义的 ID。
|
properties.resourceSelectors
|
ResourceSelector[]
|
按资源属性筛选策略的资源选择器列表。
|
响应
安全性
azure_auth
Azure Active Directory OAuth2 Flow。
类型:
oauth2
流向:
implicit
授权 URL:
https://login.microsoftonline.com/common/oauth2/authorize
作用域
名称 |
说明 |
user_impersonation
|
模拟用户帐户
|
示例
Create or update a policy assignment
示例请求
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
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource.policy import PolicyClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-resource
# USAGE
python create_policy_assignment.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = PolicyClient(
credential=DefaultAzureCredential(),
subscription_id="SUBSCRIPTION_ID",
)
response = client.policy_assignments.create(
scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2",
policy_assignment_name="EnforceNaming",
parameters={
"properties": {
"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",
}
},
)
print(response)
# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignment.json
if __name__ == "__main__":
main()
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
示例响应
{
"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
示例请求
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
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource.policy import PolicyClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-resource
# USAGE
python create_policy_assignment_with_identity.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = PolicyClient(
credential=DefaultAzureCredential(),
subscription_id="SUBSCRIPTION_ID",
)
response = client.policy_assignments.create(
scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2",
policy_assignment_name="EnforceNaming",
parameters={
"identity": {"type": "SystemAssigned"},
"location": "eastus",
"properties": {
"description": "Force resource names to begin with given DeptA and end with -LC",
"displayName": "Enforce resource naming rules",
"enforcementMode": "Default",
"metadata": {"assignedBy": "Foo Bar"},
"parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
},
},
)
print(response)
# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithIdentity.json
if __name__ == "__main__":
main()
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
示例响应
{
"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
示例请求
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
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource.policy import PolicyClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-resource
# USAGE
python create_policy_assignment_with_user_assigned_identity.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = PolicyClient(
credential=DefaultAzureCredential(),
subscription_id="SUBSCRIPTION_ID",
)
response = client.policy_assignments.create(
scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2",
policy_assignment_name="EnforceNaming",
parameters={
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/testResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-identity": {}
},
},
"location": "eastus",
"properties": {
"description": "Force resource names to begin with given DeptA and end with -LC",
"displayName": "Enforce resource naming rules",
"enforcementMode": "Default",
"metadata": {"assignedBy": "Foo Bar"},
"parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}},
"policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming",
},
},
)
print(response)
# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithUserAssignedIdentity.json
if __name__ == "__main__":
main()
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
示例响应
{
"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
示例请求
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
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource.policy import PolicyClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-resource
# USAGE
python create_policy_assignment_non_compliance_messages.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = PolicyClient(
credential=DefaultAzureCredential(),
subscription_id="SUBSCRIPTION_ID",
)
response = client.policy_assignments.create(
scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2",
policy_assignment_name="securityInitAssignment",
parameters={
"properties": {
"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",
}
},
)
print(response)
# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentNonComplianceMessages.json
if __name__ == "__main__":
main()
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
示例响应
{
"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
示例请求
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
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource.policy import PolicyClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-resource
# USAGE
python create_policy_assignment_with_overrides.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = PolicyClient(
credential=DefaultAzureCredential(),
subscription_id="SUBSCRIPTION_ID",
)
response = client.policy_assignments.create(
scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2",
policy_assignment_name="CostManagement",
parameters={
"properties": {
"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",
}
},
)
print(response)
# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithOverrides.json
if __name__ == "__main__":
main()
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
示例响应
{
"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
示例请求
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
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource.policy import PolicyClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-resource
# USAGE
python create_policy_assignment_with_resource_selectors.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = PolicyClient(
credential=DefaultAzureCredential(),
subscription_id="SUBSCRIPTION_ID",
)
response = client.policy_assignments.create(
scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2",
policy_assignment_name="CostManagement",
parameters={
"properties": {
"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"}],
}
],
}
},
)
print(response)
# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithResourceSelectors.json
if __name__ == "__main__":
main()
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
示例响应
{
"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.
示例请求
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
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource.policy import PolicyClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-resource
# USAGE
python create_policy_assignment_without_enforcement.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = PolicyClient(
credential=DefaultAzureCredential(),
subscription_id="SUBSCRIPTION_ID",
)
response = client.policy_assignments.create(
scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2",
policy_assignment_name="EnforceNaming",
parameters={
"properties": {
"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",
}
},
)
print(response)
# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2023-04-01/examples/createPolicyAssignmentWithoutEnforcement.json
if __name__ == "__main__":
main()
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
示例响应
{
"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"
}
定义
CloudError
Object
策略操作的错误响应。
名称 |
类型 |
说明 |
error
|
ErrorResponse
|
错误响应
所有 Azure 资源管理器 API 的常见错误响应,以返回失败操作的错误详细信息。 (这也遵循 OData 错误响应格式。)
|
createdByType
枚举
创建资源的标识的类型。
值 |
说明 |
User
|
|
Application
|
|
ManagedIdentity
|
|
Key
|
|
enforcementMode
枚举
策略分配强制模式。 可能的值为 Default 和 DoNotEnforce。
值 |
说明 |
Default
|
在资源创建或更新期间强制实施策略效果。
|
DoNotEnforce
|
在资源创建或更新期间,不会强制实施策略效果。
|
ErrorAdditionalInfo
Object
资源管理错误附加信息。
名称 |
类型 |
说明 |
info
|
object
|
其他信息。
|
type
|
string
|
其他信息类型。
|
ErrorResponse
Object
错误响应
Identity
Object
资源的标识。 策略分配最多支持一个标识。 这是系统分配的标识或单个用户分配的标识。
名称 |
类型 |
说明 |
principalId
|
string
|
资源标识的主体 ID。 此属性仅针对系统分配的标识提供
|
tenantId
|
string
|
资源标识的租户 ID。 此属性仅针对系统分配的标识提供
|
type
|
ResourceIdentityType
|
标识类型。 这是将系统或用户分配的标识添加到资源时的唯一必填字段。
|
userAssignedIdentities
|
UserAssignedIdentities
|
与策略关联的用户标识。 用户标识字典密钥引用的格式为 ARM 资源 ID:“/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}”。
|
NonComplianceMessage
Object
描述资源不符合策略的原因的消息。 这会显示在“拒绝”错误消息中,以及资源的不符合符合性结果。
名称 |
类型 |
说明 |
message
|
string
|
描述资源不符合策略的原因的消息。 这会显示在“拒绝”错误消息中,以及资源的不符合符合性结果。
|
policyDefinitionReferenceId
|
string
|
消息适用于的策略集定义中的策略定义引用 ID。 这仅适用于策略分配分配策略集定义。 如果未提供此消息,则消息适用于此策略分配分配的所有策略。
|
Override
Object
策略属性值重写。
OverrideKind
枚举
重写类型。
值 |
说明 |
policyEffect
|
它将替代策略效果类型。
|
ParameterValuesValue
Object
参数的值。
名称 |
类型 |
说明 |
value
|
object
|
参数的值。
|
PolicyAssignment
Object
策略分配。
名称 |
类型 |
默认值 |
说明 |
id
|
string
|
|
策略分配的 ID。
|
identity
|
Identity
|
|
与策略分配关联的托管标识。
|
location
|
string
|
|
策略分配的位置。 仅当使用托管标识时才需要。
|
name
|
string
|
|
策略分配的名称。
|
properties.definitionVersion
|
string
|
|
要使用的策略定义的版本。
|
properties.description
|
string
|
|
如果发生策略冲突,此消息将是响应的一部分。
|
properties.displayName
|
string
|
|
策略分配的显示名称。
|
properties.effectiveDefinitionVersion
|
string
|
|
正在使用的策略定义的有效版本。 仅当通过$expand查询参数请求时,才存在此参数。
|
properties.enforcementMode
|
enforcementMode
|
Default
|
策略分配强制模式。 可能的值为 Default 和 DoNotEnforce。
|
properties.latestDefinitionVersion
|
string
|
|
可用的策略定义的最新版本。 仅当通过$expand查询参数请求时,才存在此参数。
|
properties.metadata
|
object
|
|
策略分配元数据。 元数据是一个开放结束的对象,通常是键值对的集合。
|
properties.nonComplianceMessages
|
NonComplianceMessage[]
|
|
描述资源不符合策略的原因的消息。
|
properties.notScopes
|
string[]
|
|
策略的排除范围。
|
properties.overrides
|
Override[]
|
|
策略属性值重写。
|
properties.parameters
|
<string,
ParameterValuesValue>
|
|
分配的策略规则的参数值。 键是参数名称。
|
properties.policyDefinitionId
|
string
|
|
要分配的策略定义或策略集定义的 ID。
|
properties.resourceSelectors
|
ResourceSelector[]
|
|
按资源属性筛选策略的资源选择器列表。
|
properties.scope
|
string
|
|
策略分配的范围。
|
systemData
|
systemData
|
|
与此资源相关的系统元数据。
|
type
|
string
|
|
策略分配的类型。
|
ResourceIdentityType
枚举
标识类型。 这是将系统或用户分配的标识添加到资源时的唯一必填字段。
值 |
说明 |
SystemAssigned
|
指示系统分配的标识与资源相关联。
|
UserAssigned
|
指示系统分配的标识与资源相关联。
|
None
|
指示没有与资源关联的标识或应删除现有标识。
|
ResourceSelector
Object
按资源属性筛选策略的资源选择器。
名称 |
类型 |
说明 |
name
|
string
|
资源选择器的名称。
|
selectors
|
Selector[]
|
选择器表达式的列表。
|
Selector
Object
选择器表达式。
名称 |
类型 |
说明 |
in
|
string[]
|
要筛选的值列表。
|
kind
|
SelectorKind
|
选择器类型。
|
notIn
|
string[]
|
要筛选出的值列表。
|
SelectorKind
枚举
选择器类型。
值 |
说明 |
resourceLocation
|
按资源位置筛选策略的选择器类型。
|
resourceType
|
按资源类型筛选策略的选择器类型。
|
resourceWithoutLocation
|
按没有位置的资源筛选策略的选择器类型。
|
policyDefinitionReferenceId
|
按策略定义引用 ID 筛选策略的选择器类型。
|
systemData
Object
与创建和上次修改资源相关的元数据。
名称 |
类型 |
说明 |
createdAt
|
string
(date-time)
|
资源创建时间戳(UTC)。
|
createdBy
|
string
|
创建资源的标识。
|
createdByType
|
createdByType
|
创建资源的标识的类型。
|
lastModifiedAt
|
string
(date-time)
|
上次修改的资源时间戳(UTC)
|
lastModifiedBy
|
string
|
上次修改资源的标识。
|
lastModifiedByType
|
createdByType
|
上次修改资源的标识的类型。
|
UserAssignedIdentities
Object
与策略关联的用户标识。 用户标识字典密钥引用的格式为 ARM 资源 ID:“/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}”。