Работа с New Relic (newrelic alert) и Terraform в Unix/Linux

New Relic — это веб-приложение, нацеленное в первую очередь на разработчиков. Его основная цель — отслеживание путей взаимодействия пользователя с разработанными продуктами. Это средство аналитики ПО.

Ключевые особенности New Relic:

  • Мониторинг доступности.
  • Предупреждения и уведомления.
  • Профили производительности.
  • Плагины.
  • Гистограммы и процентили.
  • Доступ API.
  • Время отклика в режиме реального времени.
  • Анализатор производительности виртуальной машины Java.
  • Обнаружение ошибок, анализ.
  • Вызов базы данных с временем отклика и пропускной способностью.
  • Диагностика, трассировка транзакций, трассировка стека.
  • Анализ времени отклика, пропускной способности и разбивка по компонентам.
  • Подробности по производительности SQL.
  • Анализ пользователя в режиме реального времени при просмотре веб-страниц.
  • Кастомные дэшборды.
  • Отслеживание отдельных бизнес-операций.
  • X-Ray сессии для деловых операций.
  • Кросс-трассировка приложений для распределенных приложений.
  • Отчёты по доступности, масштабируемости, развёртыванию.

Установка terraform в Unix/Linux

Установка крайне примитивная и я описал как это можно сделать тут:

Установка terraform в Unix/Linux

Так же, в данной статье, я создал скрипт для автоматической установки данного ПО. Он был протестирован на CentOS 6/7, Debian 8 и на Mac OS X. Все работает должным образом!

Чтобы получить помощь по использованию команд, выполните:

$ terraform --help
Usage: terraform [-version] [-help] <command> [args]

The available commands for execution are listed below.
The most common, useful commands are shown first, followed by
less common or more advanced commands. If you're just getting
started with Terraform, stick with the common commands. For the
other commands, please read the help and docs before usage.

Common commands:
    apply              Builds or changes infrastructure
    console            Interactive console for Terraform interpolations
    destroy            Destroy Terraform-managed infrastructure
    env                Workspace management
    fmt                Rewrites config files to canonical format
    get                Download and install modules for the configuration
    graph              Create a visual graph of Terraform resources
    import             Import existing infrastructure into Terraform
    init               Initialize a Terraform working directory
    output             Read an output from a state file
    plan               Generate and show an execution plan
    providers          Prints a tree of the providers used in the configuration
    push               Upload this Terraform module to Atlas to run
    refresh            Update local state file against real resources
    show               Inspect Terraform state or plan
    taint              Manually mark a resource for recreation
    untaint            Manually unmark a resource as tainted
    validate           Validates the Terraform files
    version            Prints the Terraform version
    workspace          Workspace management

All other commands:
    debug              Debug output management (experimental)
    force-unlock       Manually unlock the terraform state
    state              Advanced state management

Приступим к использованию!

Работа с New Relic (newrelic alert) и Terraform в Unix/Linux —

У меня есть папка terraform, в ней у меня будут лежать провайдеры с которыми я буду работать. Т.к в этом примере я буду использовать newrelic, то создам данную папку и перейду в нее. Далее, в этой папке, стоит создать:

$ mkdir examples modules

В папке examples, я буду хранить так званые «плейбуки» для разварачивания различных служб, например — zabbix-server, grafana, web-серверы и так далее. В modules директории, я буду хранить все необходимые модули.

Начнем писать модуль, но для этой задачи, я создам папку:

$  mkdir modules/newrelic_alert

Переходим в нее:

$ cd modules/newrelic_alert

Открываем файл:

$ vim newrelic_alert_policy.tf

В данный файл, вставляем:

resource "newrelic_alert_policy" "alert_policy" {
    count   = "${var.alert_policy ? 1 : 0}"

    name    = "${var.alert_policy_name !="" ? "${lower(var.alert_policy_name)}" : "${lower(var.name)}-nr-policy-${lower(var.alert_policy_incident_preference)}-${lower(var.environment)}" }"
    incident_preference = "${var.alert_policy_incident_preference}"

    lifecycle = {
        create_before_destroy   = true,
        ignore_changes          = []
    }

    depends_on  = []
}

resource "newrelic_alert_policy" "simple_default" {
    count   = "${var.alert_policy && var.alert_policy_simple_default ? 1 : 0}"
                        
    name    = "${var.alert_policy_simple_default_name !="" ? "${lower(var.alert_policy_simple_default_name)}" : "simple-default-nr-policy-${lower(var.alert_policy_incident_preference)}-${lower(var.environment)}" }"
    lifecycle = {
        create_before_destroy   = true,
        ignore_changes          = []
    }

    depends_on  = []
}

Открываем файл:

$ vim newrelic_alert_channel.tf

В данный файл, вставляем:

#---------------------------------------------------
# Add newrelic alert channel
#---------------------------------------------------
# campfire
resource "newrelic_alert_channel" "alert_channel_campfire" {
    count   = "${var.alert_channel_campfire && var.alert_channel ? 1 : 0}"

    name    = "${var.alert_channel_campfire_name !="" ? var.alert_channel_campfire_name : "${lower(var.name)}-nr-channel-campfire-${lower(var.environment)}" }"
    type    = "campfire"
    
    configuration = {
        room        = "${var.alert_channel_campfire_configuration_room}"
        subdomain   = "${var.alert_channel_campfire_configuration_subdomain}"
        token       = "${var.alert_channel_campfire_configuration_token}"
    }

    lifecycle = {
        create_before_destroy   = true,
        ignore_changes          = []
    }

    depends_on  = []
    
}

#email
resource "newrelic_alert_channel" "alert_channel_email" {
    count   = "${var.alert_channel_email && var.alert_channel ? 1 : 0}"

    name    = "${var.alert_channel_email_name !="" ? var.alert_channel_email_name : "${lower(var.name)}-nr-channel-email-${lower(var.environment)}" }"
    type    = "email"

    configuration = {
        recipients              = "${var.alert_channel_email_configuration_recipients}"
        include_json_attachment = "${var.alert_channel_email_configuration_include_json_attachment}"
    }

    lifecycle = {
        create_before_destroy   = true,
        ignore_changes          = []
    }

    depends_on  = []

}

#opsgenie
resource "newrelic_alert_channel" "alert_channel_opsgenie" {
    count   = "${var.alert_channel_opsgenie && var.alert_channel ? 1 : 0}"

    name    = "${var.alert_channel_opsgenie_name !="" ? var.alert_channel_opsgenie_name : "${lower(var.name)}-nr-channel-opsgenie-${lower(var.environment)}" }"
    type    = "opsgenie"

    configuration = {
        api_key                 = "${var.alert_channel_opsgenie_configuration_api_key}"
        recipients              = "${var.alert_channel_opsgenie_configuration_recipients}"
        tags                    = "${var.alert_channel_opsgenie_configuration_tags}"
        teams                   = "${var.alert_channel_opsgenie_configuration_teams}"
    }

    lifecycle = {
        create_before_destroy   = true,
        ignore_changes          = []
    }

    depends_on  = []

}

#pagerduty
resource "newrelic_alert_channel" "alert_channel_pagerduty" {
    count   = "${var.alert_channel_pagerduty && var.alert_channel ? 1 : 0}"

    name    = "${var.alert_channel_pagerduty_name !="" ? var.alert_channel_pagerduty_name : "${lower(var.name)}-nr-channel-pagerduty-${lower(var.environment)}" }"
    type    = "pagerduty"

    configuration = {
        service_key = "${var.alert_channel_pagerduty_configuration_service_key}"
    }

    lifecycle = {
        create_before_destroy   = true,
        ignore_changes          = []
    }

    depends_on  = []

}

#slack
resource "newrelic_alert_channel" "alert_channel_slack" {
    count   = "${var.alert_channel_slack && var.alert_channel ? 1 : 0}"
        
    name    = "${var.alert_channel_slack_name !="" ? var.alert_channel_slack_name : "${lower(var.name)}-nr-channel-slack-${lower(var.environment)}" }"
    type    = "slack"

    configuration = {
        channel     = "${var.alert_channel_slack_configuration_channel}"
        url         = "${var.alert_channel_slack_configuration_url}"
    }

    lifecycle = {
        create_before_destroy   = true,
        ignore_changes          = ["configuration"]
    }

    depends_on  = []

}

#user
resource "newrelic_alert_channel" "alert_channel_user" {
    count   = "${var.alert_channel_user && var.alert_channel ? 1 : 0}"

    name    = "${var.alert_channel_user_name !="" ? var.alert_channel_user_name : "${lower(var.name)}-nr-channel-user-${lower(var.environment)}" }"
    type    = "user"

    configuration = {
        user_id     = "${var.alert_channel_user_configuration_user_id}"
    }

    lifecycle = {
        create_before_destroy   = true,
        ignore_changes          = []
    }

    depends_on  = []
}

#victorops
resource "newrelic_alert_channel" "alert_channel_victorops" {
    count   = "${var.alert_channel_victorops && var.alert_channel ? 1 : 0}"

    name    = "${var.alert_channel_victorops_name !="" ? var.alert_channel_victorops_name : "${lower(var.name)}-nr-channel-victorops-${lower(var.environment)}" }"
    type    = "victorops"

    configuration = {
        key         = "${var.alert_channel_victorops_configuration_key}"
        route_key   = "${var.alert_channel_victorops_configuration_route_key}"
    }

    lifecycle = {
        create_before_destroy   = true,
        ignore_changes          = []
    }

    depends_on  = []

}

#webhook
resource "newrelic_alert_channel" "alert_channel_webhook" {
    count   = "${var.alert_channel_webhook && var.alert_channel ? 1 : 0}"
       
    name    = "${var.alert_channel_webhook_name !="" ? var.alert_channel_webhook_name : "${lower(var.name)}-nr-channel-webhook-${lower(var.environment)}" }"
    type    = "webhook"

    configuration = {                           
        auth_password           = "${var.alert_channel_webhook_configuration_auth_password}"
        auth_type               = "${var.alert_channel_webhook_configuration_auth_type}"
        auth_username           = "${var.alert_channel_webhook_configuration_auth_username}"
        base_url                = "${var.alert_channel_webhook_configuration_base_url}"
        headers                 = "${var.alert_channel_webhook_configuration_headers}"
        payload_type            = "${var.alert_channel_webhook_configuration_payload_type}"
        payload                 = "${var.alert_channel_webhook_configuration_payload}"
    }

    lifecycle = {
        create_before_destroy   = true,
        ignore_changes          = []
    }

    depends_on  = []

}

Открываем файл:

$ vim newrelic_alert_condition.tf

Вставляем:

resource "newrelic_alert_condition" "alert_condition" {
    count                       = "${var.alert_condition? 1 : 0}"
                            
    name                        = "${var.alert_condition_name !="" ? "${lower(var.alert_condition_name)}" : "${lower(var.name)}-nr-alert-condition-${var.alert_condition_type}-${lower(var.environment)}" }"
    policy_id                   = "${var.alert_condition_policy_id}"
    type                        = "${var.alert_condition_type}"
    entities                    = ["${data.newrelic_application.application.id}"]
    metric                      = "${var.alert_condition_metric}"

    gc_metric                   = "${var.alert_condition_gc_metric}"
    violation_close_timer       = "${var.alert_condition_violation_close_timer}"
    runbook_url                 = "${var.alert_condition_runbook_url}"
    condition_scope             = "${var.alert_condition_condition_scope}"
    user_defined_metric         = "${var.alert_condition_user_defined_metric}"
    user_defined_value_function = "${var.alert_condition_user_defined_value_function}"

    term {
        duration      = "${var.alert_condition_term_duration}"
        operator      = "${var.alert_condition_term_operator}"
        priority      = "${var.alert_condition_term_priority}"
        threshold     = "${var.alert_condition_term_threshold}"
        time_function = "${var.alert_condition_term_time_function}"
    }

    lifecycle = {
        create_before_destroy   = true,
        # I think, newrelic provider has a bug. To fix it, I have added the next ignoring changes.
        # Note: If you're changing those values, please use `terraform destroy` and `terraform plan && terraform apply` to update all your values.
        ignore_changes          = ["gc_metric", "user_defined_value_function", "violation_close_timer"]
    }

    depends_on  = ["data.newrelic_application.application"]
    
}

data "newrelic_application" "application" {
    count   = "${length(var.alert_condition_entities) >0 ? 1 : 0}"

    name    = "${var.alert_condition_entities[count.index]}"
}

Открываем файл:

$ vim newrelic_alert_policy_channel.tf
resource "newrelic_alert_policy_channel" "alert_policy_channel" {
    count       = "${var.alert_policy_channel ? 1 : 0}"
            
    policy_id   = "${var.alert_policy_policy_id}"
    channel_id  = "${var.alert_policy_channel_id}"
}

Открываем файл:

$ vim variables.tf

И прописываем:

#-----------------------------------------------------------
# Global 
#-----------------------------------------------------------
variable "name" {
    description = "The name for newrelic_alert resources"
    default     = "test"
}   

variable "environment" {
    description = "environment"
    default     = "prod"
}

#-----------------------------------------------------------
# newrelic_alert_channel
#-----------------------------------------------------------
variable "alert_channel" {
    description = "Enable newrelic alert channel at general"
    default     = "false"
}

#-----------------------------------------------------------
# newrelic_alert_channel_campfire
#-----------------------------------------------------------
variable "alert_channel_campfire" {
    description = "Enable newrelic alert channel campfire usage"
    default     = "false"
}

variable "alert_channel_campfire_name" {
    description = "Set custom name for newrelic_alert_channel"
    default     = ""
}

variable "alert_channel_campfire_configuration_room" {
    description = "Set room"
    default     = ""
}

variable "alert_channel_campfire_configuration_subdomain" {
    description = "Set subdomain"
    default     = ""
}

variable "alert_channel_campfire_configuration_token" {
    description = "Set token"
    default     = ""
}

#-----------------------------------------------------------
# newrelic_alert_channel_email
#-----------------------------------------------------------
variable "alert_channel_email" {
    description = "Enable newrelic alert channel email usage"
    default     = "false"
}

variable "alert_channel_email_name" {
    description = "Set custom name for newrelic_alert_channel"
    default     = ""
}

variable "alert_channel_email_configuration_recipients" {
    description = "Set reemail. In this case, its - email address"
    default     = ""
}

variable "alert_channel_email_configuration_include_json_attachment" {
    description = "Set include_json_attachment"
    default     = 1
}

#-----------------------------------------------------------
# newrelic_alert_channel_opsgenie
#-----------------------------------------------------------
variable "alert_channel_opsgenie" {
    description = "Enable newrelic alert channel opsgenie"
    default     = "false"
}

variable "alert_channel_opsgenie_name" {
    description = "Set custom name for newrelic_alert_channel"
    default     = ""
}

variable "alert_channel_opsgenie_configuration_api_key" {
    description = "Set api_key"
    default     = ""
}

variable "alert_channel_opsgenie_configuration_recipients" {
    description = "Set reemail. In this case, its - email address"
    default     = ""
}

variable "alert_channel_opsgenie_configuration_tags" {
    description = "Set tags"
    type        = "list"
    default     = []
}


variable "alert_channel_opsgenie_configuration_teams" {
    description = "Set teams"
    type        = "list"
    default     = []
}

#-----------------------------------------------------------
# newrelic_alert_channel_pagerduty
#-----------------------------------------------------------
variable "alert_channel_pagerduty" {
    description = "Enable newrelic alert channel pagerduty usage"
    default     = "false"
}

variable "alert_channel_pagerduty_name" {
    description = "Set custom name for newrelic_alert_channel"
    default     = ""
}

variable "alert_channel_pagerduty_configuration_service_key" {
    description = "Set service_key"
    default     = ""
}

#-----------------------------------------------------------
# newrelic_alert_channel_slack
#-----------------------------------------------------------
variable "alert_channel_slack" {
    description = "Enable newrelic alert channel slack usage"
    default     = "false"
}

variable "alert_channel_slack_name" {
    description = "Set custom name for newrelic_alert_channel"
    default     = ""
}

variable "alert_channel_slack_configuration_channel" {
    description = "Set channel"
    default     = ""
}

variable "alert_channel_slack_configuration_url" {
    description = "Set url"
    default     = 1
}

#-----------------------------------------------------------
# newrelic_alert_channel_user
#-----------------------------------------------------------
variable "alert_channel_user" {
    description = "Enable newrelic alert channel user usage"
    default     = "false"
}

variable "alert_channel_user_name" {
    description = "Set custom name for newrelic_alert_channel"
    default     = ""
}

variable "alert_channel_user_configuration_user_id" {
    description = "Set user_id"
    default     = ""
}

#-----------------------------------------------------------
# newrelic_alert_channel_victorops
#-----------------------------------------------------------
variable "alert_channel_victorops" {
    description = "Enable newrelic alert channel victorops usage"
    default     = "false"
}

variable "alert_channel_victorops_name" {
    description = "Set custom name for newrelic_alert_channel"
    default     = ""
}

variable "alert_channel_victorops_configuration_key" {
    description = "Set key"
    default     = ""
}

variable "alert_channel_victorops_configuration_route_key" {
    description = "Set route_key"
    default     = ""
}

#-----------------------------------------------------------
# newrelic_alert_channel_webhook
#-----------------------------------------------------------
variable "alert_channel_webhook" {
    description = "Enable newrelic alert channel webhook usage"
    default     = "false"
}

variable "alert_channel_webhook_name" {
    description = "Set custom name for newrelic_alert_channel"
    default     = ""
}

variable "alert_channel_webhook_configuration_auth_password" {
    description = "Set auth_password"
    default     = ""
}

variable "alert_channel_webhook_configuration_auth_type" {
    description = "Set auth_type"
    default     = ""
}

variable "alert_channel_webhook_configuration_auth_username" {
    description = "Set auth_username"
    default     = ""
}

variable "alert_channel_webhook_configuration_base_url" {
    description = "Set base_url"
    default     = ""
}

variable "alert_channel_webhook_configuration_headers" {
    description = "Set headers"
    type        = "list" 
    default     = []
}

variable "alert_channel_webhook_configuration_payload_type" {
    description = "Set type"
    default     = ""
}

variable "alert_channel_webhook_configuration_payload" {
    type        = "list"
    default     = []
}

#-----------------------------------------------------------
# newrelic_alert_policy
#-----------------------------------------------------------

variable "alert_policy" {
    description = "Enable newrelic_alert_policy usage"
    default     = "false"
}

variable "alert_policy_name" {
    description = "Set custom name for newrelic_alert_policy"
    default     = ""
}

variable "alert_policy_incident_preference" {
    description = "(Optional) The rollup strategy for the policy. Options include: PER_POLICY, PER_CONDITION, or PER_CONDITION_AND_TARGET. The default is PER_POLICY."
    default     = "PER_POLICY"
}
 
variable "alert_policy_simple_default" {
    description = "Enable newrelic_alert_policy_simple_default"
    default     = "false"
}

variable "alert_policy_simple_default_name" {
    description = "Name"
    default     = ""
}

#-----------------------------------------------------------
# newrelic_alert_condition
#-----------------------------------------------------------

variable "alert_condition" {
    description = "Enable newrelic_alert_condition"
    default     = "false"
}

variable "alert_condition_policy_id" {
    description = "(Required) The ID of the policy where this condition should be used."
    default     = ""
}

variable "alert_condition_name" {
    description = "(Required) The title of the condition"
    default     = ""
}

variable "alert_condition_type" {
    description = "(Required) The type of condition. One of: apm_app_metric, apm_jvm_metric, apm_kt_metric, servers_metric, browser_metric, mobile_metric"
    default     = "apm_app_metric"
}

variable "alert_condition_entities" {
    description = "(Required) The instance IDS associated with this condition."
    type        = "list"
    default     = []
}

variable "alert_condition_metric" {
    description = "(Required) The metric field accepts parameters based on the `type` set."
    default     = "apdex"
}

variable "alert_condition_gc_metric" {
    description = "(Optional) A valid Garbage Collection metric e.g. GC/G1 Young Generation. This is required if you are using apm_jvm_metric with gc_cpu_time condition type."
    default     = "GC/G1 Young Generation"
}

variable "alert_condition_violation_close_timer" {
    description = "(Optional) Automatically close instance-based violations, including JVM health metric violations, after the number of hours specified. Must be: 1, 2, 4, 8, 12 or 24."
    default     = 1
}

variable "alert_condition_runbook_url" {
    description = "(Optional) Runbook URL to display in notifications."
    default     = ""
}

variable "alert_condition_condition_scope" {
    description = "(Optional) instance or application. This is required if you are using the JVM plugin in New Relic."
    default     = "application"
}

variable "alert_condition_user_defined_metric" {
    description = "(Optional) A custom metric to be evaluated."
    default     = ""
}

variable "alert_condition_user_defined_value_function" {
    description = "(Optional) One of: average, min, max, total, or sample_size."
    default     = "average"
}

variable "alert_condition_term_duration" {
    description = "(Required) In minutes, must be: 5, 10, 15, 30, 60, or 120."
    default     = 5
}

variable "alert_condition_term_operator" {
    description = "(Optional) above, below, or equal. Defaults to equal."
    default     = "equal"
}

variable "alert_condition_term_priority" {
    description = "(Optional) critical or warning. Defaults to critical."
    default     = "critical"
}

variable "alert_condition_term_threshold" {
    description = "(Required) Must be 0 or greater."
    default     = 0
}

variable "alert_condition_term_time_function" {
    description = "(Required) all or any."
    default     = "all"
}

#-----------------------------------------------------------
# newrelic_alert_policy_channel
#-----------------------------------------------------------
variable "alert_policy_channel" {
    description = "Enable newrelic_alert_policy_channel"
    default     = "false"
}

variable "alert_policy_policy_id" {
    description = "(Required) The ID of the policy."
    default     = ""
}

variable "alert_policy_channel_id" {
    description = "(Required) The ID of the channel."
    default     = ""
}

Собственно в этом файле храняться все переменные. Спасибо кэп!

Открываем последний файл:

$ vim outputs.tf

И в него вставить нужно следующие строки:

#-----------------------------------------------------------
# newrelic_alert_channel
#-----------------------------------------------------------
output "alert_channel_campfire_id" {
    description = "ID for newrelic_alert_channel_campfire"
    value       = "${newrelic_alert_channel.alert_channel_campfire.*.id}"
}

output "alert_channel_email_id" {
    description = "ID for newrelic_alert_channel_email"
    value       = "${newrelic_alert_channel.alert_channel_email.*.id}"
}

output "alert_channel_opsgenie_id" {
    description = "ID for newrelic_alert_channel_opsgenie"
    value       = "${newrelic_alert_channel.alert_channel_opsgenie.*.id}"
}

output "alert_channel_pagerduty_id" {
    description = "ID for newrelic_alert_channel_pagerduty"
    value       = "${newrelic_alert_channel.alert_channel_pagerduty.*.id}"
}

output "alert_channel_slack_id" {
    description = "ID for newrelic_alert_channel_slack"
    value       = "${newrelic_alert_channel.alert_channel_slack.*.id}"
}

output "alert_channel_user_id" {
    description = "ID for newrelic_alert_channel_user"
    value       = "${newrelic_alert_channel.alert_channel_user.*.id}"
}

output "alert_channel_victorops_id" {
    description = "ID for newrelic_alert_channel_victorops"
    value       = "${newrelic_alert_channel.alert_channel_victorops.*.id}"
}

output "alert_channel_webhook_id" {
    description = "ID for newrelic_alert_channel_webhook"
    value       = "${newrelic_alert_channel.alert_channel_webhook.*.id}"
}

#-----------------------------------------------------------
# newrelic_alert_policy
#-----------------------------------------------------------
output "alert_policy_id" {
    description = "ID of the policy."
    value       = "${newrelic_alert_policy.alert_policy.*.id}"
}

output "simple_default_alert_policy_id" {
    description = "ID of the policy for simple_default"
    value       = "${newrelic_alert_policy.simple_default.*.id}"
}

#-----------------------------------------------------------
# newrelic_alert_condition
#-----------------------------------------------------------
output "alert_condition_id" {
    description = "The ID of the alert condition."
    value       = "${newrelic_alert_condition.alert_condition.*.id}"
}

#-----------------------------------------------------------
# newrelic_alert_policy_channel
#-----------------------------------------------------------
output "alert_policy_channel_id" {
    description = "The ID of the alert policy channel"
    value       = "${newrelic_alert_policy_channel.alert_policy_channel.*.id}"
}

Переходим теперь в папку aws/examples и создадим еще одну папку для проверки написанного чуда:

$ mkdir newrelic_alert && cd $_

Внутри созданной папки открываем файл:

$ vim main.tf

И вставим в него следующий код:

#
# MAINTAINER Vitaliy Natarov "vitaliy.natarov@yahoo.com"
#
terraform {
  required_version = "~> 0.11.11"
}

provider "newrelic" {
    api_key = "75e6741e6326cce1666ecfb94c3c0b8fdf"
}

module "newrelic_alert" {
    source                                              = "../../modules/newrelic_alert"
                                                        
    # vars for newrelic_alert_policy
    alert_policy                                        = "true"
    #alert_policy_name                                  = "new-relic-policy-PER_CONDITION"
    alert_policy_incident_preference                    = "PER_CONDITION"
    alert_policy_simple_default                         = "true"
    
    alert_channel                                       = "true"
    #
    alert_channel_campfire                              = "false"
    #
    alert_channel_email                                 = "false"
    #
    alert_channel_opsgenie                              = "false"
    #
    alert_channel_pagerduty                             = "false"
    # 
    alert_channel_slack                                 = "true"
    alert_channel_slack_configuration_channel           = "new-relic"
    alert_channel_slack_configuration_url               = "https://hooks.slack.com/services/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666"
    # 
    alert_channel_user                                  = "false"
    # 
    alert_channel_victorops                             = "false"
    #
    alert_channel_webhook                               = "false"
    #
    alert_condition                                     = "true"     
    alert_condition_policy_id                           = "${element(module.newrelic_alert.simple_default_alert_policy_id, 0)}"
    alert_condition_type                                = "apm_app_metric"
    alert_condition_entities                            = ["PHP Application"]

    alert_policy_channel                                = "false"
} 

В файле стоит прописать все необходимое, но самое главное:

  • api_key — API ключ, который можно сгенерировать в «‘Account settings’->’API keys'».

Можно так же еще создать:

$ vim output.tf

И в него вставить что-то типа:

#-----------------------------------------------------------
#newrelic_alert_channel 
#-----------------------------------------------------------
output "nr_alert_channel_slack" {
    description = "ID for newrelic_alert_channel_slack"
    value       = "${module.newrelic_alert.alert_channel_slack_id}"
}

#-----------------------------------------------------------
# newrelic_alert_policy
#-----------------------------------------------------------
output "nr_alert_policy_id" {
    description = "ID of the policy."
    value       = "${module.newrelic_alert.alert_policy_id}"
}

output "nr_simple_default_alert_policy_id" {
    description = "ID of the policy for simple_default"
    value       = "${module.newrelic_alert.simple_default_alert_policy_id}"
}

Все уже написано и готово к использованию. Ну что, начнем тестирование. В папке с вашим плейбуком, выполняем:

$ terraform init

Этим действием я инициализирую проект. Затем, подтягиваю модуль:

$ terraform get

PS: Для обновление изменений в самом модуле, можно выполнять:

$ terraform get -update

Проверим валидацию:

$ terraform validate

Запускем прогон:

$ terraform plan

Мне вывело что все у меня хорошо и можно запускать деплой:

$ terraform apply

Как видно с вывода, — все прошло гладко! Чтобы удалить созданное творение, можно выполнить:

$ terraform destroy

Еще полезности:

Работа с New Relic (newrelic alert) и Terraform в Unix/Linux

Работа с New Relic (newrelic nrql) и Terraform в Unix/Linux

Работа с New Relic (newrelic infra) и Terraform в Unix/Linux

Работа с New Relic (newrelic synthetics) и Terraform в Unix/Linux

Работа с New Relic (newrelic dashboard) и Terraform в Unix/Linux

Весь материал аплоаджу в github аккаунт для удобства использования:

$ git clone https://github.com/SebastianUA/terraform.git

Вот и все на этом. Данная статья «Работа с New Relic (newrelic alert) и Terraform в Unix/Linux» завершена.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.