Created
December 25, 2017 06:40
-
-
Save hironobu-s/09be8f7e7422f5a477182a871ae8d6ca to your computer and use it in GitHub Desktop.
gophercloudサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/rackspace/gophercloud" | |
"github.com/rackspace/gophercloud/openstack" | |
"github.com/rackspace/gophercloud/openstack/compute/v2/servers" | |
"github.com/rackspace/gophercloud/pagination" | |
) | |
func main() { | |
// APIの認証情報を設定する | |
opts := gophercloud.AuthOptions{ | |
IdentityEndpoint: "https://identity.tyo1.conoha.io/v2.0", | |
Username: "gncu********", | |
TenantName: "gnct********", | |
Password: "************", | |
} | |
// AuthenticatedClient() は内部で認証を行い、 | |
// 各サービス(Compute, Network, Storageなど)の | |
// 接続に使われるクライアントを返します。 | |
client, err := openstack.AuthenticatedClient(opts) | |
if err != nil { | |
panic(err) | |
} | |
// このclientは内部に token を保持しています。 | |
println(client.TokenID) | |
// 今回は例としてCompute APIを使います。 | |
// gophercloudでは各サービスへのAPIアクセスをProvider構造体に抽象化されていて、 | |
// openstackパッケージにあるNewComputeV2()を呼ぶと、 | |
// Compute APIへアクセスする情報がセットされたクライアントが返ってきます。 | |
eo := gophercloud.EndpointOpts{ | |
Type: "compute", | |
Region: "tyo1", | |
} | |
compute, err := openstack.NewComputeV2(client, eo) | |
if err != nil { | |
panic(err) | |
} | |
// Compute APIの各機能は | |
// github.com/rackspace/gophercloud/openstack/compute/v2/servers | |
// パッケージにあります。 | |
// 各機能を実行するにはクライアント(compute)を渡す必要があります。 | |
listOpts := servers.ListOpts{} | |
pager := servers.List(compute, listOpts) | |
pager.EachPage(func(page pagination.Page) (bool, error) { | |
serverList, err := servers.ExtractServers(page) | |
if err != nil { | |
return false, err | |
} | |
for _, server := range serverList { | |
fmt.Printf("%v\n", server) | |
} | |
return true, nil | |
}) | |
// VPSを作成するような複雑なリクエストもとても簡単です。 | |
// ただ、gophercloudはConoHa独自のパラメータに対応していません。 | |
// たとえば管理者パスワードを設定する"adminPass"や、 | |
// SSHの公開鍵を指定する"key_name"などです。 | |
// | |
// これらを指定する場合はuser_dataを使うことになります。 | |
// https://www.conoha.jp/guide/startupscript.php | |
copts := servers.CreateOpts{ | |
Name: "gophercloud-test", | |
ImageRef: "b9e54c41-cda9-4d84-8248-808bfaf6c793", | |
FlavorRef: "7eea7469-0d85-4f82-8050-6ae742394681", | |
SecurityGroups: []string{ | |
"default", | |
"gncs-ipv4-all", | |
"gncs-ipv6-all", | |
}, | |
Metadata: map[string]string{ | |
"instance_name_tag": "gophercloud-test", | |
}, | |
} | |
r := servers.Create(compute, copts) | |
if r.Err != nil { | |
panic(r.Err) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment