Terraform alert policy

Hey guys,

Is there a way I can make alert_policy idempotent. Currently, my config recreates the policy on every plan >> apply. I was trying to retrieve policy_id and check if length > 0 which ensures the policy already exists.

terraform - 0.12.6
terragrunt - 0.23.32
terraform-newrelic-provider - 2.7.4

# Data source
data "newrelic_alert_policy" "name" {
  name = "${var.service}-${var.env}"
}


resource "newrelic_alert_policy" "policy_name" {
  name = length(data.newrelic_alert_policy.name.id) > 0 ? "${var.service}-${var.env}" : null
  incident_preference = var.incident_preference
}

Or

# Data source
data "newrelic_application" "app" {
  name = var.service
}

resource newrelic_alert_policy web_service {
  name = "${var.service}-${var.env}"
  incident_preference = var.incident_preference
}

Cheers

Hi @deshdeep,

Thanks for asking! In this case, you shouldn’t need to use a data source and a resource. Since Terraform handles state management, you should only need to use the newrelic_alert_policy resource. However, if this is an alert policy that already exists (meaning it was created outside of Terraform), you’ll want to import the resource to “inform” Terraform about it before trying to run terraform apply.

Importing a resource will tell Terraform to store it in your Terraform state (locally this would be a terraform.tfstate file that gets generated by Terraform). Once Terraform “knows” about your alert policy, you can try running terraform apply again and it should automatically detect that it already exists in your New Relic account and won’t create a new one.

If this doesn’t work, we’ll probably need to see more of your Terraform configuration (sensitive data redacted) to debug further. :slight_smile:

2 Likes

Thank you @sblue for your response.

We are using terragrunt wrapper on top of our base module & it fails when I try to import the resource. Before importing this resource, please create its configuration in the root module. For example:
Also, the state list doesn’t give me the absolute name of the policy, as we are creating the policy as below.

resource “newrelic_alert_policy” “policy_name” {
name = “${var.service}-${var.env}”
incident_preference = var.incident_preference
}

Is there anything obvious which I am missing?

If you’re needing to populate variables with values, you can include additional import command options as part of the import command. So you might need to import with something similar to the example below, but with your information replacing the placeholders I made.

terraform import newrelic_alert_policy.foo "<policy_id>:<account_id>" -var 'service=your_service_name' -var 'env=your_environment_name' -var 'incident_preference=your_incident_preference'

References:

1 Like