forked from DavidKrau/terraform-provider-simplemdm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeviceGroup_resource.go
More file actions
450 lines (389 loc) · 14.9 KB
/
deviceGroup_resource.go
File metadata and controls
450 lines (389 loc) · 14.9 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
448
449
450
package provider
import (
"context"
"fmt"
"strconv"
"github.com/DavidKrau/simplemdm-go-client"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag"
"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"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &deviceGroupResource{}
_ resource.ResourceWithConfigure = &deviceGroupResource{}
_ resource.ResourceWithImportState = &deviceGroupResource{}
)
// deviceGroupResourceModel maps the resource schema data.
type deviceGroupResourceModel struct {
Name types.String `tfsdk:"name"`
ID types.String `tfsdk:"id"`
Attributes types.Map `tfsdk:"attributes"`
Profiles types.Set `tfsdk:"profiles"`
CustomProfiles types.Set `tfsdk:"customprofiles"`
CloneFrom types.String `tfsdk:"clone_from"`
}
// deviceGroupResource is a helper function to simplify the provider implementation.
func DeviceGroupResource() resource.Resource {
return &deviceGroupResource{}
}
// deviceGroupResource is the resource implementation.
type deviceGroupResource struct {
client *simplemdm.Client
}
// Configure adds the provider configured client to the resource.
func (r *deviceGroupResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
r.client = req.ProviderData.(*simplemdm.Client)
}
// Metadata returns the resource type name.
func (r *deviceGroupResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_devicegroup"
}
// Schema defines the schema for the resource.
func (r *deviceGroupResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "⚠️ DEPRECATED: Device Groups have been superseded by Assignment Groups in SimpleMDM. " +
"Please use the simplemdm_assignmentgroup resource instead. " +
"This resource is maintained for backward compatibility only. " +
"Device Group resource can be used to manage Device Group. Can be used together with Custom Profile(s), Attribute(s), Assignment Group(s) or Device Group(s) and set addition details regarding Device Group.",
DeprecationMessage: "Device Groups are deprecated. Use simplemdm_assignmentgroup instead.",
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Required: true,
Optional: false,
Description: "Required. The name of the device group.",
},
"id": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Description: "ID of a Device Group in SimpleMDM",
},
"profiles": schema.SetAttribute{
ElementType: types.StringType,
Optional: true,
Description: "Optional. List of Configuration Profiles assigned to this Device Group",
},
"customprofiles": schema.SetAttribute{
ElementType: types.StringType,
Optional: true,
Description: "Optional. List of Custom Configuration Profiles assigned to this Device Group",
},
"clone_from": schema.StringAttribute{
Optional: true,
Description: "Optional. Clone configuration from an existing legacy device group. Changing this value forces a new device group to be created.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"attributes": schema.MapAttribute{
ElementType: types.StringType,
Optional: true,
Description: "Optional. Map of Custom Configuration Profiles and values set for this Device Group",
},
},
}
}
func (r *deviceGroupResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
// Retrieve import ID and save to state
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
// Create a new resource
func (r *deviceGroupResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
//Retrieve values from plan
var plan deviceGroupResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Device groups cannot be created via API - they are legacy read-only resources
resp.Diagnostics.AddError(
"Device Group Creation Not Supported",
"Device Groups are deprecated in SimpleMDM and cannot be created via the API. "+
"Legacy device groups are read-only through this resource. "+
"Please use simplemdm_assignmentgroup for new group functionality.",
)
}
func (r *deviceGroupResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
// Get current state
var state deviceGroupResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Get device group value from SimpleMDM
devicegroup, err := r.client.DeviceGroupGet(state.ID.ValueString())
if err != nil {
if isNotFoundError(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError(
"Error Reading SimpleMDM device group",
"Could not read SimpleMDM device group "+state.ID.ValueString()+": "+err.Error(),
)
return
}
//load attributes for given group
attributes, err := r.client.AttributeGetAttributesForDeviceGroup(state.ID.ValueString())
if err != nil {
resp.Diagnostics.AddError(
"Error Reading SimpleMDM device group attributes",
"Could not read SimpleMDM device group attributes"+state.ID.ValueString()+": "+err.Error(),
)
return
}
//adding attributes to the map
attributePresent := false
attributesElements := map[string]attr.Value{}
for _, attribute := range attributes.Data {
if attribute.Attributes.Source == "group" {
attributesElements[attribute.ID] = types.StringValue(attribute.Attributes.Value)
attributePresent = true
}
}
if attributePresent {
attributesSetValue, _ := types.MapValue(types.StringType, attributesElements)
state.Attributes = attributesSetValue
} else {
attributesSetValue := types.MapNull(types.StringType)
state.Attributes = attributesSetValue
}
// Overwrite items with refreshed state
state.Name = types.StringValue(devicegroup.Data.Attributes.Name)
// Load all profiles in SimpleMDM
profiles, err := r.client.ProfileGetAll()
if err != nil {
resp.Diagnostics.AddError(
"Error Reading SimpleMDM profiles",
"Could not read SimpleMDM profiles: "+err.Error(),
)
return
}
// //read all profiles and put them to slice
profilesPresent := false
profilesElements := []attr.Value{}
customProfilesPresent := false
customProfilesElements := []attr.Value{}
for _, profile := range profiles.Data { //<<edit here
for _, group := range profile.Relationships.DeviceGroups.Data {
if strconv.Itoa(group.ID) == state.ID.ValueString() {
if profile.Type == "custom_configuration_profile" {
customProfilesElements = append(customProfilesElements, types.StringValue(strconv.Itoa(profile.ID)))
customProfilesPresent = true
} else {
profilesElements = append(profilesElements, types.StringValue(strconv.Itoa(profile.ID)))
profilesPresent = true
}
}
}
}
//if there are profile or custom profiles return them to state
if profilesPresent {
profilesSetValue, _ := types.SetValue(types.StringType, profilesElements)
state.Profiles = profilesSetValue
} else {
profilesSetValue := types.SetNull(types.StringType)
state.Profiles = profilesSetValue
}
if customProfilesPresent {
customProfilesSetValue, _ := types.SetValue(types.StringType, customProfilesElements)
state.CustomProfiles = customProfilesSetValue
} else {
customProfilesSetValue := types.SetNull(types.StringType)
state.CustomProfiles = customProfilesSetValue
}
// Set refreshed state
diags = resp.State.Set(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
func (r *deviceGroupResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
//Retrieve values from plan
var plan, state deviceGroupResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
// Device groups are read-only legacy resources - name changes not supported
if plan.Name.ValueString() != state.Name.ValueString() {
resp.Diagnostics.AddError(
"Device Group Updates Not Supported",
"Device Groups are deprecated and read-only. Name changes are not supported via the API. "+
"Please use simplemdm_assignmentgroup for mutable group functionality.",
)
return
}
// Add deprecation warnings before performing operations
if !plan.Attributes.Equal(state.Attributes) && !plan.Attributes.IsNull() {
resp.Diagnostics.AddWarning(
"Using Deprecated Custom Attribute Management",
"Custom attribute management for device groups is deprecated. "+
"Consider migrating to simplemdm_assignmentgroup resource for attribute management.",
)
}
r.reconcileAttributes(ctx, plan.ID.ValueString(), state.Attributes, plan.Attributes, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
if !plan.Profiles.Equal(state.Profiles) && !plan.Profiles.IsNull() {
resp.Diagnostics.AddWarning(
"Using Deprecated Profile Assignment",
"Profile assignment to device groups is deprecated. "+
"Consider migrating to simplemdm_assignmentgroup resource for profile management.",
)
}
r.reconcileProfiles(ctx, plan.ID.ValueString(), state.Profiles, plan.Profiles, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
if !plan.CustomProfiles.Equal(state.CustomProfiles) && !plan.CustomProfiles.IsNull() {
resp.Diagnostics.AddWarning(
"Using Deprecated Custom Profile Assignment",
"Custom profile assignment to device groups is deprecated. "+
"Consider migrating to simplemdm_assignmentgroup resource for profile management.",
)
}
r.reconcileCustomProfiles(ctx, plan.ID.ValueString(), state.CustomProfiles, plan.CustomProfiles, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
diags = resp.State.Set(ctx, plan)
resp.Diagnostics.Append(diags...)
}
func (r *deviceGroupResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state deviceGroupResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Device groups are legacy read-only resources and cannot be deleted via API
resp.Diagnostics.AddWarning(
"Device Group Deletion Not Supported",
"Device Groups are deprecated and cannot be deleted via the API. "+
"The resource will be removed from Terraform state only. "+
"Please manage device group lifecycle through the SimpleMDM web interface.",
)
// Resource is removed from state automatically after this function returns
}
func (r *deviceGroupResource) reconcileAttributes(ctx context.Context, groupID string, oldAttributes, newAttributes types.Map, diags *diag.Diagnostics) {
_ = ctx
if diags.HasError() {
return
}
planElements := map[string]attr.Value{}
stateElements := map[string]attr.Value{}
if !newAttributes.IsNull() && !newAttributes.IsUnknown() {
planElements = newAttributes.Elements()
}
if !oldAttributes.IsNull() && !oldAttributes.IsUnknown() {
stateElements = oldAttributes.Elements()
}
for planAttribute, planValue := range planElements {
trimmed := planValue.(types.String).ValueString()
if stateValue, ok := stateElements[planAttribute]; ok {
if planValue.Equal(stateValue) {
continue
}
}
if err := r.client.AttributeSetAttributeForDeviceGroup(groupID, planAttribute, trimmed); err != nil {
diags.AddError(
"Error updating SimpleMDM device group attribute",
fmt.Sprintf("Could not update attribute %q on device group %s: %s", planAttribute, groupID, err.Error()),
)
return
}
}
for stateAttribute := range stateElements {
if _, ok := planElements[stateAttribute]; ok {
continue
}
if err := r.client.AttributeSetAttributeForDeviceGroup(groupID, stateAttribute, ""); err != nil {
diags.AddError(
"Error clearing SimpleMDM device group attribute",
fmt.Sprintf("Could not clear attribute %q on device group %s: %s", stateAttribute, groupID, err.Error()),
)
return
}
}
}
func (r *deviceGroupResource) reconcileProfiles(ctx context.Context, groupID string, oldProfiles, newProfiles types.Set, diags *diag.Diagnostics) {
_ = ctx
if diags.HasError() {
return
}
stateProfiles := extractStringSet(oldProfiles)
planProfiles := extractStringSet(newProfiles)
profilesToAdd, profilesToRemove := diffFunction(stateProfiles, planProfiles)
for _, profileID := range profilesToAdd {
if err := r.client.ProfileAssignToGroup(profileID, groupID); err != nil {
diags.AddError(
"Error assigning profile to device group",
fmt.Sprintf("Could not assign profile %s to device group %s: %s", profileID, groupID, err.Error()),
)
return
}
}
for _, profileID := range profilesToRemove {
if err := r.client.ProfileUnAssignToGroup(profileID, groupID); err != nil {
diags.AddError(
"Error unassigning profile from device group",
fmt.Sprintf("Could not unassign profile %s from device group %s: %s", profileID, groupID, err.Error()),
)
return
}
}
}
func (r *deviceGroupResource) reconcileCustomProfiles(ctx context.Context, groupID string, oldProfiles, newProfiles types.Set, diags *diag.Diagnostics) {
_ = ctx
if diags.HasError() {
return
}
stateProfiles := extractStringSet(oldProfiles)
planProfiles := extractStringSet(newProfiles)
profilesToAdd, profilesToRemove := diffFunction(stateProfiles, planProfiles)
for _, profileID := range profilesToAdd {
if err := r.client.CustomProfileAssignToDeviceGroup(profileID, groupID); err != nil {
diags.AddError(
"Error assigning custom profile to device group",
fmt.Sprintf("Could not assign custom profile %s to device group %s: %s", profileID, groupID, err.Error()),
)
return
}
}
for _, profileID := range profilesToRemove {
if err := r.client.CustomProfileUnassignFromDeviceGroup(profileID, groupID); err != nil {
diags.AddError(
"Error unassigning custom profile from device group",
fmt.Sprintf("Could not unassign custom profile %s from device group %s: %s", profileID, groupID, err.Error()),
)
return
}
}
}
func extractStringSet(set types.Set) []string {
if set.IsNull() || set.IsUnknown() {
return []string{}
}
values := []string{}
for _, value := range set.Elements() {
values = append(values, value.(types.String).ValueString())
}
return values
}