[MyFirstApp] Gophercloud library migration

Migrating from rackspace/gophercloud to gophercloud/gophercloud library.

Change-Id: Ia72a4c548e23b4225b788520d924be8e04ce5c6f
This commit is contained in:
Marcela Bonell 2017-01-10 12:48:55 -06:00
parent f03fcbdc62
commit ef14eaaf5e
3 changed files with 300 additions and 263 deletions

View File

@ -1,294 +1,310 @@
package main package main
import ( import (
"fmt" "fmt"
"io/ioutil" "github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack"
"github.com/rackspace/gophercloud" "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/floatingips"
"github.com/rackspace/gophercloud/openstack" "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/keypairs"
"github.com/rackspace/gophercloud/openstack/compute/v2/flavors" "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/secgroups"
"github.com/rackspace/gophercloud/openstack/compute/v2/images" "github.com/gophercloud/gophercloud/openstack/compute/v2/flavors"
"github.com/rackspace/gophercloud/openstack/compute/v2/servers" "github.com/gophercloud/gophercloud/openstack/compute/v2/images"
"github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip" "github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
"github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs" "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/external"
"github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups" "github.com/gophercloud/gophercloud/openstack/networking/v2/networks"
"github.com/rackspace/gophercloud/openstack/networking/v2/networks" "io/ioutil"
"github.com/rackspace/gophercloud/openstack/networking/v2/extensions/external" "os"
) )
func main() { func main() {
// step-1
var authUsername string = "your_auth_username"
var authPassword string = "your_auth_password"
var authUrl string = "http://controller:5000"
var projectName string = "your_project_id"
var regionName string = "your_region_name"
authOpts := gophercloud.AuthOptions{ // step-1
IdentityEndpoint: authUrl, authOpts, err := openstack.AuthOptionsFromEnv()
Username: authUsername, if err != nil {
Password: authPassword, fmt.Println(err)
TenantID: projectName, return
} }
provider, _ := openstack.AuthenticatedClient(authOpts)
client, _ := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{
Region: regionName,
})
// step-2 provider, err := openstack.AuthenticatedClient(authOpts)
pager := images.ListDetail(client, images.ListOpts{}) if err != nil {
page, _ := pager.AllPages() fmt.Println(err)
imageList, _ := images.ExtractImages(page) return
fmt.Println(imageList) }
// step-3 var regionName = os.Getenv("OS_REGION_NAME")
pager = flavors.ListDetail(client, flavors.ListOpts{}) client, err := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{
page, _ = pager.AllPages() Region: regionName,
flavorList, _ := flavors.ExtractFlavors(page) Type: "computev21",
fmt.Println(flavorList) })
if err != nil {
fmt.Println(err)
return
}
// step-4 // step-2
imageID := "74e6d1ec-9a08-444c-8518-4f232446386d" pager := images.ListDetail(client, images.ListOpts{})
image, _ := images.Get(client, imageID).Extract() page, _ := pager.AllPages()
fmt.Println(image) imageList, _ := images.ExtractImages(page)
fmt.Println(imageList)
// step-5 // step-3
flavorID := "1" pager = flavors.ListDetail(client, flavors.ListOpts{})
flavor, _ := flavors.Get(client, flavorID).Extract() page, _ = pager.AllPages()
fmt.Println(flavor) flavorList, _ := flavors.ExtractFlavors(page)
fmt.Println(flavorList)
// step-6 // step-4
instanceName := "testing" imageID := "74e6d1ec-9a08-444c-8518-4f232446386d"
testingInstance, _ := servers.Create(client, servers.CreateOpts{ image, _ := images.Get(client, imageID).Extract()
Name: instanceName, fmt.Println(image)
ImageRef: imageID,
FlavorRef: flavorID,
}).Extract()
fmt.Println(testingInstance)
// step-7 // step-5
pager = servers.List(client, servers.ListOpts{}) flavorID := "1"
page, _ = pager.AllPages() flavor, _ := flavors.Get(client, flavorID).Extract()
serverList, _ := servers.ExtractServers(page) fmt.Println(flavor)
fmt.Println(serverList)
// step-8 // step-6
servers.Delete(client, testingInstance.ID) instanceName := "testing"
testingInstance, err := servers.Create(client, servers.CreateOpts{
Name: instanceName,
ImageRef: imageID,
FlavorRef: flavorID,
}).Extract()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(testingInstance)
// step-9 // step-7
fmt.Println("Checking for existing SSH key pair...") pager = servers.List(client, servers.ListOpts{})
keyPairName := "demokey" page, _ = pager.AllPages()
pubKeyFile := "~/.ssh/id_rsa.pub" serverList, _ := servers.ExtractServers(page)
keyPairExists := false fmt.Println(serverList)
pager = keypairs.List(client) // step-8
page, _ = pager.AllPages() servers.Delete(client, testingInstance.ID)
keypairList, _ := keypairs.ExtractKeyPairs(page)
for _, k := range keypairList {
if k.Name == keyPairName {
keyPairExists = true
break
}
}
if keyPairExists { // step-9
fmt.Println("Keypair " + keyPairName + " already exists. Skipping import.") fmt.Println("Checking for existing SSH key pair...")
} else { keyPairName := "demokey"
fmt.Println("adding keypair...") pubKeyFile := "~/.ssh/id_rsa.pub"
bs, _ := ioutil.ReadFile(pubKeyFile) keyPairExists := false
keypairs.Create(client, keypairs.CreateOpts{
Name: keyPairName,
PublicKey: string(bs),
}).Extract()
}
pager = keypairs.List(client) pager = keypairs.List(client)
page, _ = pager.AllPages() page, _ = pager.AllPages()
keypairList, _ = keypairs.ExtractKeyPairs(page) keypairList, _ := keypairs.ExtractKeyPairs(page)
fmt.Println(keypairList) for _, k := range keypairList {
if k.Name == keyPairName {
keyPairExists = true
break
}
}
// step-10 if keyPairExists {
fmt.Println("Checking for existing security group...") fmt.Println("Keypair " + keyPairName + " already exists. Skipping import.")
var allInOneSecurityGroup secgroups.SecurityGroup } else {
securityGroupName := "all-in-one" fmt.Println("adding keypair...")
securityGroupExists := false bs, _ := ioutil.ReadFile(pubKeyFile)
keypairs.Create(client, keypairs.CreateOpts{
Name: keyPairName,
PublicKey: string(bs),
}).Extract()
}
pager = secgroups.List(client) pager = keypairs.List(client)
page, _ = pager.AllPages() page, _ = pager.AllPages()
secgroupList, _ := secgroups.ExtractSecurityGroups(page) keypairList, _ = keypairs.ExtractKeyPairs(page)
for _, secGroup := range secgroupList { fmt.Println(keypairList)
if secGroup.Name == securityGroupName {
allInOneSecurityGroup = secGroup
securityGroupExists = true
break
}
}
if securityGroupExists { // step-10
fmt.Println("Security Group " + allInOneSecurityGroup.Name + " already exists. Skipping creation.") fmt.Println("Checking for existing security group...")
} else { var allInOneSecurityGroup secgroups.SecurityGroup
allInOneSecurityGroup, _ := secgroups.Create(client, secgroups.CreateOpts{ securityGroupName := "all-in-one"
Name: securityGroupName, securityGroupExists := false
Description: "network access for all-in-one application.",
}).Extract()
secgroups.CreateRule(client, secgroups.CreateRuleOpts{
ParentGroupID: allInOneSecurityGroup.ID,
FromPort: 80,
ToPort: 80,
IPProtocol: "TCP",
CIDR: "0.0.0.0/0",
}).Extract()
secgroups.CreateRule(client, secgroups.CreateRuleOpts{
ParentGroupID: allInOneSecurityGroup.ID,
FromPort: 22,
ToPort: 22,
IPProtocol: "TCP",
CIDR: "0.0.0.0/0",
}).Extract()
}
pager = secgroups.List(client) pager = secgroups.List(client)
page, _ = pager.AllPages() page, _ = pager.AllPages()
secgroupList, _ = secgroups.ExtractSecurityGroups(page) secgroupList, _ := secgroups.ExtractSecurityGroups(page)
fmt.Println(secgroupList) for _, secGroup := range secgroupList {
if secGroup.Name == securityGroupName {
allInOneSecurityGroup = secGroup
securityGroupExists = true
break
}
}
// step-11 if securityGroupExists {
userData := `#!/usr/bin/env bash fmt.Println("Security Group " + allInOneSecurityGroup.Name + " already exists. Skipping creation.")
curl -L -s https://git.openstack.org/cgit/openstack/faafo/plain/contrib/install.sh | bash -s -- \ } else {
-i faafo -i messaging -r api -r worker -r demo allInOneSecurityGroup, _ := secgroups.Create(client, secgroups.CreateOpts{
` Name: securityGroupName,
Description: "network access for all-in-one application.",
}).Extract()
secgroups.CreateRule(client, secgroups.CreateRuleOpts{
ParentGroupID: allInOneSecurityGroup.ID,
FromPort: 80,
ToPort: 80,
IPProtocol: "TCP",
CIDR: "0.0.0.0/0",
}).Extract()
secgroups.CreateRule(client, secgroups.CreateRuleOpts{
ParentGroupID: allInOneSecurityGroup.ID,
FromPort: 22,
ToPort: 22,
IPProtocol: "TCP",
CIDR: "0.0.0.0/0",
}).Extract()
}
// step-12 pager = secgroups.List(client)
fmt.Println("Checking for existing instance...") page, _ = pager.AllPages()
instanceName = "all-in-one" secgroupList, _ = secgroups.ExtractSecurityGroups(page)
instanceExists := false fmt.Println(secgroupList)
pager = servers.List(client, servers.ListOpts{}) // step-11
page, _ = pager.AllPages() userData := `#!/usr/bin/env bash
serverList, _ = servers.ExtractServers(page) curl -L -s https://git.openstack.org/cgit/openstack/faafo/plain/contrib/install.sh | bash -s -- \
for _, s := range serverList { -i faafo -i messaging -r api -r worker -r demo`
if s.Name == instanceName {
testingInstance = &s
instanceExists = true
break
}
}
if instanceExists { // step-12
fmt.Println("Instance " + testingInstance.Name + " already exists. Skipping creation.") fmt.Println("Checking for existing instance...")
} else { instanceName = "all-in-one"
opts := servers.CreateOpts{ instanceExists := false
Name: instanceName,
ImageRef: image.ID,
FlavorRef: flavor.ID,
SecurityGroups: []string{securityGroupName},
UserData: []byte(userData),
}
testingInstance, _ = servers.Create(client, keypairs.CreateOptsExt{
CreateOptsBuilder: opts,
KeyName: keyPairName,
}).Extract()
}
servers.WaitForStatus(client, testingInstance.ID, "ACTIVE", 300)
pager = servers.List(client, servers.ListOpts{}) pager = servers.List(client, servers.ListOpts{})
page, _ = pager.AllPages() page, _ = pager.AllPages()
serverList, _ = servers.ExtractServers(page) serverList, _ = servers.ExtractServers(page)
fmt.Println(serverList) for _, s := range serverList {
if s.Name == instanceName {
testingInstance = &s
instanceExists = true
break
}
}
// step-13 if instanceExists {
var privateIP string fmt.Println("Instance " + testingInstance.Name + " already exists. Skipping creation.")
for t, addrs := range testingInstance.Addresses { } else {
if t != "private" || len(privateIP) != 0 { opts := servers.CreateOpts{
continue Name: instanceName,
} ImageRef: image.ID,
addrs, ok := addrs.([]interface{}) FlavorRef: flavor.ID,
if !ok { SecurityGroups: []string{securityGroupName},
continue UserData: []byte(userData),
} }
for _, addr := range addrs { testingInstance, err = servers.Create(client, keypairs.CreateOptsExt{
a, ok := addr.(map[string]interface{}) CreateOptsBuilder: opts,
if !ok || a["version"].(float64) != 4 { KeyName: keyPairName,
continue }).Extract()
} if err != nil {
ip, ok := a["addr"].(string) fmt.Println(err)
if ok && len(ip) != 0 { return
privateIP = ip }
fmt.Println("Private IP found: " + privateIP) }
break servers.WaitForStatus(client, testingInstance.ID, "ACTIVE", 300)
}
}
}
// step-14 pager = servers.List(client, servers.ListOpts{})
var publicIP string page, _ = pager.AllPages()
for t, addrs := range testingInstance.Addresses { serverList, _ = servers.ExtractServers(page)
if t != "public" || len(publicIP) != 0 { fmt.Println(serverList)
continue
}
addrs, ok := addrs.([]interface{})
if !ok {
continue
}
for _, addr := range addrs {
a, ok := addr.(map[string]interface{})
if !ok || a["version"].(float64) != 4 {
continue
}
ip, ok := a["addr"].(string)
if ok && len(ip) != 0 {
publicIP = ip
fmt.Println("Public IP found: " + publicIP)
break
}
}
}
// step-15 // step-13
fmt.Println("Checking for unused Floating IP...") var privateIP string
var unusedFloatingIP string for t, addrs := range testingInstance.Addresses {
pager = floatingip.List(client) if t != "private" || len(privateIP) != 0 {
page, _ = pager.AllPages() continue
floatingIPList, _ := floatingip.ExtractFloatingIPs(page) }
for _, ip := range floatingIPList { addrs, ok := addrs.([]interface{})
if ip.InstanceID == "" { if !ok {
unusedFloatingIP = ip.IP continue
break }
} for _, addr := range addrs {
} a, ok := addr.(map[string]interface{})
if !ok || a["version"].(float64) != 4 {
continue
}
ip, ok := a["addr"].(string)
if ok && len(ip) != 0 {
privateIP = ip
fmt.Println("Private IP found: " + privateIP)
break
}
}
}
networkClient, _ := openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{ // step-14
Region: regionName, var publicIP string
}) for t, addrs := range testingInstance.Addresses {
if t != "public" || len(publicIP) != 0 {
continue
}
addrs, ok := addrs.([]interface{})
if !ok {
continue
}
for _, addr := range addrs {
a, ok := addr.(map[string]interface{})
if !ok || a["version"].(float64) != 4 {
continue
}
ip, ok := a["addr"].(string)
if ok && len(ip) != 0 {
publicIP = ip
fmt.Println("Public IP found: " + publicIP)
break
}
}
}
pager = networks.List(networkClient, networks.ListOpts{}) // step-15
page, _ = pager.AllPages() fmt.Println("Checking for unused Floating IP...")
poolList, _ := external.ExtractList(page) var unusedFloatingIP string
for _, pool := range poolList { pager = floatingips.List(client)
if len(unusedFloatingIP) != 0 || !pool.External { page, _ = pager.AllPages()
continue floatingIPList, _ := floatingips.ExtractFloatingIPs(page)
} for _, ip := range floatingIPList {
fmt.Println("Allocating new Floating IP from pool: " + pool.Name) if ip.InstanceID == "" {
f, _ := floatingip.Create(client, floatingip.CreateOpts{Pool: pool.Name}).Extract() unusedFloatingIP = ip.IP
unusedFloatingIP = f.IP break
} }
}
// step-16 networkClient, _ := openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{
if len(publicIP) != 0 { Region: regionName,
fmt.Println("Instance " + testingInstance.Name + " already has a public ip. Skipping attachment.") })
} else {
floatingip.Associate(client, testingInstance.ID, unusedFloatingIP)
}
// step-17 pager = networks.List(networkClient, networks.ListOpts{})
var actualIPAddress string page, _ = pager.AllPages()
if len(publicIP) != 0 { poolList, _ := external.ExtractList(page)
actualIPAddress = publicIP for _, pool := range poolList {
} else if len(unusedFloatingIP) != 0 { if len(unusedFloatingIP) != 0 || !pool.External {
actualIPAddress = unusedFloatingIP continue
} else { }
actualIPAddress = privateIP fmt.Println("Allocating new Floating IP from pool: " + pool.Name)
} f, _ := floatingips.Create(client, floatingips.CreateOpts{Pool: pool.Name}).Extract()
unusedFloatingIP = f.IP
}
fmt.Println("The Fractals app will be deployed to http://" + actualIPAddress) // step-16
if len(publicIP) != 0 {
fmt.Println("Instance " + testingInstance.Name + " already has a public ip. Skipping attachment.")
} else {
opts := floatingips.AssociateOpts{
FloatingIP: unusedFloatingIP,
}
floatingips.AssociateInstance(client, testingInstance.ID, opts)
}
// step-17
var actualIPAddress string
if len(publicIP) != 0 {
actualIPAddress = publicIP
} else if len(unusedFloatingIP) != 0 {
actualIPAddress = unusedFloatingIP
} else {
actualIPAddress = privateIP
}
fmt.Println("The Fractals app will be deployed to http://" + actualIPAddress)
} }

View File

@ -33,3 +33,24 @@ Specify a network during instance build
image=image_id, image=image_id,
flavor=flavor_id, flavor=flavor_id,
network=network_id) network=network_id)
.. only:: gophercloud
Add the option Networks and send its id to attach the instance to:
.. code-block:: go
opts := servers.CreateOpts {
Name: instanceName,
ImageRef: image.ID,
FlavorRef: flavor.ID,
SecurityGroups: []string{securityGroupName},
UserData: []byte(userData),
Networks: []servers.Network{servers.Network{UUID: networkID}},
}
testingInstance, _ = servers.Create(client, keypairs.CreateOptsExt {
CreateOptsBuilder: opts,
KeyName: keyPairName,
}).Extract()

View File

@ -97,9 +97,9 @@ and toolkits with the OpenStack cloud:
Use it to write C++ or C# code for Microsoft applications. Use it to write C++ or C# code for Microsoft applications.
- https://www.nuget.org/packages/openstack.net - https://www.nuget.org/packages/openstack.net
* - Go * - Go
- `gophercloud <https://github.com/rackspace/gophercloud>`_ - `gophercloud <https://github.com/gophercloud/gophercloud>`_
- A go-based SDK. - A go-based SDK.
Use it with multiple clouds. Use it to write Golang code that works with OpenStack clouds.
- http://gophercloud.io/ - http://gophercloud.io/
For a list of available SDKs, see `Software Development Kits <https://wiki.openstack.org/wiki/SDKs>`_. For a list of available SDKs, see `Software Development Kits <https://wiki.openstack.org/wiki/SDKs>`_.
@ -232,7 +232,7 @@ To interact with the cloud, you must also have
.. only:: gophercloud .. only:: gophercloud
`a recent version of gophercloud installed <https://godoc.org/github.com/rackspace/gophercloud>`_ `a recent version of gophercloud installed <https://godoc.org/github.com/gophercloud/gophercloud>`_
Obtain the following information from your cloud provider: Obtain the following information from your cloud provider:
@ -383,14 +383,14 @@ to run code snippets in your language of choice.
.. only:: gophercloud .. only:: gophercloud
To try it, add the following code to go file Use environment variables to set your cloud credentials
.. literalinclude:: ../samples/gophercloud/getting_started.go .. literalinclude:: ../samples/gophercloud/getting_started.go
:language: go :language: go
:start-after: step-1 :start-after: step-1
:end-before: step-2 :end-before: step-2
.. note:: The client object accesses the Compute v2.0 service, .. note:: The client object accesses the Compute v2.0 service and type v2.1,
so that version is in this tutorial. so that version is in this tutorial.
Flavors and images Flavors and images