This repository has been archived by the owner on Jul 21, 2020. It is now read-only.
forked from scaleway/terraform-provider-scaleway
-
Notifications
You must be signed in to change notification settings - Fork 3
/
data_source_instance_volume.go
64 lines (55 loc) · 1.69 KB
/
data_source_instance_volume.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package scaleway
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
instance "github.com/scaleway/scaleway-sdk-go/api/instance/v1"
)
func dataSourceScalewayInstanceVolume() *schema.Resource {
// Generate datasource schema from resource
dsSchema := datasourceSchemaFromResourceSchema(resourceScalewayInstanceVolume().Schema)
// Set 'Optional' schema elements
addOptionalFieldsToSchema(dsSchema, "name", "zone")
dsSchema["volume_id"] = &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "The ID of the volume",
ConflictsWith: []string{"name"},
ValidateFunc: validationUUIDorUUIDWithLocality(),
}
dsSchema["name"].ConflictsWith = []string{"volume_id"}
return &schema.Resource{
Read: dataSourceScalewayInstanceVolumeRead,
Schema: dsSchema,
}
}
func dataSourceScalewayInstanceVolumeRead(d *schema.ResourceData, m interface{}) error {
meta := m.(*Meta)
instanceApi, zone, err := instanceAPIWithZone(d, meta)
if err != nil {
return err
}
volumeID, ok := d.GetOk("volume_id")
if !ok { // Get volumes by zone and name.
res, err := instanceApi.ListVolumes(&instance.ListVolumesRequest{
Zone: zone,
Name: String(d.Get("name").(string)),
})
if err != nil {
return err
}
if len(res.Volumes) == 0 {
return fmt.Errorf("no volume found with the name %s", d.Get("name"))
}
if len(res.Volumes) > 1 {
return fmt.Errorf("%d volumes found with the same name %s", len(res.Volumes), d.Get("name"))
}
volumeID = res.Volumes[0].ID
}
zonedID := datasourceNewZonedID(volumeID, zone)
d.SetId(zonedID)
err = d.Set("volume_id", zonedID)
if err != nil {
return err
}
return resourceScalewayInstanceVolumeRead(d, m)
}