IDFromName for networking resources
diff --git a/openstack/networking/v2/ports/requests.go b/openstack/networking/v2/ports/requests.go
index 781a3c3..bba8b71 100644
--- a/openstack/networking/v2/ports/requests.go
+++ b/openstack/networking/v2/ports/requests.go
@@ -1,6 +1,8 @@
package ports
import (
+ "fmt"
+
"github.com/rackspace/gophercloud"
"github.com/rackspace/gophercloud/pagination"
)
@@ -223,3 +225,36 @@
_, res.Err = c.Delete(deleteURL(c, id), nil)
return res
}
+
+// IDFromName is a convienience function that returns a port's ID given its name.
+func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) {
+ portCount := 0
+ portID := ""
+ if name == "" {
+ return "", fmt.Errorf("A network name must be provided.")
+ }
+ pager := List(client, nil)
+ pager.EachPage(func(page pagination.Page) (bool, error) {
+ portList, err := ExtractPorts(page)
+ if err != nil {
+ return false, err
+ }
+
+ for _, p := range portList {
+ if p.Name == name {
+ portCount++
+ portID = p.ID
+ }
+ }
+ return true, nil
+ })
+
+ switch portCount {
+ case 0:
+ return "", fmt.Errorf("Unable to find network: %s", name)
+ case 1:
+ return portID, nil
+ default:
+ return "", fmt.Errorf("Found %d networks matching %s", portCount, name)
+ }
+}