/
synchronization_provider_resource.go
328 lines (291 loc) · 13.9 KB
/
synchronization_provider_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
package synchronizationprovider
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/boolplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"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-log/tflog"
client "github.com/pingidentity/pingdirectory-go-client/v10000/configurationapi"
"github.com/pingidentity/terraform-provider-pingdirectory/internal/configvalidators"
"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 = &synchronizationProviderResource{}
_ resource.ResourceWithConfigure = &synchronizationProviderResource{}
_ resource.ResourceWithImportState = &synchronizationProviderResource{}
)
// Create a Synchronization Provider resource
func NewSynchronizationProviderResource() resource.Resource {
return &synchronizationProviderResource{}
}
// synchronizationProviderResource is the resource implementation.
type synchronizationProviderResource struct {
providerConfig internaltypes.ProviderConfiguration
apiClient *client.APIClient
}
// Metadata returns the resource type name.
func (r *synchronizationProviderResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_default_synchronization_provider"
}
// Configure adds the provider configured client to the resource.
func (r *synchronizationProviderResource) 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 synchronizationProviderResourceModel 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"`
NumUpdateReplayThreads types.Int64 `tfsdk:"num_update_replay_threads"`
Description types.String `tfsdk:"description"`
Enabled types.Bool `tfsdk:"enabled"`
}
// GetSchema defines the schema for the resource.
func (r *synchronizationProviderResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
schemaDef := schema.Schema{
Description: "Manages a Synchronization Provider.",
Attributes: map[string]schema.Attribute{
"type": schema.StringAttribute{
Description: "The type of Synchronization Provider resource. Options are ['replication', 'custom']",
Optional: false,
Required: false,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Validators: []validator.String{
stringvalidator.OneOf([]string{"replication", "custom"}...),
},
},
"num_update_replay_threads": schema.Int64Attribute{
Description: "Specifies the number of update replay threads.",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknown(),
},
},
"description": schema.StringAttribute{
Description: "A description for this Synchronization Provider",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"enabled": schema.BoolAttribute{
Description: "Indicates whether the Synchronization Provider is enabled for use.",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
},
}
config.AddCommonResourceSchema(&schemaDef, true)
resp.Schema = schemaDef
}
// Add config validators
func (r synchronizationProviderResource) ConfigValidators(ctx context.Context) []resource.ConfigValidator {
return []resource.ConfigValidator{
configvalidators.ImpliesOtherAttributeOneOfString(
path.MatchRoot("num_update_replay_threads"),
path.MatchRoot("type"),
[]string{"replication"},
),
}
}
// Read a ReplicationSynchronizationProviderResponse object into the model struct
func readReplicationSynchronizationProviderResponse(ctx context.Context, r *client.ReplicationSynchronizationProviderResponse, state *synchronizationProviderResourceModel, diagnostics *diag.Diagnostics) {
state.Type = types.StringValue("replication")
state.Id = types.StringValue(r.Id)
state.Name = types.StringValue(r.Id)
state.NumUpdateReplayThreads = internaltypes.Int64TypeOrNil(r.NumUpdateReplayThreads)
state.Description = internaltypes.StringTypeOrNil(r.Description, true)
state.Enabled = types.BoolValue(r.Enabled)
state.Notifications, state.RequiredActions = config.ReadMessages(ctx, r.Urnpingidentityschemasconfigurationmessages20, diagnostics)
}
// Read a CustomSynchronizationProviderResponse object into the model struct
func readCustomSynchronizationProviderResponse(ctx context.Context, r *client.CustomSynchronizationProviderResponse, state *synchronizationProviderResourceModel, diagnostics *diag.Diagnostics) {
state.Type = types.StringValue("custom")
state.Id = types.StringValue(r.Id)
state.Name = types.StringValue(r.Id)
state.Description = internaltypes.StringTypeOrNil(r.Description, true)
state.Enabled = types.BoolValue(r.Enabled)
state.Notifications, state.RequiredActions = config.ReadMessages(ctx, r.Urnpingidentityschemasconfigurationmessages20, diagnostics)
}
// Create any update operations necessary to make the state match the plan
func createSynchronizationProviderOperations(plan synchronizationProviderResourceModel, state synchronizationProviderResourceModel) []client.Operation {
var ops []client.Operation
operations.AddInt64OperationIfNecessary(&ops, plan.NumUpdateReplayThreads, state.NumUpdateReplayThreads, "num-update-replay-threads")
operations.AddStringOperationIfNecessary(&ops, plan.Description, state.Description, "description")
operations.AddBoolOperationIfNecessary(&ops, plan.Enabled, state.Enabled, "enabled")
return ops
}
// 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 *synchronizationProviderResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
// Retrieve values from plan
var plan synchronizationProviderResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
readResponse, httpResp, err := r.apiClient.SynchronizationProviderAPI.GetSynchronizationProvider(
config.ProviderBasicAuthContext(ctx, r.providerConfig), plan.Name.ValueString()).Execute()
if err != nil {
config.ReportHttpError(ctx, &resp.Diagnostics, "An error occurred while getting the Synchronization Provider", 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 synchronizationProviderResourceModel
if readResponse.ReplicationSynchronizationProviderResponse != nil {
readReplicationSynchronizationProviderResponse(ctx, readResponse.ReplicationSynchronizationProviderResponse, &state, &resp.Diagnostics)
}
if readResponse.CustomSynchronizationProviderResponse != nil {
readCustomSynchronizationProviderResponse(ctx, readResponse.CustomSynchronizationProviderResponse, &state, &resp.Diagnostics)
}
// Determine what changes are needed to match the plan
updateRequest := r.apiClient.SynchronizationProviderAPI.UpdateSynchronizationProvider(config.ProviderBasicAuthContext(ctx, r.providerConfig), plan.Name.ValueString())
ops := createSynchronizationProviderOperations(plan, state)
if len(ops) > 0 {
updateRequest = updateRequest.UpdateRequest(*client.NewUpdateRequest(ops))
// Log operations
operations.LogUpdateOperations(ctx, ops)
updateResponse, httpResp, err := r.apiClient.SynchronizationProviderAPI.UpdateSynchronizationProviderExecute(updateRequest)
if err != nil {
config.ReportHttpError(ctx, &resp.Diagnostics, "An error occurred while updating the Synchronization Provider", err, httpResp)
return
}
// Log response JSON
responseJson, err := updateResponse.MarshalJSON()
if err == nil {
tflog.Debug(ctx, "Update response: "+string(responseJson))
}
// Read the response
if updateResponse.ReplicationSynchronizationProviderResponse != nil {
readReplicationSynchronizationProviderResponse(ctx, updateResponse.ReplicationSynchronizationProviderResponse, &state, &resp.Diagnostics)
}
if updateResponse.CustomSynchronizationProviderResponse != nil {
readCustomSynchronizationProviderResponse(ctx, updateResponse.CustomSynchronizationProviderResponse, &state, &resp.Diagnostics)
}
}
diags = resp.State.Set(ctx, state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
// Read resource information
func (r *synchronizationProviderResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
// Get current state
var state synchronizationProviderResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
readResponse, httpResp, err := r.apiClient.SynchronizationProviderAPI.GetSynchronizationProvider(
config.ProviderBasicAuthContext(ctx, r.providerConfig), state.Name.ValueString()).Execute()
if err != nil {
config.ReportHttpError(ctx, &resp.Diagnostics, "An error occurred while getting the Synchronization Provider", 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
if readResponse.ReplicationSynchronizationProviderResponse != nil {
readReplicationSynchronizationProviderResponse(ctx, readResponse.ReplicationSynchronizationProviderResponse, &state, &resp.Diagnostics)
}
if readResponse.CustomSynchronizationProviderResponse != nil {
readCustomSynchronizationProviderResponse(ctx, readResponse.CustomSynchronizationProviderResponse, &state, &resp.Diagnostics)
}
// Set refreshed state
diags = resp.State.Set(ctx, &state)
resp.Diagnostics.Append(diags...)
}
// Update a resource
func (r *synchronizationProviderResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
// Retrieve values from plan
var plan synchronizationProviderResourceModel
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 synchronizationProviderResourceModel
req.State.Get(ctx, &state)
updateRequest := r.apiClient.SynchronizationProviderAPI.UpdateSynchronizationProvider(
config.ProviderBasicAuthContext(ctx, r.providerConfig), plan.Name.ValueString())
// Determine what update operations are necessary
ops := createSynchronizationProviderOperations(plan, state)
if len(ops) > 0 {
updateRequest = updateRequest.UpdateRequest(*client.NewUpdateRequest(ops))
// Log operations
operations.LogUpdateOperations(ctx, ops)
updateResponse, httpResp, err := r.apiClient.SynchronizationProviderAPI.UpdateSynchronizationProviderExecute(updateRequest)
if err != nil {
config.ReportHttpError(ctx, &resp.Diagnostics, "An error occurred while updating the Synchronization Provider", err, httpResp)
return
}
// Log response JSON
responseJson, err := updateResponse.MarshalJSON()
if err == nil {
tflog.Debug(ctx, "Update response: "+string(responseJson))
}
// Read the response
if updateResponse.ReplicationSynchronizationProviderResponse != nil {
readReplicationSynchronizationProviderResponse(ctx, updateResponse.ReplicationSynchronizationProviderResponse, &state, &resp.Diagnostics)
}
if updateResponse.CustomSynchronizationProviderResponse != nil {
readCustomSynchronizationProviderResponse(ctx, updateResponse.CustomSynchronizationProviderResponse, &state, &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 *synchronizationProviderResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
// No implementation necessary
}
func (r *synchronizationProviderResource) ImportState(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)
}