2015-07-31
■ [ruby][memo] google-api-clientでGCE instanceを起動する
gcloudコマンドと同じことがAPI経由でもできるはずだよね〜と軽い気持ちで試してみたらかなり大変だったので、コードの断片だけ貼っておく。
require 'google/api_client' # v0.8.6
...
def create
if options['mesosphere_id']
network = "global/networks/mesosphere-custom-#{options['mesosphere_id']}"
firewall = "mesosphere-custom-#{options['mesosphere_id']}-port-22"
else
raise "--mesosphere_id is not set"
end
zone = "asia-east1-c"
name = "instance_test1"
gce = google.discovered_api('compute')
logger.info("Creating instance")
res = google.execute(
api_method: gce.instances.insert,
parameters: {
project: config["gce_project_id"],
zone: zone,
},
body_object: {
name: name,
machineType: "zones/#{zone}/machineTypes/n1-standard-1",
disks: [{
boot: true,
initializeParams: {
sourceImage: "projects/google-containers/global/images/container-vm-v20150715",
diskSizeGb: 50,
},
}],
networkInterfaces: [{
network: network, # Mesosphereとの連携に使用
accessConfigs: [{type: 'ONE_TO_ONE_NAT', name: 'External NAT'}] # これがないと外部IPが付かない
}],
tags: {items: [firewall]} # Mesosphereとの連携に使用
}
)
logger.debug(res.inspect)
json = JSON.parse(res.body)
if json["error"]
logger.error("Got error:\n"+res.body)
else
logger.info("Response:\n"+res.body)
end
end
private
def google
return @google if @google
@google = Google::APIClient.new(
:application_name => 'Example Ruby application',
:application_version => '1.0.0'
)
@google.authorization = :google_app_default
@google.authorization.fetch_access_token!
return @google
end
end