Skip to content

Instantly share code, notes, and snippets.

@stephenfin
Last active February 14, 2024 13:59
Show Gist options
  • Save stephenfin/a07f378586e12b19a99a017ac49a4070 to your computer and use it in GitHub Desktop.
Save stephenfin/a07f378586e12b19a99a017ac49a4070 to your computer and use it in GitHub Desktop.
Gophercloud examples
package main
import (
"os"
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/layer3/floatingips"
"github.com/gophercloud/gophercloud/openstack/networking/v2/networks"
"github.com/gophercloud/utils/openstack/clientconfig"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("usage: create-fip <NETWORK>")
return
}
network := os.Args[1]
opts := new(clientconfig.ClientOpts)
// We could configure the cloud manually but we don't. Instead we'll leave it unset causing gophercloud to load the
// cloud from the 'OS_CLOUD' environment variable. We could also simplify this further and pass 'nil' below instead
// of generating and passing a 'ClientOpts' object but this shows how you _could_ configure things if you so chose.
// opts.Cloud = "devstack-admin"
client, err := clientconfig.NewServiceClient("network", opts)
if err != nil {
fmt.Println(err)
return
}
pager, err := networks.List(client, networks.ListOpts{
Name: network,
}).AllPages()
if err != nil {
fmt.Println(err)
return
}
networks, err := networks.ExtractNetworks(pager)
if err != nil {
fmt.Println(err)
return
}
if len(networks) > 1 {
fmt.Println("Found more than one match!")
return
}
if len(networks) < 1 {
fmt.Println("Found no matches!")
return
}
floatingIP, err := floatingips.Create(client, floatingips.CreateOpts{
Description: "stephenfin hello-world FIP",
FloatingNetworkID: networks[0].ID,
}).Extract()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Created FIP")
fmt.Printf("floating IP: id=%s, tags=%s\n", floatingIP.ID, floatingIP.Tags)
tag := fmt.Sprintf("fooBar=%s", "wow")
err = attributestags.Add(client, "floatingips", floatingIP.ID, tag).ExtractErr()
if err != nil {
fmt.Println(err)
return
}
floatingIP, err = floatingips.Get(client, floatingIP.ID).Extract()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Tagged FIP")
fmt.Printf("floating IP: id=%s, tags=%s\n", floatingIP.ID, floatingIP.Tags)
err = floatingips.Delete(client, floatingIP.ID).ExtractErr()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Deleted FIP")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment