forked from DavidKrau/terraform-provider-simplemdm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustomDeclaration_device_assignment_resource.go
More file actions
258 lines (215 loc) · 8.52 KB
/
customDeclaration_device_assignment_resource.go
File metadata and controls
258 lines (215 loc) · 8.52 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package provider
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/DavidKrau/simplemdm-go-client"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type customDeclarationDeviceAssignmentResource struct {
client *simplemdm.Client
}
type customDeclarationDeviceAssignmentModel struct {
ID types.String `tfsdk:"id"`
CustomDeclarationID types.String `tfsdk:"custom_declaration_id"`
DeviceID types.String `tfsdk:"device_id"`
}
var (
_ resource.Resource = &customDeclarationDeviceAssignmentResource{}
_ resource.ResourceWithConfigure = &customDeclarationDeviceAssignmentResource{}
_ resource.ResourceWithImportState = &customDeclarationDeviceAssignmentResource{}
)
func CustomDeclarationDeviceAssignmentResource() resource.Resource {
return &customDeclarationDeviceAssignmentResource{}
}
func (r *customDeclarationDeviceAssignmentResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_customdeclaration_device_assignment"
}
func (r *customDeclarationDeviceAssignmentResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages the assignment of a custom declaration to a SimpleMDM device.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"custom_declaration_id": schema.StringAttribute{
Required: true,
Description: "Identifier of the custom declaration to assign.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"device_id": schema.StringAttribute{
Required: true,
Description: "Identifier of the device that should receive the custom declaration.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
},
}
}
func (r *customDeclarationDeviceAssignmentResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
r.client = req.ProviderData.(*simplemdm.Client)
}
func (r *customDeclarationDeviceAssignmentResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan customDeclarationDeviceAssignmentModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
url := fmt.Sprintf("https://%s/api/v1/custom_declarations/%s/devices/%s", r.client.HostName, plan.CustomDeclarationID.ValueString(), plan.DeviceID.ValueString())
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil)
if err != nil {
resp.Diagnostics.AddError("Error creating SimpleMDM custom declaration assignment request", err.Error())
return
}
if _, err := r.client.RequestResponse204or409(httpReq); err != nil {
resp.Diagnostics.AddError("Error assigning custom declaration to device", err.Error())
return
}
plan.ID = types.StringValue(buildCustomDeclarationAssignmentID(plan.CustomDeclarationID.ValueString(), plan.DeviceID.ValueString()))
diags = resp.State.Set(ctx, &plan)
resp.Diagnostics.Append(diags...)
}
func (r *customDeclarationDeviceAssignmentResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
resp.Diagnostics.AddError(
"Cannot update custom declaration assignments",
"Updates are not supported. Remove and recreate the assignment to target a different device or declaration.",
)
}
func (r *customDeclarationDeviceAssignmentResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state customDeclarationDeviceAssignmentModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
url := fmt.Sprintf("https://%s/api/v1/devices/%s", r.client.HostName, state.DeviceID.ValueString())
httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
resp.Diagnostics.AddError("Error creating SimpleMDM device request", err.Error())
return
}
body, err := r.client.RequestResponse200(httpReq)
if err != nil {
if strings.Contains(err.Error(), "404") {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Error reading SimpleMDM device assignments", err.Error())
return
}
assigned, err := deviceHasCustomDeclarationAssignment(body, state.CustomDeclarationID.ValueString(), state.DeviceID.ValueString())
if err != nil {
resp.Diagnostics.AddError("Error parsing SimpleMDM device relationships", err.Error())
return
}
if !assigned {
resp.State.RemoveResource(ctx)
return
}
state.ID = types.StringValue(buildCustomDeclarationAssignmentID(state.CustomDeclarationID.ValueString(), state.DeviceID.ValueString()))
diags = resp.State.Set(ctx, &state)
resp.Diagnostics.Append(diags...)
}
func (r *customDeclarationDeviceAssignmentResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state customDeclarationDeviceAssignmentModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
url := fmt.Sprintf("https://%s/api/v1/custom_declarations/%s/devices/%s", r.client.HostName, state.CustomDeclarationID.ValueString(), state.DeviceID.ValueString())
httpReq, err := http.NewRequestWithContext(ctx, http.MethodDelete, url, nil)
if err != nil {
resp.Diagnostics.AddError("Error creating SimpleMDM custom declaration assignment request", err.Error())
return
}
if _, err := r.client.RequestResponse204or409(httpReq); err != nil {
if strings.Contains(err.Error(), "404") {
return
}
resp.Diagnostics.AddError("Error removing custom declaration assignment", err.Error())
}
}
func (r *customDeclarationDeviceAssignmentResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
// Support both : and | as separators for backward compatibility
var parts []string
var declarationID, deviceID string
if strings.Contains(req.ID, "|") {
parts = strings.Split(req.ID, "|")
} else {
parts = strings.Split(req.ID, ":")
}
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
resp.Diagnostics.AddError(
"Unexpected import identifier format",
"Expected custom_declaration_id:device_id or custom_declaration_id|device_id",
)
return
}
declarationID = parts[0]
deviceID = parts[1]
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("custom_declaration_id"), declarationID)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("device_id"), deviceID)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...) //nolint:errcheck
}
func deviceHasCustomDeclarationAssignment(body []byte, customDeclarationID string, deviceID string) (bool, error) {
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
return false, fmt.Errorf("error parsing device payload for device %s: %w", deviceID, err)
}
data, ok := payload["data"].(map[string]any)
if !ok {
return false, fmt.Errorf("unexpected device payload structure for device %s: missing data node", deviceID)
}
relationships, ok := data["relationships"].(map[string]any)
if !ok {
return false, nil
}
rel, ok := relationships["custom_declarations"].(map[string]any)
if !ok {
return false, nil
}
assignments, ok := rel["data"].([]any)
if !ok {
return false, nil
}
for _, entry := range assignments {
relEntry, ok := entry.(map[string]any)
if !ok {
continue
}
idValue, ok := relEntry["id"]
if !ok {
continue
}
if fmt.Sprint(idValue) == customDeclarationID {
return true, nil
}
}
return false, nil
}
func buildCustomDeclarationAssignmentID(customDeclarationID, deviceID string) string {
// Use | separator to avoid conflicts with IDs that contain colons
// This addresses BUG-CD-012
if strings.Contains(customDeclarationID, ":") || strings.Contains(deviceID, ":") {
return fmt.Sprintf("%s|%s", customDeclarationID, deviceID)
}
return fmt.Sprintf("%s:%s", customDeclarationID, deviceID)
}