|
| 1 | +package scaleway |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" |
| 7 | + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" |
| 8 | + "github.com/scaleway/scaleway-sdk-go/api/iot/v1" |
| 9 | +) |
| 10 | + |
| 11 | +func dataSourceScalewayIotDevice() *schema.Resource { |
| 12 | + dsSchema := datasourceSchemaFromResourceSchema(resourceScalewayIotDevice().Schema) |
| 13 | + |
| 14 | + addOptionalFieldsToSchema(dsSchema, "name", "region") |
| 15 | + |
| 16 | + dsSchema["name"].ConflictsWith = []string{"device_id"} |
| 17 | + dsSchema["hub_id"].Optional = true |
| 18 | + dsSchema["device_id"] = &schema.Schema{ |
| 19 | + Type: schema.TypeString, |
| 20 | + Optional: true, |
| 21 | + Description: "The ID of the IOT Device", |
| 22 | + ConflictsWith: []string{"name"}, |
| 23 | + ValidateFunc: validationUUIDorUUIDWithLocality(), |
| 24 | + } |
| 25 | + |
| 26 | + return &schema.Resource{ |
| 27 | + ReadContext: dataSourceScalewayIotDeviceRead, |
| 28 | + Schema: dsSchema, |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +func dataSourceScalewayIotDeviceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { |
| 33 | + api, region, err := iotAPIWithRegion(d, meta) |
| 34 | + if err != nil { |
| 35 | + return diag.FromErr(err) |
| 36 | + } |
| 37 | + |
| 38 | + deviceID, ok := d.GetOk("device_id") |
| 39 | + if !ok { |
| 40 | + hubID, hubIDExists := d.GetOk("hub_id") |
| 41 | + if hubIDExists { |
| 42 | + _, hubID, err = parseRegionalID(hubID.(string)) |
| 43 | + if err != nil { |
| 44 | + return diag.FromErr(err) |
| 45 | + } |
| 46 | + } |
| 47 | + res, err := api.ListDevices(&iot.ListDevicesRequest{ |
| 48 | + Region: region, |
| 49 | + Name: expandStringPtr(d.Get("name")), |
| 50 | + HubID: expandStringPtr(hubID), |
| 51 | + }) |
| 52 | + if err != nil { |
| 53 | + return diag.FromErr(err) |
| 54 | + } |
| 55 | + for _, device := range res.Devices { |
| 56 | + if device.Name == d.Get("name").(string) { |
| 57 | + if deviceID != "" { |
| 58 | + return diag.Errorf("more than 1 device with the same name %s", d.Get("name")) |
| 59 | + } |
| 60 | + deviceID = device.ID |
| 61 | + } |
| 62 | + } |
| 63 | + if deviceID == "" { |
| 64 | + return diag.Errorf("no device found with the name %s", d.Get("name")) |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + regionalID := datasourceNewRegionalizedID(deviceID, region) |
| 69 | + d.SetId(regionalID) |
| 70 | + err = d.Set("device_id", regionalID) |
| 71 | + if err != nil { |
| 72 | + return diag.FromErr(err) |
| 73 | + } |
| 74 | + diags := resourceScalewayIotDeviceRead(ctx, d, meta) |
| 75 | + if diags != nil { |
| 76 | + return diags |
| 77 | + } |
| 78 | + if d.Id() == "" { |
| 79 | + return diag.Errorf("IOT Device not found (%s)", regionalID) |
| 80 | + } |
| 81 | + return nil |
| 82 | +} |
0 commit comments