Skip to content
This repository was archived by the owner on Aug 1, 2023. It is now read-only.

Commit f956c6c

Browse files
committed
Merge pull request #440 from jrperritt/block-storage-id-by-name
IDFromName functions for block storage
2 parents d6b6004 + 24c2083 commit f956c6c

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

openstack/blockstorage/v1/snapshots/requests.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,3 +171,36 @@ func UpdateMetadata(client *gophercloud.ServiceClient, id string, opts UpdateMet
171171
})
172172
return res
173173
}
174+
175+
// IDFromName is a convienience function that returns a snapshot's ID given its name.
176+
func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) {
177+
snapshotCount := 0
178+
snapshotID := ""
179+
if name == "" {
180+
return "", fmt.Errorf("A snapshot name must be provided.")
181+
}
182+
pager := List(client, nil)
183+
pager.EachPage(func(page pagination.Page) (bool, error) {
184+
snapshotList, err := ExtractSnapshots(page)
185+
if err != nil {
186+
return false, err
187+
}
188+
189+
for _, s := range snapshotList {
190+
if s.Name == name {
191+
snapshotCount++
192+
snapshotID = s.ID
193+
}
194+
}
195+
return true, nil
196+
})
197+
198+
switch snapshotCount {
199+
case 0:
200+
return "", fmt.Errorf("Unable to find snapshot: %s", name)
201+
case 1:
202+
return snapshotID, nil
203+
default:
204+
return "", fmt.Errorf("Found %d snapshots matching %s", snapshotCount, name)
205+
}
206+
}

openstack/blockstorage/v1/volumes/requests.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,3 +201,36 @@ func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder
201201
})
202202
return res
203203
}
204+
205+
// IDFromName is a convienience function that returns a server's ID given its name.
206+
func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) {
207+
volumeCount := 0
208+
volumeID := ""
209+
if name == "" {
210+
return "", fmt.Errorf("A volume name must be provided.")
211+
}
212+
pager := List(client, nil)
213+
pager.EachPage(func(page pagination.Page) (bool, error) {
214+
volumeList, err := ExtractVolumes(page)
215+
if err != nil {
216+
return false, err
217+
}
218+
219+
for _, s := range volumeList {
220+
if s.Name == name {
221+
volumeCount++
222+
volumeID = s.ID
223+
}
224+
}
225+
return true, nil
226+
})
227+
228+
switch volumeCount {
229+
case 0:
230+
return "", fmt.Errorf("Unable to find volume: %s", name)
231+
case 1:
232+
return volumeID, nil
233+
default:
234+
return "", fmt.Errorf("Found %d volumes matching %s", volumeCount, name)
235+
}
236+
}

0 commit comments

Comments
 (0)