Google APIsを使ってGCEのスナップショットを取得する(PHP Laravel5)
Google APIsのPHPクライアント
githubにPHPのクライアントライブラリがあるのでそれを使います。
composer require設定
"google/apiclient": "^2.0.0@RC"
composer autoload設定
"autoload": { "classmap": [ "vendor/google/apiclient/src/Google" ], "psr-4": { "App\\": "app/" } },
Compute Engine API
google-api-php-clientは、カレンダーとかメールとか多数のAPIラッパーがあります。今回はスナップショットを作成するので、Compute Engine API
を利用します。
GCEで実行する場合はデフォルトの認証キーが利用できる
Authorizing Requests to Google Compute Engine
If you run applications on your Compute Engine instances, application default credentials can obtain credentials through built-in service accounts
具体的には以下2行で認証情報を設定できます。
$client = new \Google_Client(); $client->useApplicationDefaultCredentials();
スナップショット作成
$client = new \Google_Client(); $client->useApplicationDefaultCredentials(); $client->setScopes([\Google_Service_Compute::COMPUTE]); $compute_service = new \Google_Service_Compute($client); // 既存のスナップショット削除 try { $compute_service->snapshots->delete('project-name', 'snapshot-name', array()); } catch (\Exception $e) {} // スナップショット作成 try { $snapshot = new \Google_Service_Compute_Snapshot(); $snapshot->setName('snapshot-name'); $compute_service->disks->createSnapshot('project-name', 'asia-east1-a', 'instance-name', $snapshot, array()); } catch (\Exception $e) { Log::error($e); }
まとめ
Compute Engine API以外にもBigquery APIなど使えるので今後組み込んでみます。
参考
Authorizing Requests to Google Compute Engine
Google API - Service account connection - Laravel 5
Google Application Default Credentials
LARAVEL 5 + GOOGLE APIS CLIENT LIBRARY
[GoogleAPI千本ノック] Google Compute Engine API を試してみた