forked from upbound/terraform-provider-aws
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser.go
More file actions
480 lines (416 loc) · 17.1 KB
/
Copy pathuser.go
File metadata and controls
480 lines (416 loc) · 17.1 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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package mq
import (
"context"
"fmt"
"slices"
"sort"
"strings"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/mq"
awstypes "github.com/aws/aws-sdk-go-v2/service/mq/types"
"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/planmodifier"
"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/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/hashicorp/terraform-provider-aws/internal/create"
"github.com/hashicorp/terraform-provider-aws/internal/errs"
"github.com/hashicorp/terraform-provider-aws/internal/framework"
"github.com/hashicorp/terraform-provider-aws/internal/framework/flex"
fwtypes "github.com/hashicorp/terraform-provider-aws/internal/framework/types"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/names"
)
// diagErrorFramework is a helper method that creates an error diagnostic.
// This method was formerly at internal/create/errors.go
func diagErrorFramework(service, action, resource, id string, gotError error) diag.Diagnostic {
return diag.NewErrorDiagnostic(
create.ProblemStandardMessage(service, action, resource, id, nil),
gotError.Error(),
)
}
// @FrameworkResource("aws_mq_user", name="User")
func newResourceUser(_ context.Context) (resource.ResourceWithConfigure, error) {
return &resourceUser{}, nil
}
const (
ResourceNameUser = "User"
)
type resourceUser struct {
framework.ResourceWithModel[resourceUserData]
}
// Schema returns the schema for this resource.
func (r *resourceUser) Schema(ctx context.Context, request resource.SchemaRequest, response *resource.SchemaResponse) {
response.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
"broker_id": schema.StringAttribute{
Required: true,
Description: "The ID of the broker where the user will be created.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"console_access": schema.BoolAttribute{
Optional: true,
Description: "Whether to enable console access for the user.",
PlanModifiers: []planmodifier.Bool{
&consoleAccessPlanModifier{},
},
},
"groups": schema.ListAttribute{
CustomType: fwtypes.ListOfStringType,
ElementType: types.StringType,
Optional: true,
Description: "List of groups to which the user belongs.",
PlanModifiers: []planmodifier.List{
&listSortModifier{},
&groupsPlanModifier{},
},
},
"id": framework.IDAttribute(),
"password": schema.StringAttribute{
Required: true,
Sensitive: true,
Description: "The password for the user. Must be at least 12 characters long.",
Validators: []validator.String{
stringvalidator.LengthAtLeast(12),
},
},
"replication_user": schema.BoolAttribute{
Optional: true,
Description: "Whether the user is a replication user.",
},
"username": schema.StringAttribute{
Required: true,
Description: "The username for the MQ user.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
},
Blocks: map[string]schema.Block{
// Pending changes information returned by the AWS API. This is a
// computed-only attribute that tracks pending modifications to
// the user.
"pending": schema.SingleNestedBlock{
CustomType: fwtypes.NewObjectTypeOf[pendingModel](ctx),
Description: "Tracks pending modifications returned by the AWS MQ API. This field allows you to monitor changes that are actively being processed before they are fully applied.",
Attributes: map[string]schema.Attribute{
"pending_change": schema.StringAttribute{
Computed: true,
Optional: false,
Description: "The type of pending change. Valid values are CREATE, UPDATE, or DELETE.",
},
"console_access": schema.BoolAttribute{
Computed: true,
Optional: false,
Description: "The pending console access value if a change to console access is being processed.",
},
"groups": schema.ListAttribute{
ElementType: types.StringType,
Computed: true,
Optional: false,
Description: "The pending groups value if a change to groups is being processed.",
PlanModifiers: []planmodifier.List{
&listSortModifier{},
},
},
},
},
},
}
}
func (r *resourceUser) Create(ctx context.Context, request resource.CreateRequest, response *resource.CreateResponse) {
var plan resourceUserData
response.Diagnostics.Append(request.Plan.Get(ctx, &plan)...)
if response.Diagnostics.HasError() {
return
}
conn := r.Meta().MQClient(ctx)
input := &mq.CreateUserInput{
BrokerId: flex.StringFromFramework(ctx, plan.BrokerID),
Password: flex.StringFromFramework(ctx, plan.Password),
Username: flex.StringFromFramework(ctx, plan.Username),
ConsoleAccess: flex.BoolFromFramework(ctx, plan.ConsoleAccess),
Groups: flex.ExpandFrameworkStringValueList(ctx, plan.Groups),
ReplicationUser: flex.BoolFromFramework(ctx, plan.ReplicationUser),
}
_, err := conn.CreateUser(ctx, input)
if err != nil {
response.Diagnostics.Append(diagErrorFramework(names.MQ, create.ErrActionCreating, ResourceNameUser, fmt.Sprintf("%s/%s", plan.BrokerID.ValueString(), plan.Username.ValueString()), err))
return
}
// Create API call returns no data. Get resource details.
userDetails, err := findUserByID(ctx, conn, plan.BrokerID.ValueString(), plan.Username.ValueString())
if err != nil {
response.Diagnostics.Append(diagErrorFramework(names.MQ, create.ErrActionCreating, ResourceNameUser, fmt.Sprintf("%s/%s", plan.BrokerID.ValueString(), plan.Username.ValueString()), err))
return
}
state := plan
response.Diagnostics.Append(state.refreshFromOutput(ctx, userDetails)...)
response.Diagnostics.Append(response.State.Set(ctx, state)...)
}
func (r *resourceUser) Read(ctx context.Context, request resource.ReadRequest, response *resource.ReadResponse) {
var state resourceUserData
response.Diagnostics.Append(request.State.Get(ctx, &state)...)
if response.Diagnostics.HasError() {
return
}
conn := r.Meta().MQClient(ctx)
userDetails, err := findUserByID(ctx, conn, state.BrokerID.ValueString(), state.ID.ValueString())
if tfresource.NotFound(err) {
create.LogNotFoundRemoveState(names.MQ, create.ErrActionReading, ResourceNameUser, fmt.Sprintf("%s/%s", state.BrokerID.ValueString(), state.ID.ValueString()))
response.State.RemoveResource(ctx)
return
}
if err != nil {
response.Diagnostics.Append(diagErrorFramework(names.MQ, create.ErrActionReading, ResourceNameUser, fmt.Sprintf("%s/%s", state.BrokerID.ValueString(), state.ID.ValueString()), err))
return
}
response.Diagnostics.Append(state.refreshFromOutput(ctx, userDetails)...)
response.Diagnostics.Append(response.State.Set(ctx, &state)...)
}
func (r *resourceUser) Update(ctx context.Context, request resource.UpdateRequest, response *resource.UpdateResponse) {
var state, plan resourceUserData
response.Diagnostics.Append(request.State.Get(ctx, &state)...)
if response.Diagnostics.HasError() {
return
}
response.Diagnostics.Append(request.Plan.Get(ctx, &plan)...)
if response.Diagnostics.HasError() {
return
}
if userHasChanges(plan, state) {
conn := r.Meta().MQClient(ctx)
input := &mq.UpdateUserInput{
BrokerId: flex.StringFromFramework(ctx, plan.BrokerID),
Password: flex.StringFromFramework(ctx, plan.Password),
Username: flex.StringFromFramework(ctx, plan.ID),
ConsoleAccess: flex.BoolFromFramework(ctx, plan.ConsoleAccess),
Groups: flex.ExpandFrameworkStringValueList(ctx, plan.Groups),
ReplicationUser: flex.BoolFromFramework(ctx, plan.ReplicationUser),
}
_, err := conn.UpdateUser(ctx, input)
if err != nil {
response.Diagnostics.Append(diagErrorFramework(names.MQ, create.ErrActionUpdating, ResourceNameUser, fmt.Sprintf("%s/%s", state.BrokerID.ValueString(), state.ID.ValueString()), err))
return
}
}
response.Diagnostics.Append(response.State.Set(ctx, &plan)...)
}
func (r *resourceUser) Delete(ctx context.Context, request resource.DeleteRequest, response *resource.DeleteResponse) {
var state resourceUserData
response.Diagnostics.Append(request.State.Get(ctx, &state)...)
if response.Diagnostics.HasError() {
return
}
conn := r.Meta().MQClient(ctx)
input := &mq.DeleteUserInput{
BrokerId: flex.StringFromFramework(ctx, state.BrokerID),
Username: flex.StringFromFramework(ctx, state.ID),
}
_, err := conn.DeleteUser(ctx, input)
if err != nil {
response.Diagnostics.Append(diagErrorFramework(names.MQ, create.ErrActionDeleting, ResourceNameUser, fmt.Sprintf("%s/%s", state.BrokerID.ValueString(), state.ID.ValueString()), err))
return
}
}
func (r *resourceUser) ImportState(ctx context.Context, request resource.ImportStateRequest, response *resource.ImportStateResponse) {
parts := strings.Split(request.ID, "/")
if len(parts) != 2 {
response.Diagnostics.AddError("Resource Import Invalid ID", fmt.Sprintf("wrong format of import ID (%s), use: broker-id/username'", request.ID))
return
}
brokerID := parts[0]
username := parts[1]
response.Diagnostics.Append(response.State.SetAttribute(ctx, path.Root("id"), username)...)
response.Diagnostics.Append(response.State.SetAttribute(ctx, path.Root("broker_id"), brokerID)...)
}
func findUserByID(ctx context.Context, conn *mq.Client, brokerID string, id string) (*mq.DescribeUserOutput, error) {
if brokerID == "" {
return nil, &retry.NotFoundError{
Message: "cannot find User with an empty broker ID.",
}
}
if id == "" {
return nil, &retry.NotFoundError{
Message: "cannot find User with an empty username.",
}
}
input := &mq.DescribeUserInput{
BrokerId: aws.String(brokerID),
Username: aws.String(id),
}
output, err := conn.DescribeUser(ctx, input)
if errs.IsA[*awstypes.NotFoundException](err) {
return nil, &retry.NotFoundError{
LastError: err,
LastRequest: input,
}
}
if err != nil {
return nil, err
}
if output == nil {
return nil, tfresource.NewEmptyResultError(input)
}
return output, nil
}
type resourceUserData struct {
framework.WithRegionModel
BrokerID types.String `tfsdk:"broker_id"`
ConsoleAccess types.Bool `tfsdk:"console_access"`
Groups fwtypes.ListOfString `tfsdk:"groups"`
ID types.String `tfsdk:"id"`
Password types.String `tfsdk:"password"`
ReplicationUser types.Bool `tfsdk:"replication_user"`
Username types.String `tfsdk:"username"`
Pending fwtypes.ObjectValueOf[pendingModel] `tfsdk:"pending"` // Computed-only field tracking pending AWS changes
}
// pendingModel represents pending changes to an MQ user returned by the AWS API.
// This information is populated when modifications are queued but not yet applied.
type pendingModel struct {
ConsoleAccess types.Bool `tfsdk:"console_access"`
PendingChange types.String `tfsdk:"pending_change"`
Groups fwtypes.ListOfString `tfsdk:"groups"`
}
// refreshFromOutput populates the resource data from the AWS API response.
func (rd *resourceUserData) refreshFromOutput(ctx context.Context, out *mq.DescribeUserOutput) diag.Diagnostics {
if out == nil {
return nil
}
rd.BrokerID = flex.StringToFramework(ctx, out.BrokerId)
rd.ConsoleAccess = flex.BoolToFramework(ctx, out.ConsoleAccess)
rd.Groups = flex.FlattenFrameworkStringValueListOfString(ctx, out.Groups)
rd.ReplicationUser = flex.BoolToFramework(ctx, out.ReplicationUser)
rd.Username = flex.StringToFramework(ctx, out.Username)
rd.ID = rd.Username
// Populate the pending attribute with data from the AWS API response.
// If there are pending changes, populate with actual values; otherwise use
// an empty struct.
if out.Pending != nil {
s := string(out.Pending.PendingChange)
pending, d := fwtypes.NewObjectValueOf(ctx, &pendingModel{
ConsoleAccess: flex.BoolToFramework(ctx, out.Pending.ConsoleAccess),
PendingChange: flex.StringToFramework(ctx, &s),
Groups: flex.FlattenFrameworkStringValueListOfString(ctx, out.Pending.Groups),
})
if d.HasError() {
return d
}
rd.Pending = pending
} else {
// Initialize with empty values when no pending changes exist.
pending := fwtypes.NewObjectValueOfNull[pendingModel](ctx)
rd.Pending = pending
}
return nil
}
// userHasChanges determines if the plan contains changes compared to the current state.
func userHasChanges(plan, state resourceUserData) bool {
return !plan.ConsoleAccess.Equal(state.ConsoleAccess) ||
!plan.Groups.Equal(state.Groups) ||
!plan.Password.Equal(state.Password) ||
!plan.ReplicationUser.Equal(state.ReplicationUser)
}
// Custom Plan Modifier: Sorts list items
type listSortModifier struct{}
func (m *listSortModifier) PlanModifyList(ctx context.Context, req planmodifier.ListRequest, resp *planmodifier.ListResponse) {
// Get plan value
planValue := req.PlanValue
// If plan value is null or unknown, do nothing
if planValue.IsNull() || planValue.IsUnknown() {
return
}
// Convert plan value to []string
var groups []string
diags := planValue.ElementsAs(ctx, &groups, false)
if diags.HasError() {
resp.Diagnostics.Append(diags...)
return
}
sort.Strings(groups)
// Write sorted value back to plan
sortedList, diags := types.ListValueFrom(ctx, types.StringType, groups)
if diags.HasError() {
resp.Diagnostics.Append(diags...)
return
}
resp.PlanValue = sortedList
}
func (m *listSortModifier) Description(ctx context.Context) string {
return "Sorts the list elements alphabetically."
}
func (m *listSortModifier) MarkdownDescription(ctx context.Context) string {
return "Sorts the list elements alphabetically."
}
// consoleAccessPlanModifier prevents unnecessary updates when the planned
// console_access value matches a pending change in AWS. This avoids triggering
// an update when the change is already queued on the AWS side, keeping the
// current state value instead.
type consoleAccessPlanModifier struct{}
func (c *consoleAccessPlanModifier) PlanModifyBool(ctx context.Context, req planmodifier.BoolRequest, resp *planmodifier.BoolResponse) {
var state *resourceUserData
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if state == nil || state.Pending.IsNull() {
return
}
var pm pendingModel
resp.Diagnostics.Append(state.Pending.As(ctx, &pm, basetypes.ObjectAsOptions{})...)
consoleAccessValue := req.PlanValue
// If the planned value matches the pending console_access, keep the current
// state value to avoid an unnecessary update operation.
if !pm.ConsoleAccess.IsNull() && !pm.ConsoleAccess.IsUnknown() && pm.ConsoleAccess.Equal(consoleAccessValue) {
resp.PlanValue = req.StateValue
}
}
func (c *consoleAccessPlanModifier) Description(_ context.Context) string {
return "Prevents unnecessary updates when the planned console_access value matches a pending change in AWS."
}
func (c *consoleAccessPlanModifier) MarkdownDescription(_ context.Context) string {
return "Prevents unnecessary updates when the planned `console_access` value matches a pending change in AWS."
}
// groupsPlanModifier prevents unnecessary updates when the planned groups value
// matches a pending change in AWS. This avoids triggering an update when the
// change is already queued on the AWS side, keeping the current state value instead.
type groupsPlanModifier struct{}
func (g *groupsPlanModifier) PlanModifyList(ctx context.Context, req planmodifier.ListRequest, resp *planmodifier.ListResponse) {
var state *resourceUserData
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if state == nil || state.Pending.IsNull() {
return
}
var pm pendingModel
resp.Diagnostics.Append(state.Pending.As(ctx, &pm, basetypes.ObjectAsOptions{})...)
if !pm.Groups.IsNull() && !pm.Groups.IsUnknown() && !req.PlanValue.IsNull() && !req.PlanValue.IsUnknown() {
var pendingGroups []string
resp.Diagnostics.Append(pm.Groups.ElementsAs(ctx, &pendingGroups, false)...)
var planGroups []string
resp.Diagnostics.Append(req.PlanValue.ElementsAs(ctx, &planGroups, false)...)
sort.Strings(pendingGroups)
sort.Strings(planGroups)
if slices.Equal(planGroups, pendingGroups) {
resp.PlanValue = req.StateValue
}
}
}
func (g *groupsPlanModifier) Description(_ context.Context) string {
return "Prevents unnecessary updates when the planned groups value matches a pending change in AWS."
}
func (g *groupsPlanModifier) MarkdownDescription(_ context.Context) string {
return "Prevents unnecessary updates when the planned `groups` value matches a pending change in AWS."
}