|
| 1 | +package scaleway |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" |
| 8 | + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" |
| 9 | + function "github.com/scaleway/scaleway-sdk-go/api/function/v1beta1" |
| 10 | + "github.com/scaleway/scaleway-sdk-go/scw" |
| 11 | +) |
| 12 | + |
| 13 | +func dataSourceScalewayFunctionNamespace() *schema.Resource { |
| 14 | + // Generate datasource schema from resource |
| 15 | + dsSchema := datasourceSchemaFromResourceSchema(resourceScalewayFunctionNamespace().Schema) |
| 16 | + |
| 17 | + addOptionalFieldsToSchema(dsSchema, "name", "region") |
| 18 | + |
| 19 | + dsSchema["name"].ConflictsWith = []string{"namespace_id"} |
| 20 | + dsSchema["namespace_id"] = &schema.Schema{ |
| 21 | + Type: schema.TypeString, |
| 22 | + Optional: true, |
| 23 | + Description: "The ID of the function namespace", |
| 24 | + ValidateFunc: validationUUIDorUUIDWithLocality(), |
| 25 | + ConflictsWith: []string{"name"}, |
| 26 | + } |
| 27 | + |
| 28 | + return &schema.Resource{ |
| 29 | + ReadContext: dataSourceScalewayFunctionNamespaceRead, |
| 30 | + Schema: dsSchema, |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +func dataSourceScalewayFunctionNamespaceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { |
| 35 | + api, region, err := functionAPIWithRegion(d, meta) |
| 36 | + if err != nil { |
| 37 | + return diag.FromErr(err) |
| 38 | + } |
| 39 | + |
| 40 | + namespaceID, ok := d.GetOk("namespace_id") |
| 41 | + if !ok { |
| 42 | + res, err := api.ListNamespaces(&function.ListNamespacesRequest{ |
| 43 | + Region: region, |
| 44 | + Name: expandStringPtr(d.Get("name")), |
| 45 | + }, scw.WithContext(ctx)) |
| 46 | + if err != nil { |
| 47 | + return diag.FromErr(err) |
| 48 | + } |
| 49 | + if len(res.Namespaces) == 0 { |
| 50 | + return diag.FromErr(fmt.Errorf("no function namespaces found with the name %s", d.Get("name"))) |
| 51 | + } |
| 52 | + if len(res.Namespaces) > 1 { |
| 53 | + return diag.FromErr(fmt.Errorf("%d function namespaces found with the same name %s", len(res.Namespaces), d.Get("name"))) |
| 54 | + } |
| 55 | + namespaceID = res.Namespaces[0].ID |
| 56 | + } |
| 57 | + |
| 58 | + regionalID := datasourceNewRegionalizedID(namespaceID, region) |
| 59 | + d.SetId(regionalID) |
| 60 | + _ = d.Set("namespace_id", regionalID) |
| 61 | + |
| 62 | + return resourceScalewayFunctionNamespaceRead(ctx, d, meta) |
| 63 | +} |
0 commit comments