-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathresource_group.go
462 lines (394 loc) · 14.6 KB
/
resource_group.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
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
451
452
453
454
455
456
457
458
459
460
461
462
package platform
import (
"context"
"net/http"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"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/booldefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/setplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/jfrog/terraform-provider-shared/util"
utilfw "github.com/jfrog/terraform-provider-shared/util/fw"
validatorfw "github.com/jfrog/terraform-provider-shared/validator/fw"
"github.com/samber/lo"
)
var _ resource.Resource = (*groupResource)(nil)
type groupResource struct {
util.JFrogResource
}
func NewGroupResource() resource.Resource {
return &groupResource{
JFrogResource: util.JFrogResource{
TypeName: "platform_group",
ValidArtifactoryVersion: "7.49.3",
CollectionEndpoint: "access/api/v2/groups",
DocumentEndpoint: "access/api/v2/groups/{name}",
},
}
}
var groupSchemaV0 = schema.Schema{
Version: 0,
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Required: true,
Validators: []validator.String{
stringvalidator.LengthBetween(1, 64),
},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
MarkdownDescription: "Name of the group.",
},
"description": schema.StringAttribute{
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
MarkdownDescription: "A description for the group.",
},
"external_id": schema.StringAttribute{
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
MarkdownDescription: "New external group ID used to configure the corresponding group in Azure AD.",
},
"auto_join": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Validators: []validator.Bool{
validatorfw.BoolConflict(true, path.Expressions{
path.MatchRelative().AtParent().AtName("admin_privileges"),
}...),
},
MarkdownDescription: "When this parameter is set, any new users defined in the system are automatically assigned to this group.",
},
"admin_privileges": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
MarkdownDescription: "Any users added to this group will automatically be assigned with admin privileges in the system.",
},
"members": schema.SetAttribute{
ElementType: types.StringType,
Optional: true,
PlanModifiers: []planmodifier.Set{
setplanmodifier.UseStateForUnknown(),
},
MarkdownDescription: "List of users assigned to the group.",
},
"realm": schema.StringAttribute{
Computed: true,
MarkdownDescription: "The realm for the group.",
},
"realm_attributes": schema.StringAttribute{
Computed: true,
MarkdownDescription: "The realm for the group.",
},
},
MarkdownDescription: "Provides a group resource to create and manage groups, and manages membership. A group represents a role and is used with RBAC (Role-Based Access Control) rules. See [JFrog documentation](https://jfrog.com/help/r/jfrog-platform-administration-documentation/create-and-edit-groups) for more details.",
}
var groupSchemaV1 = schema.Schema{
Version: 1,
Attributes: lo.Assign(
groupSchemaV0.Attributes,
map[string]schema.Attribute{
"members": schema.SetAttribute{
ElementType: types.StringType,
Optional: true,
PlanModifiers: []planmodifier.Set{
setplanmodifier.UseStateForUnknown(),
},
MarkdownDescription: "List of users assigned to the group.",
DeprecationMessage: "Replaced by `platform_group_members` resource. This should not be used in combination with `platform_group_members` resource. Use `use_group_members_resource` attribute to control which resource manages group membership.",
},
"use_group_members_resource": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(true),
MarkdownDescription: "When set to `true`, this resource will ignore the `members` attributes and allow memberships to be managed by `platform_group_members` resource instead. Default value is `true`.",
},
},
),
MarkdownDescription: groupSchemaV0.MarkdownDescription,
}
func (r *groupResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = groupSchemaV1
}
type groupResourceModelV0 struct {
Name types.String `tfsdk:"name"`
Description types.String `tfsdk:"description"`
ExternalId types.String `tfsdk:"external_id"`
AutoJoin types.Bool `tfsdk:"auto_join"`
AdminPrivileges types.Bool `tfsdk:"admin_privileges"`
Members types.Set `tfsdk:"members"`
Realm types.String `tfsdk:"realm"`
RealmAttributes types.String `tfsdk:"realm_attributes"`
}
type groupResourceModelV1 struct {
groupResourceModelV0
UseGroupMembersResource types.Bool `tfsdk:"use_group_members_resource"`
}
func (r *groupResourceModelV1) toAPIModel(ctx context.Context, apiModel *groupAPIModel) (ds diag.Diagnostics) {
var members []string
if !r.UseGroupMembersResource.ValueBool() {
ds.Append(r.Members.ElementsAs(ctx, &members, false)...)
if ds.HasError() {
return
}
}
*apiModel = groupAPIModel{
Name: r.Name.ValueString(),
Description: r.Description.ValueStringPointer(),
ExternalId: r.ExternalId.ValueStringPointer(),
AutoJoin: r.AutoJoin.ValueBoolPointer(),
AdminPrivileges: r.AdminPrivileges.ValueBoolPointer(),
Members: members,
}
return nil
}
func (r *groupResourceModelV1) fromAPIModel(ctx context.Context, apiModel groupAPIModel, ignoreMembers bool) diag.Diagnostics {
diags := diag.Diagnostics{}
r.Name = types.StringValue(apiModel.Name)
r.Description = types.StringPointerValue(apiModel.Description)
r.ExternalId = types.StringPointerValue(apiModel.ExternalId)
r.AutoJoin = types.BoolPointerValue(apiModel.AutoJoin)
r.AdminPrivileges = types.BoolPointerValue(apiModel.AdminPrivileges)
r.Realm = types.StringPointerValue(apiModel.Realm)
r.RealmAttributes = types.StringPointerValue(apiModel.RealmAttributes)
if !r.UseGroupMembersResource.ValueBool() {
if r.Members.IsUnknown() {
r.Members = types.SetNull(types.StringType)
}
if !ignoreMembers && len(apiModel.Members) > 0 {
members, d := types.SetValueFrom(ctx, types.StringType, apiModel.Members)
if d != nil {
diags.Append(d...)
return diags
}
r.Members = members
}
}
return diags
}
func (r *groupResource) UpgradeState(ctx context.Context) map[int64]resource.StateUpgrader {
return map[int64]resource.StateUpgrader{
// State upgrade implementation from 0 (prior state version) to 1 (Schema.Version)
0: {
PriorSchema: &groupSchemaV0,
StateUpgrader: func(ctx context.Context, req resource.UpgradeStateRequest, resp *resource.UpgradeStateResponse) {
var priorStateData groupResourceModelV0
resp.Diagnostics.Append(req.State.Get(ctx, &priorStateData)...)
if resp.Diagnostics.HasError() {
return
}
upgradedStateData := groupResourceModelV1{
groupResourceModelV0: priorStateData,
UseGroupMembersResource: types.BoolValue(false),
}
resp.Diagnostics.Append(resp.State.Set(ctx, upgradedStateData)...)
},
},
}
}
type groupAPIModel struct {
Name string `json:"name"`
Description *string `json:"description,omitempty"`
ExternalId *string `json:"external_id,omitempty"`
AutoJoin *bool `json:"auto_join,omitempty"`
AdminPrivileges *bool `json:"admin_privileges,omitempty"`
Members []string `json:"members,omitempty"` // only for create
Realm *string `json:"realm,omitempty"` // read only
RealmAttributes *string `json:"realm_attributes,omitempty"` // read only
}
type groupMembersRequestAPIModel struct {
Add []string `json:"add"`
Remove []string `json:"remove"`
}
type groupMembersResponseAPIModel struct {
Members []string `json:"members"`
}
func (r *groupResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
go util.SendUsageResourceCreate(ctx, r.ProviderData.Client.R(), r.ProviderData.ProductId, r.TypeName)
var plan *groupResourceModelV1
// Read Terraform plan data into the model
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
var group groupAPIModel
resp.Diagnostics.Append(plan.toAPIModel(ctx, &group)...)
if resp.Diagnostics.HasError() {
return
}
var newGroup groupAPIModel
var apiErrs util.JFrogErrors
response, err := r.ProviderData.Client.R().
SetBody(group).
SetResult(&newGroup).
SetError(&apiErrs).
Post(r.JFrogResource.CollectionEndpoint)
if err != nil {
utilfw.UnableToCreateResourceError(resp, err.Error())
return
}
if response.StatusCode() != http.StatusCreated {
utilfw.UnableToCreateResourceError(resp, apiErrs.String())
return
}
plan.Realm = types.StringPointerValue(newGroup.Realm)
plan.RealmAttributes = types.StringPointerValue(newGroup.RealmAttributes)
// Save data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *groupResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
go util.SendUsageResourceRead(ctx, r.ProviderData.Client.R(), r.ProviderData.ProductId, r.TypeName)
var state *groupResourceModelV1
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var group groupAPIModel
var apiErrs util.JFrogErrors
response, err := r.ProviderData.Client.R().
SetPathParam("name", state.Name.ValueString()).
SetResult(&group).
SetError(&apiErrs).
Get(r.JFrogResource.DocumentEndpoint)
if err != nil {
utilfw.UnableToRefreshResourceError(resp, err.Error())
return
}
// Treat HTTP 404 Not Found status as a signal to recreate resource
// and return early
if response.StatusCode() == http.StatusNotFound {
resp.State.RemoveResource(ctx)
return
}
if response.IsError() {
utilfw.UnableToRefreshResourceError(resp, apiErrs.String())
return
}
// Convert from the API data model to the Terraform data model
// and refresh any attribute values.
resp.Diagnostics.Append(state.fromAPIModel(ctx, group, false)...)
if resp.Diagnostics.HasError() {
return
}
// Save updated data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *groupResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
go util.SendUsageResourceUpdate(ctx, r.ProviderData.Client.R(), r.ProviderData.ProductId, r.TypeName)
var plan groupResourceModelV1
var state groupResourceModelV1
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var group groupAPIModel
resp.Diagnostics.Append(plan.toAPIModel(ctx, &group)...)
if resp.Diagnostics.HasError() {
return
}
var updatedGroup groupAPIModel
var apiErrs util.JFrogErrors
response, err := r.ProviderData.Client.R().
SetPathParam("name", plan.Name.ValueString()).
SetBody(group).
SetResult(&updatedGroup).
SetError(&apiErrs).
Patch(r.JFrogResource.DocumentEndpoint)
if err != nil {
utilfw.UnableToUpdateResourceError(resp, err.Error())
return
}
if response.IsError() {
utilfw.UnableToUpdateResourceError(resp, apiErrs.String())
return
}
resp.Diagnostics.Append(plan.fromAPIModel(ctx, updatedGroup, true)...)
if resp.Diagnostics.HasError() {
return
}
var planMembers []string
resp.Diagnostics.Append(plan.Members.ElementsAs(ctx, &planMembers, false)...)
if resp.Diagnostics.HasError() {
return
}
var stateMembers []string
resp.Diagnostics.Append(state.Members.ElementsAs(ctx, &stateMembers, false)...)
if resp.Diagnostics.HasError() {
return
}
memebersToAdd, membersToRemove := lo.Difference(planMembers, stateMembers)
membersReq := groupMembersRequestAPIModel{
Add: memebersToAdd,
Remove: membersToRemove,
}
if len(memebersToAdd) > 0 || len(membersToRemove) > 0 {
var membersRes groupMembersResponseAPIModel
response, err = r.ProviderData.Client.R().
SetPathParam("name", plan.Name.ValueString()).
SetBody(membersReq).
SetResult(&membersRes).
SetError(&apiErrs).
Patch(r.JFrogResource.DocumentEndpoint + "/members")
if err != nil {
utilfw.UnableToUpdateResourceError(resp, err.Error())
return
}
if response.IsError() {
utilfw.UnableToUpdateResourceError(resp, apiErrs.String())
return
}
// only update members attribute if it is set in the configuration
if !plan.Members.IsNull() {
ms, d := types.SetValueFrom(ctx, types.StringType, membersRes.Members)
if d != nil {
resp.Diagnostics.Append(d...)
return
}
plan.Members = ms
}
}
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *groupResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
go util.SendUsageResourceDelete(ctx, r.ProviderData.Client.R(), r.ProviderData.ProductId, r.TypeName)
var state groupResourceModelV1
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
var apiErrs util.JFrogErrors
response, err := r.ProviderData.Client.R().
SetPathParam("name", state.Name.ValueString()).
SetError(&apiErrs).
Delete(r.JFrogResource.DocumentEndpoint)
if err != nil {
utilfw.UnableToDeleteResourceError(resp, err.Error())
return
}
// Return error if the HTTP status code is not 204 No Content or 404 Not Found
if response.StatusCode() != http.StatusNotFound && response.StatusCode() != http.StatusNoContent {
utilfw.UnableToDeleteResourceError(resp, apiErrs.String())
return
}
// If the logic reaches here, it implicitly succeeded and will remove
// the resource from state if there are no other errors.
}
// ImportState imports the resource into the Terraform state.
func (r *groupResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
}