0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

さくらクラウドのシンプル監視をAPIで操作した

Posted at

モチベと概要

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?