Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Azure API Management - Global Policy Enforcement
[CmdletBinding()]
param (
$ApimName,
$ApimResourceGroup
)
function Is-ValidPolicy {
[CmdletBinding()]
param([string] $PolicyString)
if(![string]::IsNullOrEmpty($PolicyString))
{
$PolicyXml = new-object System.Xml.XmlDocument
$PolicyXml.LoadXml($PolicyString)
if($PolicyXml.SelectNodes("//inbound/base").Count -eq 0 -or $PolicyXml.SelectNodes("//outbound/base").Count -eq 0 -or $PolicyXml.SelectNodes("//on-error/base").Count -eq 0)
{
return $false
}
}
return $true
}
$ApimContext = New-AzApiManagementContext -ResourceGroupName $ApimResourceGroup -ServiceName $ApimName
$Apis = Get-AzApiManagementApi -Context $ApimContext
foreach($Api in $Apis)
{
Write-Host "Validating API '$($Api.Name)'"
$ApiPolicy = Get-AzApiManagementPolicy -Context $ApimContext -ApiId $Api.ApiId
if(!(Is-ValidPolicy -PolicyString $ApiPolicy))
{
Write-Error "Missing base element in the API policy of $($Api.Name)"
Write-Host $ApiPolicy
}
$Operations = Get-AzApiManagementOperation -Context $ApimContext -ApiId $Api.ApiId
foreach($Operation in $Operations)
{
Write-Host "Validating Operation '$($Operation.Name)'"
$OperationPolicy = Get-AzApiManagementPolicy -Context $ApimContext -ApiId $Api.ApiId -OperationId $Operation.OperationId
if(!(Is-ValidPolicy -PolicyString $OperationPolicy))
{
Write-Error "Missing base element in the '$($Operation.Name)' operation policy of $($Api.Name)"
Write-Host $OperationPolicy
}
}
}
$Products = Get-AzApiManagementProduct -Context $ApimContext
foreach($Product in $Products)
{
Write-Host "Validating Product '$($Product.Title)'"
$ProductPolicy = Get-AzApiManagementPolicy -Context $ApimContext -ProductId $Product.ProductId
if(!(Is-ValidPolicy -PolicyString $ProductPolicy))
{
Write-Error "Missing base element in the product policy of $($Product.Title)"
Write-Host $ProductPolicy
}
}
[CmdletBinding()]
param (
$PolicyString
)
Write-Host $PolicyString
$PolicyXml = new-object System.Xml.XmlDocument
$PolicyXml.LoadXml($PolicyString)
if($PolicyXml.SelectNodes("//inbound/base").Count -eq 0)
{
Write-Error "Missing base element in the inbound section"
}
if($PolicyXml.SelectNodes("//outbound/base").Count -eq 0)
{
Write-Error "Missing base element in the outbound section"
}
if($PolicyXml.SelectNodes("//on-error/base").Count -eq 0)
{
Write-Error "Missing base element in the on-error section"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment