/
server_group_resource.go
415 lines (357 loc) · 15.8 KB
/
server_group_resource.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
package servergroup
import (
"context"
"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/stringdefault"
"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-log/tflog"
client "github.com/pingidentity/pingdirectory-go-client/v10000/configurationapi"
"github.com/pingidentity/terraform-provider-pingdirectory/internal/operations"
"github.com/pingidentity/terraform-provider-pingdirectory/internal/resource/config"
internaltypes "github.com/pingidentity/terraform-provider-pingdirectory/internal/types"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &serverGroupResource{}
_ resource.ResourceWithConfigure = &serverGroupResource{}
_ resource.ResourceWithImportState = &serverGroupResource{}
_ resource.Resource = &defaultServerGroupResource{}
_ resource.ResourceWithConfigure = &defaultServerGroupResource{}
_ resource.ResourceWithImportState = &defaultServerGroupResource{}
)
// Create a Server Group resource
func NewServerGroupResource() resource.Resource {
return &serverGroupResource{}
}
func NewDefaultServerGroupResource() resource.Resource {
return &defaultServerGroupResource{}
}
// serverGroupResource is the resource implementation.
type serverGroupResource struct {
providerConfig internaltypes.ProviderConfiguration
apiClient *client.APIClient
}
// defaultServerGroupResource is the resource implementation.
type defaultServerGroupResource struct {
providerConfig internaltypes.ProviderConfiguration
apiClient *client.APIClient
}
// Metadata returns the resource type name.
func (r *serverGroupResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_server_group"
}
func (r *defaultServerGroupResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_default_server_group"
}
// Configure adds the provider configured client to the resource.
func (r *serverGroupResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
providerCfg := req.ProviderData.(internaltypes.ResourceConfiguration)
r.providerConfig = providerCfg.ProviderConfig
r.apiClient = providerCfg.ApiClient
}
func (r *defaultServerGroupResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
providerCfg := req.ProviderData.(internaltypes.ResourceConfiguration)
r.providerConfig = providerCfg.ProviderConfig
r.apiClient = providerCfg.ApiClient
}
type serverGroupResourceModel struct {
Id types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Notifications types.Set `tfsdk:"notifications"`
RequiredActions types.Set `tfsdk:"required_actions"`
Type types.String `tfsdk:"type"`
Member types.Set `tfsdk:"member"`
}
// GetSchema defines the schema for the resource.
func (r *serverGroupResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
serverGroupSchema(ctx, req, resp, false)
}
func (r *defaultServerGroupResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
serverGroupSchema(ctx, req, resp, true)
}
func serverGroupSchema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse, isDefault bool) {
schemaDef := schema.Schema{
Description: "Manages a Server Group.",
Attributes: map[string]schema.Attribute{
"type": schema.StringAttribute{
Description: "The type of Server Group resource. Options are ['server-group']",
Optional: true,
Computed: true,
Default: stringdefault.StaticString("server-group"),
Validators: []validator.String{
stringvalidator.OneOf([]string{"server-group"}...),
},
},
"member": schema.SetAttribute{
Description: "A server instance that is a member of this group.",
Optional: true,
Computed: true,
Default: internaltypes.EmptySetDefault(types.StringType),
ElementType: types.StringType,
},
},
}
if isDefault {
typeAttr := schemaDef.Attributes["type"].(schema.StringAttribute)
typeAttr.Optional = false
typeAttr.Required = false
typeAttr.Computed = true
typeAttr.PlanModifiers = []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
}
schemaDef.Attributes["type"] = typeAttr
// Add any default properties and set optional properties to computed where necessary
config.SetAttributesToOptionalAndComputedAndRemoveDefaults(&schemaDef, []string{"type"})
}
config.AddCommonResourceSchema(&schemaDef, true)
resp.Schema = schemaDef
}
// Add optional fields to create request for server-group server-group
func addOptionalServerGroupFields(ctx context.Context, addRequest *client.AddServerGroupRequest, plan serverGroupResourceModel) {
if internaltypes.IsDefined(plan.Member) {
var slice []string
plan.Member.ElementsAs(ctx, &slice, false)
addRequest.Member = slice
}
}
// Read a ServerGroupResponse object into the model struct
func readServerGroupResponse(ctx context.Context, r *client.ServerGroupResponse, state *serverGroupResourceModel, expectedValues *serverGroupResourceModel, diagnostics *diag.Diagnostics) {
state.Type = types.StringValue("server-group")
state.Id = types.StringValue(r.Id)
state.Name = types.StringValue(r.Id)
state.Member = internaltypes.GetStringSet(r.Member)
state.Notifications, state.RequiredActions = config.ReadMessages(ctx, r.Urnpingidentityschemasconfigurationmessages20, diagnostics)
}
// Create any update operations necessary to make the state match the plan
func createServerGroupOperations(plan serverGroupResourceModel, state serverGroupResourceModel) []client.Operation {
var ops []client.Operation
operations.AddStringSetOperationsIfNecessary(&ops, plan.Member, state.Member, "member")
return ops
}
// Create a server-group server-group
func (r *serverGroupResource) CreateServerGroup(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse, plan serverGroupResourceModel) (*serverGroupResourceModel, error) {
addRequest := client.NewAddServerGroupRequest(plan.Name.ValueString())
addOptionalServerGroupFields(ctx, addRequest, plan)
// Log request JSON
requestJson, err := addRequest.MarshalJSON()
if err == nil {
tflog.Debug(ctx, "Add request: "+string(requestJson))
}
apiAddRequest := r.apiClient.ServerGroupAPI.AddServerGroup(
config.ProviderBasicAuthContext(ctx, r.providerConfig))
apiAddRequest = apiAddRequest.AddServerGroupRequest(*addRequest)
addResponse, httpResp, err := r.apiClient.ServerGroupAPI.AddServerGroupExecute(apiAddRequest)
if err != nil {
config.ReportHttpError(ctx, &resp.Diagnostics, "An error occurred while creating the Server Group", err, httpResp)
return nil, err
}
// Log response JSON
responseJson, err := addResponse.MarshalJSON()
if err == nil {
tflog.Debug(ctx, "Add response: "+string(responseJson))
}
// Read the response into the state
var state serverGroupResourceModel
readServerGroupResponse(ctx, addResponse, &state, &plan, &resp.Diagnostics)
return &state, nil
}
// Create a new resource
func (r *serverGroupResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
// Retrieve values from plan
var plan serverGroupResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
state, err := r.CreateServerGroup(ctx, req, resp, plan)
if err != nil {
return
}
// Set state to fully populated data
diags = resp.State.Set(ctx, *state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
// Create a new resource
// For edit only resources like this, create doesn't actually "create" anything - it "adopts" the existing
// config object into management by terraform. This method reads the existing config object
// and makes any changes needed to make it match the plan - similar to the Update method.
func (r *defaultServerGroupResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
// Retrieve values from plan
var plan serverGroupResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
readResponse, httpResp, err := r.apiClient.ServerGroupAPI.GetServerGroup(
config.ProviderBasicAuthContext(ctx, r.providerConfig), plan.Name.ValueString()).Execute()
if err != nil {
config.ReportHttpError(ctx, &resp.Diagnostics, "An error occurred while getting the Server Group", err, httpResp)
return
}
// Log response JSON
responseJson, err := readResponse.MarshalJSON()
if err == nil {
tflog.Debug(ctx, "Read response: "+string(responseJson))
}
// Read the existing configuration
var state serverGroupResourceModel
readServerGroupResponse(ctx, readResponse, &state, &state, &resp.Diagnostics)
// Determine what changes are needed to match the plan
updateRequest := r.apiClient.ServerGroupAPI.UpdateServerGroup(config.ProviderBasicAuthContext(ctx, r.providerConfig), plan.Name.ValueString())
ops := createServerGroupOperations(plan, state)
if len(ops) > 0 {
updateRequest = updateRequest.UpdateRequest(*client.NewUpdateRequest(ops))
// Log operations
operations.LogUpdateOperations(ctx, ops)
updateResponse, httpResp, err := r.apiClient.ServerGroupAPI.UpdateServerGroupExecute(updateRequest)
if err != nil {
config.ReportHttpError(ctx, &resp.Diagnostics, "An error occurred while updating the Server Group", err, httpResp)
return
}
// Log response JSON
responseJson, err := updateResponse.MarshalJSON()
if err == nil {
tflog.Debug(ctx, "Update response: "+string(responseJson))
}
// Read the response
readServerGroupResponse(ctx, updateResponse, &state, &plan, &resp.Diagnostics)
}
diags = resp.State.Set(ctx, state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
// Read resource information
func (r *serverGroupResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
readServerGroup(ctx, req, resp, r.apiClient, r.providerConfig, false)
}
func (r *defaultServerGroupResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
readServerGroup(ctx, req, resp, r.apiClient, r.providerConfig, true)
}
func readServerGroup(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse, apiClient *client.APIClient, providerConfig internaltypes.ProviderConfiguration, isDefault bool) {
// Get current state
var state serverGroupResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
readResponse, httpResp, err := apiClient.ServerGroupAPI.GetServerGroup(
config.ProviderBasicAuthContext(ctx, providerConfig), state.Name.ValueString()).Execute()
if err != nil {
if httpResp != nil && httpResp.StatusCode == 404 && !isDefault {
config.ReportHttpErrorAsWarning(ctx, &resp.Diagnostics, "An error occurred while getting the Server Group", err, httpResp)
resp.State.RemoveResource(ctx)
} else {
config.ReportHttpError(ctx, &resp.Diagnostics, "An error occurred while getting the Server Group", err, httpResp)
}
return
}
// Log response JSON
responseJson, err := readResponse.MarshalJSON()
if err == nil {
tflog.Debug(ctx, "Read response: "+string(responseJson))
}
// Read the response into the state
readServerGroupResponse(ctx, readResponse, &state, &state, &resp.Diagnostics)
// Set refreshed state
diags = resp.State.Set(ctx, &state)
resp.Diagnostics.Append(diags...)
}
// Update a resource
func (r *serverGroupResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
updateServerGroup(ctx, req, resp, r.apiClient, r.providerConfig)
}
func (r *defaultServerGroupResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
updateServerGroup(ctx, req, resp, r.apiClient, r.providerConfig)
}
func updateServerGroup(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse, apiClient *client.APIClient, providerConfig internaltypes.ProviderConfiguration) {
// Retrieve values from plan
var plan serverGroupResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Get the current state to see how any attributes are changing
var state serverGroupResourceModel
req.State.Get(ctx, &state)
updateRequest := apiClient.ServerGroupAPI.UpdateServerGroup(
config.ProviderBasicAuthContext(ctx, providerConfig), plan.Name.ValueString())
// Determine what update operations are necessary
ops := createServerGroupOperations(plan, state)
if len(ops) > 0 {
updateRequest = updateRequest.UpdateRequest(*client.NewUpdateRequest(ops))
// Log operations
operations.LogUpdateOperations(ctx, ops)
updateResponse, httpResp, err := apiClient.ServerGroupAPI.UpdateServerGroupExecute(updateRequest)
if err != nil {
config.ReportHttpError(ctx, &resp.Diagnostics, "An error occurred while updating the Server Group", err, httpResp)
return
}
// Log response JSON
responseJson, err := updateResponse.MarshalJSON()
if err == nil {
tflog.Debug(ctx, "Update response: "+string(responseJson))
}
// Read the response
readServerGroupResponse(ctx, updateResponse, &state, &plan, &resp.Diagnostics)
} else {
tflog.Warn(ctx, "No configuration API operations created for update")
}
diags = resp.State.Set(ctx, state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
// Delete deletes the resource and removes the Terraform state on success.
// This config object is edit-only, so Terraform can't delete it.
// After running a delete, Terraform will just "forget" about this object and it can be managed elsewhere.
func (r *defaultServerGroupResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
// No implementation necessary
}
func (r *serverGroupResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
// Retrieve values from state
var state serverGroupResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
httpResp, err := r.apiClient.ServerGroupAPI.DeleteServerGroupExecute(r.apiClient.ServerGroupAPI.DeleteServerGroup(
config.ProviderBasicAuthContext(ctx, r.providerConfig), state.Name.ValueString()))
if err != nil && (httpResp == nil || httpResp.StatusCode != 404) {
config.ReportHttpError(ctx, &resp.Diagnostics, "An error occurred while deleting the Server Group", err, httpResp)
return
}
}
func (r *serverGroupResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
importServerGroup(ctx, req, resp)
}
func (r *defaultServerGroupResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
importServerGroup(ctx, req, resp)
}
func importServerGroup(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
// Retrieve import ID and save to name attribute
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
}