NewRelicPS.Configuration.Policy.psm1
<# .Synopsis Idempotently applies New Relic alert policy configurations .Description Idempotently applies New Relic alert policy configurations .Example Set-NRPolicyConfiguration -APIKey $AdminAPIKey -DefinedPolicies $Config.AlertPolicies Uses New Relic APIs to update alert policies to match the policies defined in $Config.AlertPolicies. Any existing policies that are not defined will be removed. .Parameter APIKey Must be an admin user's API Key, not an account-level REST API Key. See more here: https://docs.newrelic.com/docs/apis/get-started/intro-apis/types-new-relic-api-keys .Parameter DefinedPolicies An array of policy objects which define the desired configuration state for New Relic alert policies and conditions #> Function Set-NRPolicyConfiguration { [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSShouldProcess", '', Justification = "All CMDLets being called have ShouldProcess in place and the preference is passed to them." )] [CMDLetBinding(SupportsShouldProcess = $true)] Param ( [Parameter (Mandatory = $true)] [string] $APIKey, [Parameter (Mandatory = $false)] [array] $DefinedPolicies ) [System.Collections.ArrayList]$existingPolicies = Get-NRAlertPolicy -APIKey $APIKey Write-Verbose "There are currently $($DefinedPolicies.count) defined policies and $($existingPolicies.count) existing policies." Foreach ($policy in $DefinedPolicies) { $CurrentConfig = $existingPolicies | Where-Object { $_.name -eq $policy.name } If ($CurrentConfig) { # Update policy if it already exists but needs a configuration update If ($CurrentConfig.incident_preference -ne $policy.incident_preference) { Write-Verbose "Updating policy ($policy.name)" $policyId = ($existingPolicies | Where-Object { $_.name -eq $policy.name }).id Update-NRAlertPolicy -APIKey $APIKey -PolicyId $policyId -Name $policy.name -IncidentPreference $policy.incident_preference -Whatif:$WhatIfPreference | Out-Null } # Any extra existing policies that are not defined will be removed later $existingPolicies.Remove($CurrentConfig) } Else { # Create the policy if it doesn't exist Write-Verbose "Creating policy $($policy.name)" New-NRAlertPolicy -APIKey $APIKey -Name $policy.name -IncidentPreference $policy.incident_preference -Whatif:$WhatIfPreference | Out-Null } } # Remove any existing policies that are not defined in the configuration If ($existingPolicies) { Write-Verbose "Removing policy $($policy.name -join (','))" $existingPolicies.Id | Remove-NRAlertPolicy -APIKey $APIKey -Whatif:$WhatIfPreference | Out-Null } } |