Azure / Azure/azure-powershell

New-AzPolicyDefinition document error

Open
#18,777 14 comments 1 reaction 0 assignees View on GitHub
bug customer-reported Policy Service Attention
Dominant language
C#
Stars
4.8k
Forks
4.3k
Avg merge
2d 17h
Merged PRs (30d)
51

Description

### Description

https://docs.microsoft.com/en-us/powershell/module/az.resources/new-azpolicydefinition?view=azps-8.0.0#example-1-create-a-policy-definition-by-using-a-policy-file

In the above document, first example description, it's like:
_Three file content formats are supported:

- Policy rule only (example above).
- Policy properties object. This format is displayed in the portal when editing a policy definition and may include parameters.
- Full policy object. This format is generated by the Azure Policy export function and may include parameters._

But when I tried to use the command in https://docs.microsoft.com/en-us/azure/governance/policy/how-to/export-resources#export-with-azure-powershell to export my existing policy definition and use New-AzPolicyDefinition to recreate a new policy definition based on the exported json file, it's returning error.

**Did I misunderstand anything or should we correct this document?**

(I'm from ARM CSS team, please reach me on Teams zhangjerry)

### Issue script & Debug output

```PowerShell
PS C:\Users\zhangjerry> $mypol = Get-AzPolicyDefinition -Custom | where {$_.Properties.DisplayName -eq "testfunctionappTLS"}
$mypol | ConvertTo-Json -Depth 100 | Out-File mypol.json

PS C:\Users\zhangjerry> New-AzPolicyDefinition -Name "test" -Policy .\mypol.json -SubscriptionId 5102f0a2-xxxx-xxxx-xxxx-2834a4473453

DEBUG: 4:22:37 PM - NewAzurePolicyDefinitionCmdlet begin processing with ParameterSet 'SubscriptionIdParameterSet'.
DEBUG: 4:22:37 PM - using account id 'zhangjerry@microsoft.com'...
DEBUG: [Common.Authentication]: Authenticating using Account: 'zhangjerry@microsoft.com', environment: 'AzureCloud', tenant: '72f988bf-xxxx-xxxx-xxxx-2d7cd011db47'
DEBUG: 4:22:37 PM - [SilentAuthenticator] Calling SharedTokenCacheCredential.GetTokenAsync - TenantId:'72f988bf-xxxx-xxxx-xxxx-2d7cd011db47', Scopes:'https://management.core.windows.net//.default', AuthorityHost:'https://login.mic
rosoftonline.com/', UserId:'zhangjerry@microsoft.com'
DEBUG: SharedTokenCacheCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId:
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37 - ] Azure region was not configured or could not be discovered. Not using a regional authority.
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37] Found 1 cache accounts and 0 broker accounts
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37] Returning 1 accounts
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37 - ] MSAL MSAL.Desktop with assembly version '4.30.1.0'. CorrelationId(1f072db2-92c3-4f4b-ac53-8807fa4d2878)
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37 - ] === AcquireTokenSilent Parameters ===
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37 - ] LoginHint provided: False
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37 - ] Account provided: True
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37 - ] ForceRefresh: False
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37 - ]
=== Request Data ===
Authority Provided? - True
Scopes - https://management.core.windows.net//.default
Extra Query Params Keys (space separated) -
ApiId - AcquireTokenSilent
IsConfidentialClient - False
SendX5C - False
LoginHint ? False
IsBrokerConfigured - False
HomeAccountId - False
CorrelationId - 1f072db2-92c3-4f4b-ac53-8807fa4d2878

DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37 - ] === Token Acquisition (SilentRequest) started:

Authority Host: login.microsoftonline.com
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37 - ] Azure region was not configured or could not be discovered. Not using a regional authority.
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37 - ] Access token is not expired. Returning the found cache entry. [Current time (06/28/2022 08:22:37) - Expiration Time (06/28/2022 09:33:07 +00:
00) - Extended Expiration Time (06/28/2022 09:33:07 +00:00)]
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37 - ] Returning access token found in cache. RefreshOn exists ? False
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37 - ] Fetched access token from host login.microsoftonline.com.
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [06/28/2022 08:22:37 - ] === Token Acquisition finished successfully. An access token was returned with Expiration Time: 06/28/2022 09:33:07 +00:00 and Scopes https:/
/management.core.windows.net//user_impersonation https://management.core.windows.net//.default
DEBUG: SharedTokenCacheCredential.GetToken succeeded. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: ExpiresOn: 2022-06-28T09:33:07.0000000+00:00
DEBUG: [Common.Authentication]: Received token with LoginType 'User', Tenant: '72f988bf-xxxx-xxxx-xxxx-2d7cd011db47', UserId: 'zhangjerry@microsoft.com'
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
PUT

Absolute Uri:
https://management.azure.com/subscriptions/5102f0a2-xxxx-xxxx-xxxx-2834a4473453/providers/Microsoft.Authorization/policydefinitions/test?api-version=2021-06-01

Headers:
User-Agent : AzurePowershell/v0.0.0,Az.Resources/5.4.0,PSVersion/v5.1.22000.653,Az.Accounts/2.7.4
ParameterSetName : SubscriptionIdParameterSet
CommandName : New-AzPolicyDefinition

Body:
{
"name": "test",
"properties": {
"policyRule": {
"Name": "e30fa957-66f0-4006-9b32-de445572d0ef",
"ResourceId": "/subscriptions/5102f0a2-xxxx-xxxx-xxxx-2834a4473453/providers/Microsoft.Authorization/policyDefinitions/e30fa957-66f0-4006-9b32-de445572d0ef",
"ResourceName": "e30fa957-66f0-4006-9b32-de445572d0ef",
"ResourceType": "Microsoft.Authorization/policyDefinitions",
"SubscriptionId": "5102f0a2-xxxx-xxxx-xxxx-2834a4473453",
"Properties": {
"Description": null,
"DisplayName": "testfunctionappTLS",
"Metadata": {
"createdBy": "47f3a790-1ab1-4f5f-a190-ff1fc7928726",
"createdOn": "2022-04-06T06:14:48.8962767Z",
"updatedBy": null,
"updatedOn": null
},
"Mode": "All",
"Parameters": {
"effect": {
"type": "String",
"metadata": {
"displayName": "Effect",
"description": "Enable or disable the execution of the policy"
},
"allowedValues": [
"AuditIfNotExists",
"DeployIfNotExists",
"Disabled"
],
"defaultValue": "DeployIfNotExists"
}
},
"PolicyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.Web/sites"
},
{
"field": "kind",
"like": "functionapp*"
}
]
},
"then": {
"effect": "[parameters('effect')]",
"details": {
"type": "Microsoft.Web/sites/config",
"name": "web",
"existenceCondition": {
"field": "Microsoft.Web/sites/config/web.minTlsVersion",
"equals": "1.2"
},
"roleDefinitionIds": [
"/providers/Microsoft.Authorization/roleDefinitions/8e3af657-a8ff-443c-a75c-2fe8c4bcb635"
],
"deployment": {
"properties": {
"mode": "incremental",
"parameters": {
"sitename": {
"value": "[field('name')]"
},
"location": {
"value": "[field('location')]"
}
},
"template": {
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"sitename": {
"type": "String"
},
"location": {
"type": "String"
}
},
"resources": [
{
"type": "Microsoft.Web/sites/config",
"apiVersion": "2021-03-01",
"name": "[concat(parameters('sitename'), '/web')]",
"location": "[parameters('sitename')]",
"properties": {
"minTlsVersion": "1.2"
}
}
]
}
}
}
}
}
},
"PolicyType": 1
},
"PolicyDefinitionId": "/subscriptions/5102f0a2-xxxx-xxxx-xxxx-2834a4473453/providers/Microsoft.Authorization/policyDefinitions/e30fa957-66f0-4006-9b32-de445572d0ef"
},
"mode": "All",
"policyType": "Custom"
}
}

DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
BadRequest

Headers:
Pragma : no-cache
x-ms-ratelimit-remaining-subscription-writes: 1199
x-ms-request-id : debdfda6-a82c-4c7b-8fc9-ed2b57308c75
x-ms-correlation-request-id : debdfda6-a82c-4c7b-8fc9-ed2b57308c75
x-ms-routing-request-id : SOUTHEASTASIA:20220628T082238Z:debdfda6-a82c-4c7b-8fc9-ed2b57308c75
Strict-Transport-Security : max-age=31536000; includeSubDomains
X-Content-Type-Options : nosniff
Cache-Control : no-store, no-cache
Date : Tue, 28 Jun 2022 08:22:37 GMT
Server : Kestrel

Body:
{
"error": {
"code": "InvalidPolicyRule",
"message": "Failed to parse policy rule: 'Could not find member 'Name' on object of type 'PolicyRuleDefinition'. Path 'Name'.'."
}
}

New-AzPolicyDefinition : InvalidPolicyRule : Failed to parse policy rule: 'Could not find member 'Name' on object of type 'PolicyRuleDefinition'. Path 'Name'.'.
CorrelationId: debdfda6-a82c-4c7b-8fc9-ed2b57308c75
At line:1 char:1
+ New-AzPolicyDefinition -Name "test" -Policy .\mypol.json -Subscriptio ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzPolicyDefinition], ErrorResponseMessageException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzurePolicyDefinitionCmdlet

DEBUG: AzureQoSEvent: Module: Az.Resources:5.4.0; CommandName: New-AzPolicyDefinition; PSVersion: 5.1.22000.653; IsSuccess: False; Duration: 00:00:00.5760346; Exception: InvalidPolicyRule : Failed to parse policy rule: 'Could not
find member 'Name' on object of type 'PolicyRuleDefinition'. Path 'Name'.'.
CorrelationId: debdfda6-a82c-4c7b-8fc9-ed2b57308c75;
DEBUG: Finish sending metric.
DEBUG: 4:22:38 PM - NewAzurePolicyDefinitionCmdlet end processing.
```

### Environment data

```PowerShell
PS C:\Users\zhangjerry> $PSVersionTable

Name Value
---- -----
PSVersion 5.1.22000.653
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.22000.653
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
```

### Module versions

```PowerShell
PS C:\Users\zhangjerry> Get-Module Az*

ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 2.7.4 Az.Accounts {Add-AzEnvironment, Clear-AzContext, Clear-AzDefault, Connect-AzAccount...}
Script 5.4.0 Az.Resources {Export-AzResourceGroup, Export-AzTemplateSpec, Get-AzDenyAssignment, Get-AzDeployment...}
```

### Error output

```PowerShell
PS C:\Users\zhangjerry> Resolve-AzError
DEBUG: 4:25:32 PM - ResolveError begin processing with ParameterSet 'AnyErrorParameterSet'.
DEBUG: 4:25:32 PM - using account id 'zhangjerry@microsoft.com'...
WARNING: Upcoming breaking changes in the cmdlet 'Resolve-AzError' :
The `Resolve-Error` alias will be removed in a future release. Please change any scripts that use this alias to use `Resolve-AzError` instead.
Note : Go to https://aka.ms/azps-changewarnings for steps to suppress this breaking change warning, and other information on breaking changes in Azure PowerShell.

HistoryId: 10

Message : InvalidPolicyRule : Failed to parse policy rule: 'Could not find member 'Name' on object of type 'PolicyRuleDefinition'. Path 'Name'.'.
CorrelationId: debdfda6-a82c-4c7b-8fc9-ed2b57308c75
StackTrace : at Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.ResourceManagerCmdletBase.HandleException(ExceptionDispatchInfo capturedException)
at Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.ResourceManagerCmdletBase.ExecuteCmdlet()
at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
Exception : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.ErrorResponses.ErrorResponseMessageException
InvocationInfo : {New-AzPolicyDefinition}
Line : New-AzPolicyDefinition -Name "test" -Policy .\mypol.json -SubscriptionId 5102f0a2-xxxx-xxxx-xxxx-2834a4473453
Position : At line:1 char:1
+ New-AzPolicyDefinition -Name "test" -Policy .\mypol.json -Subscriptio ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistoryId : 10

The Azure PowerShell team is listening, please let us know how we are doing: https://aka.ms/azpssurvey?Q_CHL=ERROR.

DEBUG: AzureQoSEvent: Module: Az.Accounts:2.7.4; CommandName: Resolve-AzError; PSVersion: 5.1.22000.653; IsSuccess: True; Duration: 00:00:00.1308976
DEBUG: Finish sending metric.
DEBUG: 4:25:33 PM - ResolveError end processing.
```

Contributor guide

Open the contributing guide

Research direction

Start by comparing the New-AzPolicyDefinition documentation with the Azure PowerShell export documentation and the reported JSON payload. Reproduce the InvalidPolicyRule error using the shown command, then verify which exported policy format is supported. Done means the documentation accurately describes the accepted input and explains the correct usage or limitation.

Written by the indexing model from the issue text.

Assessment

Tech stack
azure, powershell
Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.