Problem:
When creating initiative or policy definitions in Azure Policy using PowerShell, you may receive the following error: Error reading JToken from JsonReader.
Solution:
- The New-AzPolicyDefinition cmdlet is used to create policy definitions. Use an if/else statement to ensure the “parameter” parameter is only used when it has a value:
$Test = Get-Content -Path ($PolicyPath + '\parameters.json')
if($Test)
{
New-AzPolicyDefinition `
-Name $Policy `
-DisplayName $PolicyData.DisplayName `
-Description $PolicyData.Description `
-Policy ($PolicyPath + '\rule.json') `
-Metadata ($PolicyPath + '\metadata.json') `
-Parameter ($PolicyPath + '\parameters.json') `
-Mode $PolicyData.Mode `
-Verbose `
-ErrorAction Stop | Out-Null
}
else
{
New-AzPolicyDefinition `
-Name $Policy `
-DisplayName $PolicyData.DisplayName `
-Description $PolicyData.Description `
-Policy ($PolicyPath + '\rule.json') `
-Metadata ($PolicyPath + '\metadata.json') `
-Mode $PolicyData.Mode `
-Verbose `
-ErrorAction Stop | Out-Null
}
- The New-AzPolicySetDefinition is used to create initiative definitions. Use an if/else statement to ensure the “GroupDefinition” parameter is only used when it has a value:
$Test = Get-Content -Path ($Path + '\policyDefinitionGroups.json')
if($Test)
{
New-AzPolicySetDefinition `
-Name $InitiativeData.Name `
-DisplayName $InitiativeData.DisplayName `
-Description $InitiativeData.Description `
-Metadata ($Path + '\metadata.json') `
-PolicyDefinition ($Path + '\policyDefinitions.json') `
-Parameter ($Path + '\parameters.json') `
-GroupDefinition ($Path + '\policyDefinitionGroups.json') `
-Verbose `
-ErrorAction Stop
}
else
{
New-AzPolicySetDefinition `
-Name $InitiativeData.Name `
-DisplayName $InitiativeData.DisplayName `
-Description $InitiativeData.Description `
-Metadata ($Path + '\metadata.json') `
-PolicyDefinition ($Path + '\policyDefinitions.json') `
-Parameter ($Path + '\parameters.json') `
-Verbose `
-ErrorAction Stop
}
Explanation:
You may find yourself in a situation when you need to replicate a built-in initiative or policy definition to the same Azure cloud or exported to use in another Azure cloud. When exporting out the definitions, you want to capture as much of the data as possible. However, not all policy definitions have parameters and not all initiative definitions have group definitions. Group definitions are used by Regulatory Compliance initiatives to associate control mappings with policy definitions within the initiative definition. Since only some initiative definitions contain this data, its nice to keep it if it exists but you have to be handle a null value in the code. For the parameters, it is only used when a policy definition needs a value during assignment. Some policy definitions don’t need a value during assignment so that is also why you would need an if/else statement to handle that condition.