-
Notifications
You must be signed in to change notification settings - Fork 123
/
ip_data_source.go
72 lines (63 loc) · 2.1 KB
/
ip_data_source.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
package instance
import (
"context"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/scaleway/scaleway-sdk-go/api/instance/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/httperrors"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/locality"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/locality/zonal"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/verify"
)
func DataSourceIP() *schema.Resource {
// Generate datasource schema from resource
dsSchema := datasource.SchemaFromResourceSchema(ResourceIP().Schema)
dsSchema["id"] = &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "The ID of the IP address",
ValidateFunc: verify.IsUUIDorUUIDWithLocality(),
ConflictsWith: []string{"address"},
}
dsSchema["address"] = &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "The IP address",
ConflictsWith: []string{"id"},
ValidateFunc: validation.IsIPv4Address,
}
return &schema.Resource{
ReadContext: DataSourceInstanceIPRead,
Schema: dsSchema,
}
}
func DataSourceInstanceIPRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
instanceAPI, zone, err := newAPIWithZone(d, m)
if err != nil {
return diag.FromErr(err)
}
id, ok := d.GetOk("id")
var ID string
if !ok {
res, err := instanceAPI.GetIP(&instance.GetIPRequest{
IP: d.Get("address").(string),
Zone: zone,
}, scw.WithContext(ctx))
if err != nil {
// We check for 403 because instance API returns 403 for a deleted IP
if httperrors.Is404(err) || httperrors.Is403(err) {
d.SetId("")
return nil
}
return diag.FromErr(err)
}
ID = res.IP.ID
} else {
_, ID, _ = locality.ParseLocalizedID(id.(string))
}
d.SetId(zonal.NewIDString(zone, ID))
return ResourceInstanceIPRead(ctx, d, m)
}