モチベと概要
10件以上のウェブサイト、ウェブアプリが元気かどうかをインフラ外から監視したい。
さくらのシンプル監視を採用したらWeb APIが充実してるので、APIで一気に登録すれば楽そうだ。
と思ったら、ドキュメントがない、、、?
ないと思ったが、よく読んだらあった。「共通サービス」というリソースに属しているらしい。
→ https://manual.sakura.ad.jp/cloud-api/1.1/appliance/index.html#get_commonserviceitem
これに気づけず、読まずにダッシュボード上のログだけみてRubyで叩けるようがんばった。できた。
改めてさくらのシンプル監視とは
1設定あたり22円/月でいい感じに監視してくれる。例えば https://www.phalanxware.com をみる。など。
コード
以下みたいに準備して
require 'net/http'
require 'dotenv'
require 'json'
require 'yaml'
Dotenv.load
token = ENV.fetch('SAKURA_ACCESS')
secret = ENV.fetch('SAKURA_SECRET')
zone_id = 'is1a'
api_version = '1.1'
tags = ['FromAPI']
base_url = "https://secure.sakura.ad.jp/cloud/zone/#{zone_id}/api/cloud/#{api_version}/"
uri = URI.parse(base_url + '/commonserviceitem')
こんなようなYAMLを用意して
services:
- fqdn: www.phalanxware.com
port: 443
protocol: https
description: 自社サイト
response_status: 200 # 期待値
skip: false
これを以下みたいに読み込んでループすればOK。すでに設定されているか確認していないので、リソースがどんどん再登録されてしまうので注意。
YAML.load_file('target.yaml')
.fetch('services')
.select { it.fetch('skip') == false }
.each do |service|
params = {
"CommonServiceItem": {
"Name": service.fetch('fqdn'),
"Status": {
"Target": service.fetch('fqdn')
},
"Settings": {
"SimpleMonitor": {
"HealthCheck": {
"Protocol": service.fetch('protocol'),
"Host": service.fetch('fqdn'),
"Port": service.fetch('port').to_i,
"Path": "/",
"Status": service.fetch('response_status')
},
"Enabled": "True",
"NotifyEmail": {
"Enabled": "True",
"HTML": "False"
},
"NotifySlack": {
"Enabled": "False"
},
"DelayLoop": 60,
"MaxCheckAttempts": 3,
"RetryInterval": 10,
"Timeout": 10
}
},
"Provider": {
"Class": "simplemon"
},
"Tags": tags,
"Icon": {},
"Description": [
"my-company-servers",
service.fetch('description')
].join(' - ')
},
"Count": 0,
}
req = Net::HTTP::Post.new(uri.path.to_s)
req.basic_auth(token, secret)
req.body=(JSON.generate(params))
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
res = https.start do |x|
x.request(req)
end
pp res.code
pp res.body
pp JSON.load(res.body)
end