/
data_source_baremetal_option.go
90 lines (82 loc) · 2.49 KB
/
data_source_baremetal_option.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package scaleway
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/scaleway/scaleway-sdk-go/api/baremetal/v1"
"github.com/scaleway/scaleway-sdk-go/scw"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/datasource"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/locality/zonal"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/verify"
)
func DataSourceScalewayBaremetalOption() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceScalewayBaremetalOptionRead,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Description: "Exact label of the desired option",
ConflictsWith: []string{"option_id"},
},
"option_id": {
Type: schema.TypeString,
Optional: true,
Description: "The ID of the option",
ValidateFunc: verify.IsUUIDorUUIDWithLocality(),
ConflictsWith: []string{"name"},
},
"manageable": {
Type: schema.TypeBool,
Computed: true,
Description: "Is false if the option could not be added or removed",
},
"zone": zonal.Schema(),
},
}
}
func dataSourceScalewayBaremetalOptionRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
api, zone, err := baremetalAPIWithZone(d, m)
if err != nil {
return diag.FromErr(err)
}
var optionName string
var optionManageable bool
optionID, ok := d.GetOk("option_id")
if ok {
optionID = d.Get("option_id")
res, err := api.GetOption(&baremetal.GetOptionRequest{
Zone: zone,
OptionID: optionID.(string),
}, scw.WithContext(ctx))
if err != nil {
return diag.FromErr(err)
}
optionManageable = res.Manageable
optionName = res.Name
} else {
res, err := api.ListOptions(&baremetal.ListOptionsRequest{
Zone: zone,
}, scw.WithAllPages(), scw.WithContext(ctx))
if err != nil {
return diag.FromErr(err)
}
if len(res.Options) == 0 {
return diag.FromErr(fmt.Errorf("no option found with the name %s", d.Get("name")))
}
for _, option := range res.Options {
if option.Name == d.Get("name") {
optionID, optionManageable, optionName = option.ID, option.Manageable, option.Name
break
}
}
}
zoneID := datasource.NewZonedID(optionID, zone)
d.SetId(zoneID)
_ = d.Set("option_id", zoneID)
_ = d.Set("zone", zone)
_ = d.Set("name", optionName)
_ = d.Set("manageable", optionManageable)
return nil
}