• /
  • EnglishEspañolFrançais日本語한국어Português
  • ログイン今すぐ開始

New RelicとTerraformをはじめる

Terraformは、HashiCorpが開発した人気の高いInfrastructure as Code(IaC)ソフトウェアツールです。New Relic やアラートなど、あらゆる種類のインフラストラクチャとサービスをプロビジョニングするために使用できます。このガイドでは、Terraformを使用してNew Relic をセットアップする方法を説明します。他のNew Relicリソースをセットアップする方法については、New Relic Terraformプロバイダーに関するドキュメントを参照してください。

ヒント

New RelicのCodeStream IDE拡張機能を使うと、TerraformのドキュメントをIDEに直接取り込んでワークフローを簡素化できます。ワンクリックだけで、あらゆるNew Relicリソースタイプ向けのテンプレートを追加できます。

VS CodeVisual Studio、または任意のJetBrains IDE向けのCodeStreamをインストールし、CodeStreamペインの上部にあるレンチアイコンを探してください。

まず、アラートポリシー、4つのアラート条件、通知チャネルを設定します。4つのアラート条件は、Googleのサイト信頼性エンジニアリングブックで紹介されている監視の4つのゴールデンシグナルに基づいています。

  • Latency: アプリケーションがリクエストを処理するのにかかる時間。
  • Traffic: システムが受信するリクエストの数。
  • Errors: 失敗したリクエストの割合。
  • Saturation: アプリケーションの要求を満たすために、リソースにかかる負荷。

開始する前に

このガイドを利用するには、New RelicとTerraformの両方に関する基本的な知識が必要です。New Relicオープンソースエージェントをまだ導入していない場合は、アプリケーションにNew Relicをインストールしてください。さらに、Terraform CLIをインストールしてください

TerraformとNew Relicプロバイダーのセットアップ

まず、作業ディレクトリを初期化し、Terraform設定ファイルを作成します。

bash
$
mkdir terraform-project && cd terraform-project
$
touch main.tf

次に、main.tfterraformおよびrequired_providersブロックを設定して、TerraformにNew Relicプロバイダーをインストールして使用するよう指示します。

terraform {
# Require Terraform version 1.0 (recommended)
required_version = "~> 1.0"
# Require the latest 2.x version of the New Relic provider
required_providers {
newrelic = {
source = "newrelic/newrelic"
}
}
}

このコードブロックでは、必要なTerraformのバージョンを1.0に設定し、New Relicプロバイダーを最新の2.xバージョンに設定しています。セットアップに応じたバージョン制約を使用することで、Terraformの実行における安定性が向上します。

TerraformとNew Relicプロバイダーのバージョンを設定したら、次にNew Relicプロバイダーを設定する必要があります。

New Relicプロバイダーを設定する

terraform設定が完了したら、New Relic providerの以下の項目を設定します。

  1. New RelicアカウントID

  2. New Relic 。ほとんどのユーザーキーは、NRAK-で始まります。

  3. New Relicリージョン。New Relic URLがone.newrelic.comの場合、リージョンはUSです。URLがone.eu.newrelic.comの場合、リージョンはEUです。

    main.tfでは、プロバイダーにこれらの値を設定します。

    provider "newrelic" {
    account_id = 12345 # Your New Relic account ID
    api_key = "NRAK-***" # Your New Relic user key
    region = "US" # US or EU (defaults to US)
    }

    New Relicプロバイダーにこれらの値を設定することで、New Relic APIを介してアカウント名義で変更を実行するようプロバイダーを設定できます。

    ヒント

    環境変数を使用してNew Relicプロバイダーを設定することもできます。これは、プロバイダー設定のデフォルト値を設定するのに便利な方法です。

    New Relicプロバイダーの設定については、公式プロバイダードキュメントをご覧ください。

    New Relicプロバイダーの設定が完了したら、Terraformを初期化します。

    bash
    $
    terraform init

    TerraformがNew Relicプロバイダーのインストールと登録を完了すると、成功メッセージと実行可能な次のステップ(terraform planの実行など)が表示されます。ただし、terraform planを実行する前に、リソースを作成する必要があります。

ゴールデンシグナルアラートを使用してNew Relicアラートポリシーを作成する

New Relicプロバイダーの設定と初期化が完了したら、アプリケーションのアラート戦略を定義できます。

特定のアプリケーションをターゲットにしているため、newrelic_entityを使用してNew Relicからアプリケーション情報を取得し、設定内の他の場所でそのデータを参照できるようにします。

data "newrelic_entity" "example_app" {
name = "Your App Name" # Must be an exact match to your application name in New Relic
domain = "APM" # or BROWSER, INFRA, MOBILE, SYNTH, depending on your entity's domain
type = "APPLICATION"
}

次に、newrelic_alert_policyを作成します。ポリシー名はアプリケーション名に基づいて動的に設定します。そうすることで、ポリシーの適用範囲が把握しやすくなります。

resource "newrelic_alert_policy" "golden_signal_policy" {
name = "Golden Signals - ${data.newrelic_entity.example_app.name}"
}

この時点で、ドライランで設定をテストできるはずです。

bash
$
terraform plan

Terraformの実行計画が出力されているはずです。実行計画には、terraform applyの実行時にTerraformが実行するアクションが含まれています。

bash
# Example output
------------------------------------------------------------------------
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# newrelic_alert_policy.golden_signal_policy will be created
+ resource "newrelic_alert_policy" "golden_signal_policy" {
+ account_id = (known after apply)
+ id = (known after apply)
+ incident_preference = "PER_POLICY"
+ name = "Golden Signals - Your App Name"
}
Plan: 1 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------

このケースでは、実行計画には、terraform applyを実行するとTerraformが新しいアラートポリシーを作成することが示されています。詳細を確認したら、実行計画を実行して、New Relicアカウントにアラートポリシーリソースをプロビジョニングします。

bash
$
terraform apply

applyを変更するたびに、Terraformは指示したアクションの実行確認を求めます。「yes」と入力します。

実行中、Terraformはコンソールにログを送信します。

bash
# Example output of `terraform apply`
newrelic_alert_policy.golden_signal_policy: Creating...
newrelic_alert_policy.golden_signal_policy: Creation complete after 1s [id=111222333]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

New RelicにログインしAlert Policiesに移動して、Terraformが新しいポリシーを作成したことを確認します。

アラート条件作成の次のステップに進む際には、各リソースの設定後にterraform applyを実行できます。新しいリソースを表示するには、アラートポリシーのウェブページを再読み込みしてください。

4つのゴールデンシグナルに基づいたアラート条件をプロビジョニングする

次に、レイテンシ、トラフィック、エラー、飽和度の4つのゴールデンシグナルに基づいてアプリケーションにアラート条件を追加します。前の手順で作成したアラートポリシーに、これらのアラート条件を適用します。

Latency

ほとんどの人は、レスポンスタイムの遅延を避けたいと考えています。アプリケーションの全体的なレスポンスタイムが5分間に5秒を超えた場合にトリガーされるnewrelic_alert_conditionを作成できます。

# Response time
resource "newrelic_alert_condition" "response_time_web" {
policy_id = newrelic_alert_policy.golden_signal_policy.id
name = "High Response Time (Web) - ${data.newrelic_entity.example_app.name}"
type = "apm_app_metric"
entities = [data.newrelic_entity.example_app.application_id]
metric = "response_time_web"
runbook_url = "https://www.example.com"
condition_scope = "application"
term {
duration = 5
operator = "above"
priority = "critical"
threshold = "5"
time_function = "all"
}
}

このアラート条件がpolicy_idを使用して以前に設定したアラートポリシーにリンクされていることに注意してください。

newrelic_alert_conditionは非推奨となり、今後はNRQLアラートの使用が推奨されます。次の設定を使用して、上記と同じ機能のNRQLアラートを作成できます。

# Response time - Create Alert Condition
resource "newrelic_nrql_alert_condition" "response_time_alert" {
policy_id = newrelic_alert_policy.golden_signal_policy.id
type = "static"
name = "Response Time - ${data.newrelic_entity.example_app.name}"
description = "High Transaction Response Time"
runbook_url = "https://www.example.com"
enabled = true
violation_time_limit_seconds = 3600
nrql {
query = "SELECT filter(average(newrelic.timeslice.value), WHERE metricTimesliceName = 'HttpDispatcher') OR 0 FROM Metric WHERE appId IN (${data.newrelic_entity.example_app.application_id}) AND metricTimesliceName IN ('HttpDispatcher', 'Agent/MetricsReported/count')"
}
critical {
operator = "above"
threshold = 5
threshold_duration = 300
threshold_occurrences = "ALL"
}
}

Traffic

トラフィックとは、ある瞬間にシステムにかかっている負荷の程度を示す指標です。スループットとは、アプリケーションに送信されるトラフィックの量を測定するメトリクスです。アプリケーションの全体的な応答率が5分間で1分あたり5リクエストを下回った場合にトリガーされるnewrelic_alert_conditionを作成します。

# Low throughput
resource "newrelic_alert_condition" "throughput_web" {
policy_id = newrelic_alert_policy.golden_signal_policy.id
name = "Low Throughput (Web)"
type = "apm_app_metric"
entities = [data.newrelic_entity.example_app.application_id]
metric = "throughput_web"
condition_scope = "application"
# Define a critical alert threshold that will
# trigger after 5 minutes below 5 requests per minute.
term {
priority = "critical"
duration = 5
operator = "below"
threshold = "5"
time_function = "all"
}
}

このタイプのアラートは、トラフィックのベースラインが1日を通して一定であることが予想される場合に便利です。トラフィックの減少は問題の発生を示している可能性があります。

Errors

アプリケーションのエラー率が急上昇した場合に、それを把握できるようにする必要があります。アプリケーションのエラー率が5分間で5%を超えた場合にトリガーされるnewrelic_alert_conditionを作成します。

# Error percentage
resource "newrelic_alert_condition" "error_percentage" {
policy_id = newrelic_alert_policy.golden_signal_policy.id
name = "High Error Percentage"
type = "apm_app_metric"
entities = [data.newrelic_entity.example_app.application_id]
metric = "error_percentage"
runbook_url = "https://www.example.com"
condition_scope = "application"
# Define a critical alert threshold that will trigger after 5 minutes above a 5% error rate.
term {
duration = 5
operator = "above"
threshold = "5"
time_function = "all"
}
}

Saturation

飽和度とは、サービスがどれだけ「満杯」になっているかを示す指標であり、CPU時間、メモリ割り当て、キューの深さなど、さまざまな形で表されます。この例では、アプリケーションを提供するホストにすでにNew Relic Infrastructureエージェントがインストールされており、CPU 使用率が特定の閾値を超えて急増したときの回数を設定するとします。

# High CPU usage
resource "newrelic_infra_alert_condition" "high_cpu" {
policy_id = newrelic_alert_policy.golden_signal_policy.id
name = "High CPU usage"
type = "infra_metric"
event = "SystemSample"
select = "cpuPercent"
comparison = "above"
runbook_url = "https://www.example.com"
where = "(`applicationId` = '${data.newrelic_entity.example_app.application_id}')"
# Define a critical alert threshold that will trigger after 5 minutes above 90% CPU utilization.
critical {
duration = 5
value = 90
time_function = "all"
}
}

インフラストラクチャアラートでは、これらのホストの合計CPU使用率が5分間に90%を超えた場合にトリガーされるnewrelic_infra_alert_conditionを作成しました。

アラートがトリガーされたときに通知を受け取る

これまでに、いくつかの重要なアラート条件を設定しました。アラートポリシーに通知先と通知チャネルを追加して、アラートがトリガーされたときに適切な人物に通知が届くようにします。そのためには、newrelic_notification_destinationnewrelic_notification_channelを使用します。

まず、メール通知の送信先を作成し、受信者リストを設定します。受信者リストには、特定の個人やチームを指定できます。これは通知チャネルを作成する際に使用します。

resource "newrelic_notification_destination" "team_email_destination" {
name = "email-example"
type = "EMAIL"
property {
key = "email"
value = "team.member1@email.com,team.member2@email.com,team.member3@email.com"
}
}

複数のメールアドレスを指定する場合は、メールアドレスをカンマ区切りで並べてください。

次に、メールアドレスにアラート通知を送信するために、メール通知チャネルテンプレートを作成します。チャネルを送信先IDに関連付けます。

resource "newrelic_notification_channel" "team_email_channel" {
name = "email-example"
type = "EMAIL"
destination_id = newrelic_notification_destination.team_email_destination.id
product = "IINT"
property {
key = "subject"
value = "New Subject"
}
}

最後に、アラートポリシーに通知チャネルを適用するために、newrelic_workflowを作成します。

resource "newrelic_workflow" "team_workflow" {
name = "workflow-example"
enrichments_enabled = true
destinations_enabled = true
workflow_enabled = true
muting_rules_handling = "NOTIFY_ALL_ISSUES"
enrichments {
nrql {
name = "Log"
configurations {
query = "SELECT count(*) FROM Metric"
}
}
}
issues_filter {
name = "filter-example"
type = "FILTER"
predicate {
attribute = "accumulations.sources"
operator = "EXACTLY_MATCHES"
values = [ "newrelic" ]
}
}
destination {
channel_id = newrelic_notification_channel.team_email_channel.id
}
}

newrelic_workflowにより、先ほど作成した通知チャネルをアラートにリンクします。

通知設定を完了するには、terraform applyをもう一度実行して、設定済みのすべてのリソースを最新の状態にしてください。

アラートがトリガーされたときに通知を受け取る(非推奨)

重要

アラートチャネルは非推奨となり、今後のバージョンでサポートされなくなります。

これまでに、いくつかの重要なアラート条件を設定しました。アラートポリシーに通知チャネルを追加して、アラートがトリガーされたときに適切な人物に通知が届くようにします。そのためには、newrelic_alert_channelを使用します。

まず、メールアドレスにアラート通知を送信するには、メール通知チャネルを作成します。これは、アラートがトリガーされた際に特定の人物やチームに通知したい場合に使用します。

resource "newrelic_alert_channel" "team_email" {
name = "example"
type = "email"
config {
recipients = "yourawesometeam@example.com"
include_json_attachment = "1"
}
}

複数のrecipientsを指定する場合は、メールアドレスをカンマ区切りで並べてください。

最後に、アラートポリシーに通知チャネルを適用するために、newrelic_alert_policy_channelを作成します。

resource "newrelic_alert_policy_channel" "golden_signals" {
policy_id = newrelic_alert_policy.golden_signal_policy.id
channel_ids = [newrelic_alert_channel.team_email.id]
}

newrelic_alert_policy_channelにより、先ほど作成した通知チャネルをアラートポリシーにリンクします。

ゴールデンシグナルアラートの設定を完了するには、terraform applyをもう一度実行して、設定済みのすべてのリソースを最新の状態にしてください。

応用

new_relic_alert_channel はメール、Slack、PagerDutyなど、複数の種類の通知チャネルをサポートしています。詳しく確認したい場合は、Slackなどの別のチャネルタイプのチャネルを作成してみましょう。

# Slack notification channel
resource "newrelic_alert_channel" "slack_notification" {
name = "slack-example"
type = "slack"
config {
# Use the URL provided in your New Relic Slack integration
url = "https://hooks.slack.com/services/XXXXXXX/XXXXXXX/XXXXXXXXXX"
channel = "your-slack-channel-for-alerts"
}
}

この変更をapply前に、New Relic SlackアプリをSlackアカウントに追加し、通知を送信するSlackチャネルを選択する必要があります。この新しいアラートチャネルにより、トリガーされたアラートが指定のSlackチャネルに通知を送信します。

結論

チームが導入したアラートシステムを評価する中で、設定値(例:アラートの閾値や期間)の調整が必要であることに気付くでしょう。Terraformプロジェクトをリモートリポジトリで管理している場合は、プルリクエストを送信することで、チームはそのような変更を他のコード変更と併せて確認できます。

ヒント

また、このプロセスをCI/CDパイプラインで自動化することも検討してみてください。Terraformの推奨プラクティスガイドを参照して、推奨されるワークフローの詳細と、プロビジョニングの実践方法を改善する方法を確認してください。

Copyright © 2026 New Relic株式会社。

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.