forked from DavidKrau/terraform-provider-simplemdm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassignment_group_helpers.go
More file actions
447 lines (373 loc) · 14.7 KB
/
assignment_group_helpers.go
File metadata and controls
447 lines (373 loc) · 14.7 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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
package provider
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"github.com/DavidKrau/simplemdm-go-client"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type assignmentGroupResponse struct {
Data struct {
ID int `json:"id"`
Type string `json:"type"`
Attributes assignmentGroupAttributes `json:"attributes"`
Relationships assignmentGroupRelationships `json:"relationships"`
} `json:"data"`
}
type assignmentGroupAttributes struct {
Name string `json:"name"`
AutoDeploy bool `json:"auto_deploy"`
GroupType string `json:"group_type"`
InstallType string `json:"install_type"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
DeviceCount int `json:"device_count"`
GroupCount int `json:"group_count"`
Priority *int `json:"priority,omitempty"`
AppTrackLocation *bool `json:"app_track_location,omitempty"`
}
type assignmentGroupRelationships struct {
Apps assignmentGroupRelationshipItems `json:"apps"`
Profiles assignmentGroupRelationshipItems `json:"profiles"`
Devices assignmentGroupRelationshipItems `json:"devices"`
DeviceGroups assignmentGroupRelationshipItems `json:"device_groups"`
}
type assignmentGroupRelationshipItems struct {
Data []assignmentGroupRelationshipItem `json:"data"`
}
type assignmentGroupRelationshipItem struct {
ID int `json:"id"`
Type string `json:"type"`
}
func fetchAssignmentGroup(ctx context.Context, client *simplemdm.Client, id string) (*assignmentGroupResponse, error) {
url := fmt.Sprintf("https://%s/api/v1/assignment_groups/%s", client.HostName, id)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
body, err := client.RequestResponse200(req)
if err != nil {
return nil, err
}
var assignmentGroup assignmentGroupResponse
if err := json.Unmarshal(body, &assignmentGroup); err != nil {
return nil, err
}
return &assignmentGroup, nil
}
func buildStringSetFromRelationshipItems(items []assignmentGroupRelationshipItem) types.Set {
// Return empty set instead of null for Optional+Computed attributes
// This prevents "was X but now null" errors when API doesn't return relationships
values := make([]attr.Value, 0, len(items))
for _, item := range items {
values = append(values, types.StringValue(strconv.Itoa(item.ID)))
}
return types.SetValueMust(types.StringType, values)
}
type assignmentGroupUpsertRequest struct {
Name string
AutoDeploy *bool
GroupType *string
InstallType *string
Priority *int64
AppTrackLocation *bool
}
func createAssignmentGroup(ctx context.Context, client *simplemdm.Client, payload assignmentGroupUpsertRequest) (*assignmentGroupResponse, error) {
url := fmt.Sprintf("https://%s/api/v1/assignment_groups", client.HostName)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil)
if err != nil {
return nil, err
}
req.URL.RawQuery = buildAssignmentGroupQuery(payload, true).Encode()
body, err := client.RequestResponse201(req)
if err != nil {
return nil, err
}
var assignmentGroup assignmentGroupResponse
if err := json.Unmarshal(body, &assignmentGroup); err != nil {
return nil, err
}
return &assignmentGroup, nil
}
func updateAssignmentGroup(ctx context.Context, client *simplemdm.Client, id string, payload assignmentGroupUpsertRequest) error {
url := fmt.Sprintf("https://%s/api/v1/assignment_groups/%s", client.HostName, id)
req, err := http.NewRequestWithContext(ctx, http.MethodPatch, url, nil)
if err != nil {
return err
}
req.URL.RawQuery = buildAssignmentGroupQuery(payload, false).Encode()
_, err = client.RequestResponse204(req)
return err
}
// buildAssignmentGroupQuery constructs the query parameters shared by the create and update operations.
// When includeName is true the "name" parameter is always sent, mirroring the API requirement for creation requests.
// For updates, the name is only provided when it has a non-empty value so partial updates remain possible.
func buildAssignmentGroupQuery(payload assignmentGroupUpsertRequest, includeName bool) url.Values {
values := url.Values{}
if includeName || payload.Name != "" {
values.Set("name", payload.Name)
}
setOptionalBool(values, "auto_deploy", payload.AutoDeploy)
setOptionalString(values, "type", payload.GroupType)
setOptionalString(values, "install_type", payload.InstallType)
if payload.Priority != nil {
values.Set("priority", strconv.FormatInt(*payload.Priority, 10))
}
setOptionalBool(values, "app_track_location", payload.AppTrackLocation)
return values
}
// setOptionalBool adds the given key to the query values when the pointer contains a value.
func setOptionalBool(values url.Values, key string, value *bool) {
if value != nil {
values.Set(key, strconv.FormatBool(*value))
}
}
// setOptionalString adds the given key to the query values when the pointer contains a non-empty string.
func setOptionalString(values url.Values, key string, value *string) {
if value != nil && *value != "" {
values.Set(key, *value)
}
}
func assignmentGroupAssignDevice(ctx context.Context, client *simplemdm.Client, groupID string, deviceID string, removeOthers bool) error {
url := fmt.Sprintf("https://%s/api/v1/assignment_groups/%s/devices/%s", client.HostName, groupID, deviceID)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil)
if err != nil {
return err
}
if removeOthers {
q := req.URL.Query()
q.Add("remove_others", "true")
req.URL.RawQuery = q.Encode()
}
_, err = client.RequestResponse204(req)
return err
}
func applyAssignmentGroupResponseToResourceModel(model *assignment_groupResourceModel, response *assignmentGroupResponse) {
model.ID = types.StringValue(strconv.Itoa(response.Data.ID))
model.Apps = buildStringSetFromRelationshipItems(response.Data.Relationships.Apps.Data)
model.Groups = buildStringSetFromRelationshipItems(response.Data.Relationships.DeviceGroups.Data)
model.Devices = buildStringSetFromRelationshipItems(response.Data.Relationships.Devices.Data)
model.Profiles = buildStringSetFromRelationshipItems(response.Data.Relationships.Profiles.Data)
model.Name = types.StringValue(response.Data.Attributes.Name)
model.AutoDeploy = types.BoolValue(response.Data.Attributes.AutoDeploy)
// Preserve existing group_type value if present (deprecated field)
// The API may return different values (e.g., "static") for accounts using New Groups Experience
// but we want to maintain the user's configured value ("standard" or "munki") to avoid drift
if model.GroupType.IsNull() || model.GroupType.IsUnknown() {
model.GroupType = types.StringValue(response.Data.Attributes.GroupType)
}
// Otherwise keep the existing model.GroupType value
// install_type is only returned by API for munki groups
// For standard groups, set to null since API doesn't return it
if response.Data.Attributes.GroupType == "munki" {
if response.Data.Attributes.InstallType != "" {
model.InstallType = types.StringValue(response.Data.Attributes.InstallType)
} else {
model.InstallType = types.StringNull()
}
} else {
// For standard groups, always set to null
model.InstallType = types.StringNull()
}
if response.Data.Attributes.Priority != nil {
model.Priority = types.Int64Value(int64(*response.Data.Attributes.Priority))
} else {
model.Priority = types.Int64Null()
}
if response.Data.Attributes.AppTrackLocation != nil {
model.AppTrackLocation = types.BoolValue(*response.Data.Attributes.AppTrackLocation)
} else {
model.AppTrackLocation = types.BoolNull()
}
// Always set CreatedAt and UpdatedAt for resources too
model.CreatedAt = types.StringValue(response.Data.Attributes.CreatedAt)
model.UpdatedAt = types.StringValue(response.Data.Attributes.UpdatedAt)
model.DeviceCount = types.Int64Value(int64(response.Data.Attributes.DeviceCount))
model.GroupCount = types.Int64Value(int64(response.Data.Attributes.GroupCount))
}
func applyAssignmentGroupResponseToDataSourceModel(model *assignmentGroupDataSourceModel, response *assignmentGroupResponse) {
model.ID = types.StringValue(strconv.Itoa(response.Data.ID))
model.Name = types.StringValue(response.Data.Attributes.Name)
model.AutoDeploy = types.BoolValue(response.Data.Attributes.AutoDeploy)
model.GroupType = types.StringValue(response.Data.Attributes.GroupType)
if response.Data.Attributes.GroupType == "munki" && response.Data.Attributes.InstallType != "" {
model.InstallType = types.StringValue(response.Data.Attributes.InstallType)
} else {
model.InstallType = types.StringNull()
}
if response.Data.Attributes.Priority != nil {
model.Priority = types.Int64Value(int64(*response.Data.Attributes.Priority))
} else {
model.Priority = types.Int64Null()
}
if response.Data.Attributes.AppTrackLocation != nil {
model.AppTrackLocation = types.BoolValue(*response.Data.Attributes.AppTrackLocation)
} else {
model.AppTrackLocation = types.BoolNull()
}
// Always set CreatedAt and UpdatedAt, even if empty
// This ensures Computed fields in data sources are considered "set"
model.CreatedAt = types.StringValue(response.Data.Attributes.CreatedAt)
model.UpdatedAt = types.StringValue(response.Data.Attributes.UpdatedAt)
model.Apps = buildStringSetFromRelationshipItems(response.Data.Relationships.Apps.Data)
model.Groups = buildStringSetFromRelationshipItems(response.Data.Relationships.DeviceGroups.Data)
model.Devices = buildStringSetFromRelationshipItems(response.Data.Relationships.Devices.Data)
model.Profiles = buildStringSetFromRelationshipItems(response.Data.Relationships.Profiles.Data)
model.DeviceCount = types.Int64Value(int64(response.Data.Attributes.DeviceCount))
model.GroupCount = types.Int64Value(int64(response.Data.Attributes.GroupCount))
}
// setElementsToStringSlice converts a types.Set to a []string slice
func setElementsToStringSlice(set types.Set) []string {
if set.IsNull() || set.IsUnknown() {
return []string{}
}
elements := set.Elements()
result := make([]string, 0, len(elements))
for _, element := range elements {
stringElement, ok := element.(types.String)
if !ok || stringElement.IsNull() || stringElement.IsUnknown() {
continue
}
result = append(result, stringElement.ValueString())
}
return result
}
// assignObjectsToGroup assigns multiple objects to an assignment group
// Used during Create operations to assign apps, profiles, groups, or devices
func assignObjectsToGroup(
ctx context.Context,
client *simplemdm.Client,
groupID string,
objects types.Set,
objectType string,
removeOthers bool,
) error {
if objects.IsNull() || objects.IsUnknown() {
return nil
}
for _, objectID := range objects.Elements() {
// Check for context cancellation
if err := ctx.Err(); err != nil {
return fmt.Errorf("operation cancelled: %w", err)
}
idString := objectID.(types.String).ValueString()
var err error
if objectType == "devices" {
// Devices use special assignment function with removeOthers parameter
err = assignmentGroupAssignDevice(ctx, client, groupID, idString, removeOthers)
} else {
// Apps, profiles, and device_groups use standard assignment
err = client.AssignmentGroupAssignObject(groupID, idString, objectType)
}
if err != nil {
return err
}
}
return nil
}
// updateAssignmentGroupObjects updates assignments by computing diff and applying changes
// Used during Update operations to sync state with plan
func updateAssignmentGroupObjects(
ctx context.Context,
client *simplemdm.Client,
groupID string,
stateObjects types.Set,
planObjects types.Set,
objectType string,
removeOthers bool,
) error {
// When the plan set is null or unknown, Terraform cannot determine a desired
// target state for the relationship. In these cases we must leave the
// existing assignments untouched and bail out early regardless of what the
// current state contains.
if planObjects.IsNull() || planObjects.IsUnknown() {
return nil
}
if stateObjects.IsNull() || stateObjects.IsUnknown() {
stateObjects = types.SetNull(types.StringType)
}
// Convert sets to string slices
stateSlice := setElementsToStringSlice(stateObjects)
planSlice := setElementsToStringSlice(planObjects)
// Compute diff
toAdd, toRemove := diffFunction(stateSlice, planSlice)
// Add new objects
for _, objectID := range toAdd {
// Check for context cancellation
if err := ctx.Err(); err != nil {
return fmt.Errorf("operation cancelled: %w", err)
}
var err error
if objectType == "devices" {
err = assignmentGroupAssignDevice(ctx, client, groupID, objectID, removeOthers)
} else {
err = client.AssignmentGroupAssignObject(groupID, objectID, objectType)
}
if err != nil {
return err
}
}
// Remove old objects
for _, objectID := range toRemove {
// Check for context cancellation
if err := ctx.Err(); err != nil {
return fmt.Errorf("operation cancelled: %w", err)
}
err := client.AssignmentGroupUnAssignObject(groupID, objectID, objectType)
if err != nil {
return err
}
}
return nil
}
// diffFunction computes the difference between state and plan lists
// Returns items to add and items to remove
// Optimized to O(n) complexity using map lookups instead of nested loops
func diffFunction(state []string, plan []string) (add []string, remove []string) {
// Create map of state items for O(1) lookups
stateMap := make(map[string]bool, len(state))
for _, s := range state {
stateMap[s] = true
}
// Create map of plan items and identify additions
planMap := make(map[string]bool, len(plan))
for _, p := range plan {
planMap[p] = true
if !stateMap[p] {
add = append(add, p)
}
}
// Identify removals
for _, s := range state {
if !planMap[s] {
remove = append(remove, s)
}
}
return add, remove
}
// preservePlannedRelationships handles eventual consistency by preserving planned values
// when the API doesn't immediately return assigned relationships
func preservePlannedRelationships(
model *assignment_groupResourceModel,
plannedApps, plannedProfiles, plannedGroups, plannedDevices types.Set,
apiReturnedApps, apiReturnedProfiles, apiReturnedGroups, apiReturnedDevices bool,
) {
// Restore planned relationship values if they were set but API returned empty
// This prevents "planned X but got Y" errors due to API eventual consistency
if !plannedApps.IsNull() && !plannedApps.IsUnknown() && !apiReturnedApps {
model.Apps = plannedApps
}
if !plannedProfiles.IsNull() && !plannedProfiles.IsUnknown() && !apiReturnedProfiles {
model.Profiles = plannedProfiles
}
if !plannedGroups.IsNull() && !plannedGroups.IsUnknown() && !apiReturnedGroups {
model.Groups = plannedGroups
}
if !plannedDevices.IsNull() && !plannedDevices.IsUnknown() && !apiReturnedDevices {
model.Devices = plannedDevices
}
}