序章

DigitalOcean APIのバージョン2では、発生する各イベントが「アクション」オブジェクトを作成します。 これらは、過去に発生したイベントの記録としても、進行中のイベントの進行状況を確認する方法としても機能します。 新しいドロップレットの作成から新しい領域への画像の転送まで、Actionオブジェクトはイベントに関する有用な情報を提供します。

この記事では、Actionオブジェクトについて説明し、DigitalOceanAPIの公式RubygemであるDropletKitを介して実際に使用する方法を示します。

前提条件

この記事は、DigitalOceanAPIの基本的な理解を前提としています。 このチュートリアルを完了するために必要なアクセストークンを取得する方法など、APIの詳細については、次のリソースを参照してください。

アクションオブジェクトを理解する

APIを使用してイベントを開始すると、応答でActionオブジェクトが返されます。 このオブジェクトには、イベントのステータス、開始および完了したときのタイムスタンプ、関連するリソースタイプとIDなどのイベントに関する情報が含まれます。 たとえば、ID3164450のドロップレットのスナップショットを取得する場所を考えてみましょう。

curl -X POST -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer '$TOKEN'' \
    -d '{"type":"snapshot","name":"Nifty New Snapshot"}' \
    "https://api.digitalocean.com/v2/droplets/3164450/actions" 

応答としてこれを受け取ります:

{
  "action": {
    "id": 36805022,
    "status": "in-progress",
    "type": "snapshot",
    "started_at": "2014-11-14T16:34:39Z",
    "completed_at": null,
    "resource_id": 3164450,
    "resource_type": "droplet",
    "region": "nyc3"
  }
}

resource_typedropletであり、resource_idはドロップレットのIDであることに注意してください。 statusin-progressです。 イベントが終了すると、これはcompletedに変わります。 アクションのステータスを確認するために、そのアクションのAPIに直接クエリを実行できます。

curl -X GET -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer '$TOKEN'' \
    "https://api.digitalocean.com/v2/actions/36805022" 

これにより、要求されたアクションオブジェクトが返されます。

{
  "action": {
    "id": 36805022,
    "status": "completed",
    "type": "snapshot",
    "started_at": "2014-11-14T16:34:39Z",
    "completed_at": "2014-11-14T16:38:52Z",
    "resource_id": 3164450,
    "resource_type": "droplet",
    "region": "nyc3"
  }
}

statuscompletedになったので、completed_atstarted_atのタイムスタンプがあることに注意してください。

/actionsエンドポイントでアカウントで実行されたすべてのアクションの完全な履歴にアクセスすることもできます。

curl -X GET -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer '$TOKEN'' \
    "https://api.digitalocean.com/v2/actions"

アクションオブジェクトの実際の使用

すべてのアクションオブジェクトを一覧表示することは、履歴を監査するために興味深い場合がありますが、実際には、プロセスのステータスを確認するために、ほとんどの場合、このエンドポイントを使用します。 これらの例では、droplet_kit DigitalOceanAPIの公式Rubygemを使用します。 次のコマンドでインストールできます。

gem install droplet_kit

開始するには、コマンドirbを実行してRubyシェルに入り、droplet_kit gemをインポートし、APIトークンを使用してクライアントをセットアップします。

irb(main):> require 'droplet_kit'
 => true 
irb(main):> client = DropletKit::Client.new(access_token: DO_TOKEN)

一部のアクションは、他のアクションが最初に実行されることに依存しています。 たとえば、まだ電源がオンになっているドロップレットのスナップショットを取得しようとすると、エラーが発生します。 スナップショットを作成するには、ドロップレットの電源をオフにする必要があります。

irb(main):> client.droplet_actions.snapshot(droplet_id: 4143310, name: 'Snapshot Name')
=> "{\"id\":\"unprocessable_entity\",\"message\":\"Droplet is currently on. Please power it off to run this event.\"}"

シャットダウンアクションを開始した直後にスナップショットを作成しようとすると、スナップショットを作成する前にシャットダウンアクションが完了していることを確認する必要があるため、同じエラーが発生します。 アクションをキューに入れることはできません。

irb(main):> client.droplet_actions.shutdown(droplet_id: 4143310)
=> <DropletKit::Action {:@id=>43918785, :@status=>"in-progress", :@type=>"shutdown", :@started_at=>"2015-02-16T21:22:35Z", :@completed_at=>nil, :@resource_id=>4143310, :@resource_type=>"droplet", :@region=>"nyc3"}>
irb(main):> client.droplet_actions.snapshot(droplet_id: 4143310, name: 'Snapshot Name')
=> "{\"id\":\"unprocessable_entity\",\"message\":\"Droplet is currently on. Please power it off to run this event.\"}"

上記のcurlの例と同様に、droplet_kitも、正常に開始されたイベントに応答してActionオブジェクトを返します。 通常のRubyオブジェクトとしてアクセスできます。 応答を変数に保存すると、その属性に直接アクセスできるようになります。

irb(main):> snapshot = client.droplet_actions.snapshot(droplet_id: 4143310, name: 'Snapshot Name')
=> "{\"id\":\"unprocessable_entity\",\"message\":\"Droplet is currently on. Please power it off to run this event.\"}"
irb(main):> shutdown = client.droplet_actions.shutdown(droplet_id: 4143310)
=> <DropletKit::Action {:@id=>43919195, :@status=>"in-progress", :@type=>"shutdown", :@started_at=>"2015-02-16T21:32:03Z", :@completed_at=>nil, :@resource_id=>4143310, :@resource_type=>"droplet", :@region=>"nyc3"}>
irb(main):> shutdown.status
=> "in-progress"
irb(main):> shutdown.id
=> 43919195

次に、アクションのステータスを確認できます。

irb(main):> action = client.actions.find(id: shutdown.id)
=> <DropletKit::Action {:@id=>43919195, :@status=>"completed", :@type=>"shutdown", :@started_at=>"2015-02-16T21:32:03Z", :@completed_at=>"2015-02-16T21:32:07Z", :@resource_id=>4143310, :@resource_type=>"droplet", :@region=>"nyc3"}>
irb(main):> action.status
=> "completed"

Rubyでuntilループを使用して、アクションが完了するまでアクションの進行状況を確認できます。

res = client.droplet_actions.shutdown(droplet_id: id)
until res.status == "completed"
    res = client.actions.find(id: res.id)
    sleep(2)
end

すべてを一緒に入れて

以下のRubyスクリプトは、実際のアクションのステータスを確認する方法の例です。 ドロップレットの電源を切り、上からwhileループを使用して、次に進む前にアクションが完了したことを確認します。 シャットダウンアクションが完了すると、ドロップレットのスナップショットが作成されます。

#!/usr/bin/env ruby

require 'droplet_kit'
require 'json'

token = ENV['DO_TOKEN']
client = DropletKit::Client.new(access_token: token)

droplet_id = ARGV[0]
snapshot_name = ARGV[1] || Time.now.strftime("%b. %d, %Y - %H:%M:%S %Z")

def power_off(client, id)
    res = client.droplet_actions.shutdown(droplet_id: id)
    until res.status == "completed"
        res = client.actions.find(id: res.id)
        sleep(2)
    end
    puts " *   Action status: #{res.status}"
rescue NoMethodError
    puts JSON.parse(res)['message']
end

def take_snapshot(client, id, name)
    res = client.droplet_actions.snapshot(droplet_id: id, name: name)
    puts " *   Action status: #{res.status}"
rescue NameError
    puts JSON.parse(res)['message']
end

unless droplet_id.nil?
    puts "Powering off droplet..."
    power_off(client, droplet_id)
    sleep(2)
    puts "Taking snapshot..."
    take_snapshot(client, droplet_id, snapshot_name)
else
    puts "Power off and snapshot a droplet. Requires a droplet ID and optionally a snapshot name."
    puts "Usage: #{$0} droplet_id ['snapshot name']"
end

このスクリプトをsnapshot.rbという名前のファイルとして保存する(または this GitHub Gist からダウンロードする)と、次のようにコマンドラインから実行できます。

DO_TOKEN=YOUR_DO_API_TOKEN ruby snapshot.rb 12345 "My Snapshot"

スクリプトを使用するには、APIトークンをDO_TOKENという名前の環境変数としてエクスポートする必要があることに注意してください。 スクリプトは、ドロップレットのIDとオプションでスナップショットの名前の2つの引数を取ります。 名前を指定しない場合は、日付と時刻になります。

結論

アクションアイテムは、DigtialOceanAPIの重要な部分です。 これらを使用してアクションのステータスを確認することは、APIを使用するときに実装する重要なベストプラクティスです。 それらの使用方法を理解したので、次のようなAPIのより複雑なユースケースに進む準備ができています。

その他のトピックについては、DigitalOcean開発者ポータルを確認してください。