Работа с New Relic (newrelic infra) и 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 infra) и Terraform в Unix/Linux

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

$ mkdir examples modules

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

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

$  mkdir modules/newrelic_infra

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

$ cd modules/newrelic_infra

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

$ vim newrelic_infra_alert_condition.tf

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

#---------------------------------------------------
# Add newrelic infra alert condition
#---------------------------------------------------
resource "newrelic_infra_alert_condition" "infra_alert_condition" {
    count                   = "${var.infra_alert_condition && !var.infra_alert_condition_with_warning ? 1 : 0}"
            
    policy_id               = "${var.infra_alert_condition_policy_id}"
    name                    = "${var.infra_alert_condition_name !="" ? "${lower(var.infra_alert_condition_name)}" : "${var.name}-infra-alert-condition-${lower(var.environment)}" }"
    type                    = "${var.infra_alert_condition_type}"
    event                   = "${var.infra_alert_condition_event}"
    select                  = "${var.infra_alert_condition_select}"
    comparison              = "${var.infra_alert_condition_comparison}"

    enabled                 = "${var.infra_alert_condition_enabled}"
    where                   = "${var.infra_alert_condition_where}"
    process_where           = "${var.infra_alert_condition_process_where}"
    integration_provider    = "${var.infra_alert_condition_integration_provider}"
    
    critical {
        duration      = "${var.infra_alert_condition_critical_duration}"
        value         = "${var.infra_alert_condition_critical_value}"
        time_function = "${var.infra_alert_condition_critical_time_function}"
    }
    
    lifecycle = {
        create_before_destroy   = true,
        ignore_changes          = []
    }

    depends_on  = []
}

#---------------------------------------------------
# Add newrelic infra alert condition with warning
#---------------------------------------------------
resource "newrelic_infra_alert_condition" "infra_alert_condition_with_warning" {
    count                   = "${var.infra_alert_condition && var.infra_alert_condition_with_warning ? 1 : 0}"

    policy_id               = "${var.infra_alert_condition_policy_id}"
    name                    = "${var.infra_alert_condition_name !="" ? "${lower(var.infra_alert_condition_name)}" : "${var.name}-infra-alert-condition-${lower(var.environment)}" }"
    type                    = "${var.infra_alert_condition_type}"
    event                   = "${var.infra_alert_condition_event}"
    select                  = "${var.infra_alert_condition_select}"
    comparison              = "${var.infra_alert_condition_comparison}"

    enabled                 = "${var.infra_alert_condition_enabled}"
    where                   = "${var.infra_alert_condition_where}"
    process_where           = "${var.infra_alert_condition_process_where}"
    integration_provider    = "${var.infra_alert_condition_integration_provider}"

    critical {
        duration      = "${var.infra_alert_condition_critical_duration}"
        value         = "${var.infra_alert_condition_critical_value}"
        time_function = "${var.infra_alert_condition_critical_time_function}"
    }

    warning {
        duration      = "${var.infra_alert_condition_warning_duration}"
        value         = "${var.infra_alert_condition_warning_value}"
        time_function = "${var.infra_alert_condition_warning_time_function}"
    }

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

    depends_on  = []
}

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

$ vim variables.tf

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

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

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

#-----------------------------------------------------------
# newrelic_infra_alert_condition
#-----------------------------------------------------------
variable "infra_alert_condition" {
    description = "Enable newrelic_infra_alert_condition"
    default     = "false"
}

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

variable "infra_alert_condition_name" {
    description = "(Required) The Infrastructure alert condition's name."
    default     = ""
}

variable "infra_alert_condition_type" {
    description = "(Required) The type of Infrastructure alert condition: 'infra_process_running', 'infra_metric', or 'infra_host_not_reporting'."
    default     = "infra_metric"
}

variable "infra_alert_condition_event" {
    description = "(Required) The metric event; for example, system metrics, process metrics, storage metrics, or network metrics."
    default     = ""
}

variable "infra_alert_condition_select" {
    description = "(Required) The attribute name to identify the type of metric condition; for example, 'network', 'process', 'system', or 'storage'."
    default     = "system"
}

variable "infra_alert_condition_comparison" {
    description = "(Required) The operator used to evaluate the threshold value; 'above', 'below', 'equal'."
    default     = "equal"
}

variable "infra_alert_condition_enabled" {
    description = "(Optional) Set whether to enable the alert condition. Defaults to true."
    default     = "true"
}

variable "infra_alert_condition_where" {
    description = "(Optional) Infrastructure host filter for the alert condition."
    default     = ""
}

variable "infra_alert_condition_process_where" {
    description = "(Optional) Any filters applied to processes; for example: commandName = 'java'."
    default     = ""
}

variable "infra_alert_condition_integration_provider" {
    description = "(Optional) For alerts on integrations, use this instead of event."
    default     = ""
}


variable "infra_alert_condition_critical_duration" {
    description = "(Required) Identifies the number of minutes the threshold must be passed or met for the alert to trigger. Threshold durations must be between 1 and 60 minutes (inclusive)."
    default     = 1
}

variable "infra_alert_condition_critical_value" {
    description = "(Optional) Threshold value, computed against the comparison operator. Supported by 'infra_metric' and 'infra_process_running' alert condition types."
    default     = 1
}

variable "infra_alert_condition_critical_time_function" {
    description = "(Optional) Indicates if the condition needs to be sustained or to just break the threshold once; all or any. Supported by the 'infra_metric' alert condition type."
    default     = "all"
}

#-----------------------------------------------------------
# newrelic_infra_alert_condition with warning
#-----------------------------------------------------------
variable "infra_alert_condition_with_warning" {
    description = "Enable newrelic_infra_alert_condition with warning usage"
    default     = "false"
}

variable "infra_alert_condition_warning_duration" {
    description = "(Required) Identifies the number of minutes the threshold must be passed or met for the alert to trigger. Threshold durations must be between 1 and 60 minutes (inclusive)."
    default     = 1
}

variable "infra_alert_condition_warning_value" {
    description = "(Optional) Threshold value, computed against the comparison operator. Supported by 'infra_metric' and 'infra_process_running' alert condition types."
    default     = 1
}

variable "infra_alert_condition_warning_time_function" {
    description = "(Optional) Indicates if the condition needs to be sustained or to just break the threshold once; all or any. Supported by the 'infra_metric' alert condition type."
    default     = "all"
}

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

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

$ vim outputs.tf

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

#-----------------------------------------------------------
# newrelic_infra_alert_condition
#-----------------------------------------------------------
output "infra_alert_condition_id" {
    description = "ID for newrelic_nrql_alert_condition"
    value       = "${newrelic_infra_alert_condition.infra_alert_condition.*.id}"
}

output "infra_alert_condition__with_warning_id" {
    description = "ID for newrelic_nrql_alert_condition"
    value       = "${newrelic_infra_alert_condition.infra_alert_condition_with_warning.*.id}"
}

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

$ mkdir newrelic_infra && 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_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_condition                                     = "true"
    alert_condition_policy_id                           = "${element(module.newrelic_alert.alert_policy_id, 0)}"
    #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"
}

module "newrelic_infra" {
    source                                              = "../../modules/newrelic_infra"

    infra_alert_condition                               = "true"
    infra_alert_condition_policy_id                     = "${element(module.newrelic_alert.alert_policy_id, 0)}"
    infra_alert_condition_type                          = "infra_metric"
    infra_alert_condition_event                         = "StorageSample"
    infra_alert_condition_select                        = "diskUsedPercent"
    infra_alert_condition_comparison                    = "equal"
    infra_alert_condition_where                         = "(`hostname` LIKE '%frontend%')"
    infra_alert_condition_integration_provider          = ""
    
    #
    infra_alert_condition_with_warning                  = "true"    
}                                                       

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

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

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

$ 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

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

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

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

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

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

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

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