-
Notifications
You must be signed in to change notification settings - Fork 44
/
data_source_devices.go
103 lines (93 loc) · 2.68 KB
/
data_source_devices.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
91
92
93
94
95
96
97
98
99
100
101
102
103
package tailscale
import (
"context"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/tailscale/tailscale-client-go/tailscale"
)
func dataSourceDevices() *schema.Resource {
return &schema.Resource{
Description: "The devices data source describes a list of devices in a tailnet",
ReadContext: dataSourceDevicesRead,
Schema: map[string]*schema.Schema{
"name_prefix": {
Optional: true,
Type: schema.TypeString,
Description: "Filters the device list to elements whose name has the provided prefix",
},
"devices": {
Computed: true,
Type: schema.TypeList,
Description: "The list of devices in the tailnet",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Description: "The full name of the device (e.g. `hostname.domain.ts.net`)",
Computed: true,
},
"hostname": {
Type: schema.TypeString,
Description: "The short hostname of the device",
Computed: true,
},
"user": {
Type: schema.TypeString,
Description: "The user associated with the device",
Computed: true,
},
"id": {
Type: schema.TypeString,
Description: "The unique identifier of the device",
Computed: true,
},
"addresses": {
Computed: true,
Type: schema.TypeList,
Description: "The list of device's IPs",
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"tags": {
Type: schema.TypeSet,
Description: "The tags applied to the device",
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
},
}
}
func dataSourceDevicesRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
client := m.(*tailscale.Client)
devices, err := client.Devices(ctx)
if err != nil {
return diagnosticsError(err, "Failed to fetch devices")
}
namePrefix, _ := d.Get("name_prefix").(string)
deviceMaps := make([]map[string]interface{}, 0)
for _, device := range devices {
if namePrefix != "" && !strings.HasPrefix(device.Name, namePrefix) {
continue
}
deviceMaps = append(deviceMaps, map[string]interface{}{
"addresses": device.Addresses,
"name": device.Name,
"hostname": device.Hostname,
"user": device.User,
"id": device.ID,
"tags": device.Tags,
})
}
if err = d.Set("devices", deviceMaps); err != nil {
return diag.FromErr(err)
}
d.SetId(createUUID())
return nil
}