-
Notifications
You must be signed in to change notification settings - Fork 99
/
resource_aci_annotation.go
341 lines (281 loc) · 11.9 KB
/
resource_aci_annotation.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
// Code generated by "gen/generator.go"; DO NOT EDIT.
// In order to regenerate this file execute `go generate` from the repository root.
// More details can be found in the [README](https://github.com/CiscoDevNet/terraform-provider-aci/blob/master/README.md).
package provider
import (
"context"
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/ciscoecosystem/aci-go-client/v2/client"
"github.com/ciscoecosystem/aci-go-client/v2/container"
"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"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog"
)
// Ensure provider defined types fully satisfy framework interfaces.
var _ resource.Resource = &TagAnnotationResource{}
var _ resource.ResourceWithImportState = &TagAnnotationResource{}
func NewTagAnnotationResource() resource.Resource {
return &TagAnnotationResource{}
}
// TagAnnotationResource defines the resource implementation.
type TagAnnotationResource struct {
client *client.Client
}
// TagAnnotationResourceModel describes the resource data model.
type TagAnnotationResourceModel struct {
Id types.String `tfsdk:"id"`
ParentDn types.String `tfsdk:"parent_dn"`
Key types.String `tfsdk:"key"`
Value types.String `tfsdk:"value"`
}
type TagAnnotationIdentifier struct {
Key types.String
}
func (r *TagAnnotationResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
tflog.Debug(ctx, "Start metadata of resource: aci_annotation")
resp.TypeName = req.ProviderTypeName + "_annotation"
tflog.Debug(ctx, "End metadata of resource: aci_annotation")
}
func (r *TagAnnotationResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
tflog.Debug(ctx, "Start schema of resource: aci_annotation")
resp.Schema = schema.Schema{
// This description is used by the documentation generator and the language server.
MarkdownDescription: "The annotation resource for the 'tagAnnotation' class",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Computed: true,
MarkdownDescription: "The distinguished name (DN) of the Annotation object.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"parent_dn": schema.StringAttribute{
Required: true,
MarkdownDescription: "The distinguished name (DN) of the parent object.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
stringplanmodifier.RequiresReplace(),
},
},
"key": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
stringplanmodifier.RequiresReplace(),
},
MarkdownDescription: `The key used to uniquely identify this configuration object.`,
},
"value": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
MarkdownDescription: `The value of the property.`,
},
},
}
tflog.Debug(ctx, "End schema of resource: aci_annotation")
}
func (r *TagAnnotationResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
tflog.Debug(ctx, "Start configure of resource: aci_annotation")
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*client.Client)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Resource Configure Type",
fmt.Sprintf("Expected *client.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
r.client = client
tflog.Debug(ctx, "End configure of resource: aci_annotation")
}
func (r *TagAnnotationResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
tflog.Debug(ctx, "Start create of resource: aci_annotation")
var data *TagAnnotationResourceModel
// Read Terraform plan data into the model
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
setTagAnnotationId(ctx, data)
tflog.Debug(ctx, fmt.Sprintf("Create of resource aci_annotation with id '%s'", data.Id.ValueString()))
jsonPayload := getTagAnnotationCreateJsonPayload(ctx, &resp.Diagnostics, data)
if resp.Diagnostics.HasError() {
return
}
DoRestRequest(ctx, &resp.Diagnostics, r.client, fmt.Sprintf("api/mo/%s.json", data.Id.ValueString()), "POST", jsonPayload)
if resp.Diagnostics.HasError() {
return
}
getAndSetTagAnnotationAttributes(ctx, &resp.Diagnostics, r.client, data)
// Save data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
tflog.Debug(ctx, fmt.Sprintf("End create of resource aci_annotation with id '%s'", data.Id.ValueString()))
}
func (r *TagAnnotationResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
tflog.Debug(ctx, "Start read of resource: aci_annotation")
var data *TagAnnotationResourceModel
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, fmt.Sprintf("Read of resource aci_annotation with id '%s'", data.Id.ValueString()))
getAndSetTagAnnotationAttributes(ctx, &resp.Diagnostics, r.client, data)
// Save updated data into Terraform state
if data.Id.IsNull() {
var emptyData *TagAnnotationResourceModel
resp.Diagnostics.Append(resp.State.Set(ctx, &emptyData)...)
} else {
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
tflog.Debug(ctx, fmt.Sprintf("End read of resource aci_annotation with id '%s'", data.Id.ValueString()))
}
func (r *TagAnnotationResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
tflog.Debug(ctx, "Start update of resource: aci_annotation")
var data *TagAnnotationResourceModel
// Read Terraform plan data into the model
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, fmt.Sprintf("Update of resource aci_annotation with id '%s'", data.Id.ValueString()))
jsonPayload := getTagAnnotationCreateJsonPayload(ctx, &resp.Diagnostics, data)
if resp.Diagnostics.HasError() {
return
}
DoRestRequest(ctx, &resp.Diagnostics, r.client, fmt.Sprintf("api/mo/%s.json", data.Id.ValueString()), "POST", jsonPayload)
if resp.Diagnostics.HasError() {
return
}
getAndSetTagAnnotationAttributes(ctx, &resp.Diagnostics, r.client, data)
// Save updated data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
tflog.Debug(ctx, fmt.Sprintf("End update of resource aci_annotation with id '%s'", data.Id.ValueString()))
}
func (r *TagAnnotationResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
tflog.Debug(ctx, "Start delete of resource: aci_annotation")
var data *TagAnnotationResourceModel
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, fmt.Sprintf("Delete of resource aci_annotation with id '%s'", data.Id.ValueString()))
jsonPayload := GetDeleteJsonPayload(ctx, &resp.Diagnostics, "tagAnnotation", data.Id.ValueString())
if resp.Diagnostics.HasError() {
return
}
DoRestRequest(ctx, &resp.Diagnostics, r.client, fmt.Sprintf("api/mo/%s.json", data.Id.ValueString()), "POST", jsonPayload)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, fmt.Sprintf("End delete of resource aci_annotation with id '%s'", data.Id.ValueString()))
}
func (r *TagAnnotationResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
tflog.Debug(ctx, "Start import state of resource: aci_annotation")
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
var stateData *TagAnnotationResourceModel
resp.Diagnostics.Append(resp.State.Get(ctx, &stateData)...)
tflog.Debug(ctx, fmt.Sprintf("Import state of resource aci_annotation with id '%s'", stateData.Id.ValueString()))
tflog.Debug(ctx, "End import of state resource: aci_annotation")
}
func getAndSetTagAnnotationAttributes(ctx context.Context, diags *diag.Diagnostics, client *client.Client, data *TagAnnotationResourceModel) {
requestData := DoRestRequest(ctx, diags, client, fmt.Sprintf("api/mo/%s.json", data.Id.ValueString()), "GET", nil)
if diags.HasError() {
return
}
if requestData.Search("imdata").Search("tagAnnotation").Data() != nil {
classReadInfo := requestData.Search("imdata").Search("tagAnnotation").Data().([]interface{})
if len(classReadInfo) == 1 {
attributes := classReadInfo[0].(map[string]interface{})["attributes"].(map[string]interface{})
for attributeName, attributeValue := range attributes {
if attributeName == "dn" {
data.Id = basetypes.NewStringValue(attributeValue.(string))
setTagAnnotationParentDn(ctx, attributeValue.(string), data)
}
if attributeName == "key" {
data.Key = basetypes.NewStringValue(attributeValue.(string))
}
if attributeName == "value" {
data.Value = basetypes.NewStringValue(attributeValue.(string))
}
}
} else {
diags.AddError(
"too many results in response",
fmt.Sprintf("%v matches returned for class 'tagAnnotation'. Please report this issue to the provider developers.", len(classReadInfo)),
)
}
} else {
data.Id = basetypes.NewStringNull()
}
}
func getTagAnnotationRn(ctx context.Context, data *TagAnnotationResourceModel) string {
rn := "annotationKey-[{key}]"
for _, identifier := range []string{"key"} {
fieldName := fmt.Sprintf("%s%s", strings.ToUpper(identifier[:1]), identifier[1:])
fieldValue := reflect.ValueOf(data).Elem().FieldByName(fieldName).Interface().(basetypes.StringValue).ValueString()
rn = strings.ReplaceAll(rn, fmt.Sprintf("{%s}", identifier), fieldValue)
}
return rn
}
func setTagAnnotationParentDn(ctx context.Context, dn string, data *TagAnnotationResourceModel) {
bracketIndex := 0
rnIndex := 0
for i := len(dn) - 1; i >= 0; i-- {
if string(dn[i]) == "]" {
bracketIndex = bracketIndex + 1
} else if string(dn[i]) == "[" {
bracketIndex = bracketIndex - 1
} else if string(dn[i]) == "/" && bracketIndex == 0 {
rnIndex = i
break
}
}
data.ParentDn = basetypes.NewStringValue(dn[:rnIndex])
}
func setTagAnnotationId(ctx context.Context, data *TagAnnotationResourceModel) {
rn := getTagAnnotationRn(ctx, data)
data.Id = types.StringValue(fmt.Sprintf("%s/%s", data.ParentDn.ValueString(), rn))
}
func getTagAnnotationCreateJsonPayload(ctx context.Context, diags *diag.Diagnostics, data *TagAnnotationResourceModel) *container.Container {
payloadMap := map[string]interface{}{}
payloadMap["attributes"] = map[string]string{}
if !data.Key.IsNull() && !data.Key.IsUnknown() {
payloadMap["attributes"].(map[string]string)["key"] = data.Key.ValueString()
}
if !data.Value.IsNull() && !data.Value.IsUnknown() {
payloadMap["attributes"].(map[string]string)["value"] = data.Value.ValueString()
}
payload, err := json.Marshal(map[string]interface{}{"tagAnnotation": payloadMap})
if err != nil {
diags.AddError(
"Marshalling of json payload failed",
fmt.Sprintf("Err: %s. Please report this issue to the provider developers.", err),
)
return nil
}
jsonPayload, err := container.ParseJSON(payload)
if err != nil {
diags.AddError(
"Construction of json payload failed",
fmt.Sprintf("Err: %s. Please report this issue to the provider developers.", err),
)
return nil
}
return jsonPayload
}