이 작업은 지정된 범위와 이름으로 정책 할당을 만들거나 업데이트합니다. 정책 할당은 해당 범위 내에 포함된 모든 리소스에 적용됩니다. 예를 들어 리소스 그룹 범위에서 정책을 할당하면 해당 정책이 그룹의 모든 리소스에 적용됩니다.
PUT https://management.azure.com/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}?api-version=2023-04-01
URI 매개 변수
Name |
In(다음 안에) |
필수 |
형식 |
Description |
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 버전입니다.
|
요청 본문
Name |
형식 |
Description |
identity
|
Identity
|
정책 할당과 연결된 관리 ID입니다.
|
___location
|
string
|
정책 할당의 위치입니다. 관리 ID를 활용하는 경우에만 필요합니다.
|
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[]
|
리소스 속성별로 정책을 필터링할 리소스 선택기 목록입니다.
|
응답
Name |
형식 |
Description |
201 Created
|
PolicyAssignment
|
만든 - 새 정책 할당에 대한 정보를 반환합니다.
|
Other Status Codes
|
CloudError
|
작업이 실패한 이유를 설명하는 오류 응답입니다.
|
보안
azure_auth
Azure Active Directory OAuth2 Flow.
형식:
oauth2
Flow:
implicit
권한 부여 URL:
https://login.microsoftonline.com/common/oauth2/authorize
범위
Name |
Description |
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
정책 작업의 오류 응답입니다.
Name |
형식 |
Description |
error
|
ErrorResponse
|
오류 응답
실패한 작업에 대한 오류 세부 정보를 반환하는 모든 Azure Resource Manager API에 대한 일반적인 오류 응답입니다. OData 오류 응답 형식도 따릅니다.
|
createdByType
열거형
리소스를 만든 ID의 형식입니다.
값 |
Description |
User
|
|
Application
|
|
ManagedIdentity
|
|
Key
|
|
enforcementMode
열거형
정책 할당 적용 모드입니다. 가능한 값은 Default 및 DoNotEnforce입니다.
값 |
Description |
Default
|
정책 효과는 리소스를 만들거나 업데이트하는 동안 적용됩니다.
|
DoNotEnforce
|
정책 효과는 리소스를 만들거나 업데이트하는 동안 적용되지 않습니다.
|
ErrorAdditionalInfo
Object
리소스 관리 오류 추가 정보입니다.
Name |
형식 |
Description |
info
|
object
|
추가 정보입니다.
|
type
|
string
|
추가 정보 유형입니다.
|
ErrorResponse
Object
오류 응답
Name |
형식 |
Description |
additionalInfo
|
ErrorAdditionalInfo[]
|
오류 추가 정보입니다.
|
code
|
string
|
오류 코드입니다.
|
details
|
ErrorResponse[]
|
오류 세부 정보입니다.
|
message
|
string
|
오류 메시지입니다.
|
target
|
string
|
오류 대상입니다.
|
Identity
Object
리소스의 ID입니다. 정책 할당은 최대 하나의 ID를 지원합니다. 시스템 할당 ID 또는 단일 사용자 할당 ID입니다.
Name |
형식 |
Description |
principalId
|
string
|
리소스 ID의 보안 주체 ID입니다. 이 속성은 시스템 할당 ID에 대해서만 제공됩니다.
|
tenantId
|
string
|
리소스 ID의 테넌트 ID입니다. 이 속성은 시스템 할당 ID에 대해서만 제공됩니다.
|
type
|
ResourceIdentityType
|
ID 형식입니다. 이 필드는 리소스에 시스템 또는 사용자 할당 ID를 추가할 때 유일한 필수 필드입니다.
|
userAssignedIdentities
|
UserAssignedIdentities
|
정책과 연결된 사용자 ID입니다. 사용자 ID 사전 키 참조는 '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}' 형식의 ARM 리소스 ID입니다.
|
NonComplianceMessage
Object
리소스가 정책을 준수하지 않는 이유를 설명하는 메시지입니다. 이는 '거부' 오류 메시지와 리소스의 비준수 준수 결과에 표시됩니다.
Name |
형식 |
Description |
message
|
string
|
리소스가 정책을 준수하지 않는 이유를 설명하는 메시지입니다. 이는 '거부' 오류 메시지와 리소스의 비준수 준수 결과에 표시됩니다.
|
policyDefinitionReferenceId
|
string
|
메시지가 의도된 정책 집합 정의 내의 정책 정의 참조 ID입니다. 정책 할당이 정책 집합 정의를 할당하는 경우에만 적용됩니다. 이 메시지가 제공되지 않으면 이 정책 할당에 의해 할당된 모든 정책에 메시지가 적용됩니다.
|
Override
Object
정책 속성 값이 재정의됩니다.
Name |
형식 |
Description |
kind
|
OverrideKind
|
재정의 종류입니다.
|
selectors
|
Selector[]
|
선택기 식의 목록입니다.
|
value
|
string
|
정책 속성을 재정의할 값입니다.
|
OverrideKind
열거형
재정의 종류입니다.
값 |
Description |
policyEffect
|
정책 효과 유형을 재정의합니다.
|
ParameterValuesValue
Object
매개 변수의 값입니다.
Name |
형식 |
Description |
value
|
object
|
매개 변수의 값입니다.
|
PolicyAssignment
Object
정책 할당입니다.
Name |
형식 |
Default value |
Description |
id
|
string
|
|
정책 할당의 ID입니다.
|
identity
|
Identity
|
|
정책 할당과 연결된 관리 ID입니다.
|
___location
|
string
|
|
정책 할당의 위치입니다. 관리 ID를 활용하는 경우에만 필요합니다.
|
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
열거형
ID 형식입니다. 이 필드는 리소스에 시스템 또는 사용자 할당 ID를 추가할 때 유일한 필수 필드입니다.
값 |
Description |
SystemAssigned
|
시스템 할당 ID가 리소스와 연결되어 있음을 나타냅니다.
|
UserAssigned
|
시스템 할당 ID가 리소스와 연결되어 있음을 나타냅니다.
|
None
|
리소스와 연결된 ID가 없거나 기존 ID를 제거해야 했음을 나타냅니다.
|
ResourceSelector
Object
리소스 속성을 사용하여 정책을 필터링할 리소스 선택기입니다.
Name |
형식 |
Description |
name
|
string
|
리소스 선택기의 이름입니다.
|
selectors
|
Selector[]
|
선택기 식의 목록입니다.
|
Selector
Object
선택기 식입니다.
Name |
형식 |
Description |
in
|
string[]
|
필터링할 값 목록입니다.
|
kind
|
SelectorKind
|
선택기 종류입니다.
|
notIn
|
string[]
|
필터링할 값 목록입니다.
|
SelectorKind
열거형
선택기 종류입니다.
값 |
Description |
resourceLocation
|
리소스 위치별로 정책을 필터링할 선택기 종류입니다.
|
resourceType
|
리소스 종류별로 정책을 필터링할 선택기 종류입니다.
|
resourceWithoutLocation
|
위치가 없는 리소스별로 정책을 필터링할 선택기 종류입니다.
|
policyDefinitionReferenceId
|
정책 정의 참조 ID를 기준으로 정책을 필터링할 선택기 종류입니다.
|
systemData
Object
리소스의 생성 및 마지막 수정과 관련된 메타데이터입니다.
Name |
형식 |
Description |
createdAt
|
string
(date-time)
|
리소스 만들기의 타임스탬프(UTC)입니다.
|
createdBy
|
string
|
리소스를 만든 ID입니다.
|
createdByType
|
createdByType
|
리소스를 만든 ID의 형식입니다.
|
lastModifiedAt
|
string
(date-time)
|
리소스 마지막 수정의 타임스탬프(UTC)
|
lastModifiedBy
|
string
|
리소스를 마지막으로 수정한 ID입니다.
|
lastModifiedByType
|
createdByType
|
리소스를 마지막으로 수정한 ID의 형식입니다.
|
UserAssignedIdentities
Object
정책과 연결된 사용자 ID입니다. 사용자 ID 사전 키 참조는 '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}' 형식의 ARM 리소스 ID입니다.