タイトルのままです。 先日利用を始めた個人環境用の New Relic について、Infrastructure だけではなくて外形監視(Synthetics)も行うことにしました。 Terraform では New Relic のための Provider も用意されており、New Relic 側に丁寧なスタートのためのドキュメントもあります。
Syntheics は外形監視を行う New Relic のサービスの一つです。
Terraform のリソースでは newrelic_synthetics_XXXX のルールで用意されており、2021-10-15 現在だと以下が存在しています。
- newrelic_synthetics_alert_condition
- newrelic_synthetics_monitor
- newrelic_synthetics_monitor_script
- newrelic_synthetics_multilocation_alert_condition
- newrelic_synthetics_secure_credential
上記の中で今回利用するのはnewrelic_synthetics_monitorです。
ドキュメントよりサンプルを以下に引用します。
resource "newrelic_synthetics_monitor" "foo" {
name = "foo"
type = "SIMPLE"
frequency = 5
status = "ENABLED"
locations = ["AWS_US_EAST_1", "AWS_US_EAST_2"]
uri = "https://example.com" # Required for type "SIMPLE" and "BROWSER"
validation_string = "add example validation check here" # Optional for type "SIMPLE" and "BROWSER"
verify_ssl = true # Optional for type "SIMPLE" and "BROWSER"
}
見ての通り、監視したいURIについて uri パラメタに設定し、監視間隔や方法などを指定するシンプルなリソースです。
このまま複数のサイトを監視したい場合、似たようなリソースを別名で単純に増やしていくこともできますが、 for_reach を利用することでコンパクトに定義することができます。
Code
ここでは以下の URI を、正常であればそのサイトに含まれる文字列を指定して監視します。
- https://example.com は "Example Domain" を含む文字列を返す
- https://blog.morihaya.tech は "morihaya" を含む文字列を返す
resource "newrelic_synthetics_monitor" "main" {
for_each = {
# key(FQDN to check site) = value(Validation string)
"example.com" = "Example Domain"
"blog.morihaya.tech" = "morihaya"
}
name = each.key
type = "SIMPLE"
frequency = 15
status = "ENABLED"
locations = ["AWS_AP_NORTHEAST_1"]
uri = "https://${each.key}" # Required for type "SIMPLE" and "BROWSER"
validation_string = each.value # Optional for type "SIMPLE" and "BROWSER"
verify_ssl = true # Optional for type "SIMPLE" and "BROWSER"
}
他に provider の記載もサンプルとして載せておきます。 ざっとポイントとしては
- state ファイルの格納先に Terraform Cloud を使用
- required_providers で newrelic を指定*1
- New Relic の API Key については環境変数経由で渡す*2
export TF_VAR_newrelic_key=XXXXXXexport TF_VAR_newrelic_keyid=XXXXXX
terraform {
# Require the latest the New Relic provider
required_providers {
newrelic = {
source = "newrelic/newrelic"
}
}
backend "remote" {
organization = "morihaya"
workspaces {
name = "morihaya-infra-newrelic"
}
}
}
variable "newrelic_accountid" {
type = string
}
variable "newrelic_key" {
type = string
}
provider "newrelic" {
account_id = var.newrelic_accountid # Your New Relic account ID
api_key = var.newrelic_key # Your New Relic user key
region = "US" # US or EU (defaults to US)
}
結果
無事、以下のように外形監視を実装できました!
