/
data_source_registry_namespace.go
72 lines (59 loc) · 2.13 KB
/
data_source_registry_namespace.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 scaleway
import (
"context"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/scaleway/scaleway-sdk-go/api/registry/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/types"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/verify"
)
func DataSourceScalewayRegistryNamespace() *schema.Resource {
// Generate datasource schema from resource
dsSchema := datasource.SchemaFromResourceSchema(ResourceScalewayRegistryNamespace().Schema)
datasource.AddOptionalFieldsToSchema(dsSchema, "name", "region", "project_id")
dsSchema["name"].ConflictsWith = []string{"namespace_id"}
dsSchema["namespace_id"] = &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "The ID of the registry namespace",
ValidateFunc: verify.IsUUIDorUUIDWithLocality(),
ConflictsWith: []string{"name"},
}
return &schema.Resource{
ReadContext: dataSourceScalewayRegistryNamespaceRead,
Schema: dsSchema,
}
}
func dataSourceScalewayRegistryNamespaceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
api, region, err := registryAPIWithRegion(d, m)
if err != nil {
return diag.FromErr(err)
}
namespaceID, ok := d.GetOk("namespace_id")
if !ok {
namespaceName := d.Get("name").(string)
res, err := api.ListNamespaces(®istry.ListNamespacesRequest{
Region: region,
Name: types.ExpandStringPtr(namespaceName),
ProjectID: types.ExpandStringPtr(d.Get("project_id")),
}, scw.WithContext(ctx))
if err != nil {
return diag.FromErr(err)
}
foundNamespace, err := findExact(
res.Namespaces,
func(s *registry.Namespace) bool { return s.Name == namespaceName },
namespaceName,
)
if err != nil {
return diag.FromErr(err)
}
namespaceID = foundNamespace.ID
}
regionalID := datasource.NewRegionalID(namespaceID, region)
d.SetId(regionalID)
_ = d.Set("namespace_id", regionalID)
return resourceScalewayRegistryNamespaceRead(ctx, d, m)
}