/
resource_akamai_imaging_policy_image.go
438 lines (396 loc) · 12.9 KB
/
resource_akamai_imaging_policy_image.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
package imaging
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"reflect"
"strings"
"github.com/akamai/AkamaiOPEN-edgegrid-golang/v2/pkg/imaging"
"github.com/akamai/AkamaiOPEN-edgegrid-golang/v2/pkg/session"
"github.com/akamai/terraform-provider-akamai/v2/pkg/akamai"
"github.com/akamai/terraform-provider-akamai/v2/pkg/tools"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
// MaxPolicyDepth is the maximum supported depth of the nested transformations, before we reach hard limit of the Terraform
// provider for the gRPC communication for exchanging schema information, which is 64MB
const MaxPolicyDepth = 7
// PolicyDepth is variable to allow changing it for the unit tests, to achieve faster execution for tests,
// which do not need all supported levels
var PolicyDepth = MaxPolicyDepth
func resourceImagingPolicyImage() *schema.Resource {
return &schema.Resource{
CustomizeDiff: customdiff.All(
enforcePolicyImageVersionChange,
),
CreateContext: resourcePolicyImageCreate,
ReadContext: resourcePolicyImageRead,
UpdateContext: resourcePolicyImageUpdate,
DeleteContext: resourcePolicyImageDelete,
Schema: map[string]*schema.Schema{
"activate_on_production": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "With this flag set to false, the user can perform modifications on staging without affecting the version already saved to production. " +
"With this flag set to true, the policy will be saved on the production network. " +
"It is possible to change it back to false only when there are any changes to the policy qualifying it for the new version.",
},
"version": {
Type: schema.TypeInt,
Computed: true,
Description: "The version number of this policy version",
},
"contract_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Unique identifier for the Akamai Contract containing the Policy Set(s)",
},
"policy_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Unique identifier for a Policy. It is not possible to modify the id of the policy.",
},
"policyset_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Unique identifier for the Image & Video Manager Policy Set.",
},
"json": {
Type: schema.TypeString,
Required: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsJSON),
DiffSuppressFunc: diffSuppressPolicyImage,
Description: "A JSON encoded policy",
},
},
Importer: &schema.ResourceImporter{
StateContext: resourcePolicyImageImport,
},
}
}
func resourcePolicyImageCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
meta := akamai.Meta(m)
logger := meta.Log("Imaging", "resourcePolicyImageCreate")
ctx = session.ContextWithOptions(
ctx,
session.WithContextLog(logger),
)
client := inst.Client(meta)
logger.Debug("Creating policy")
return upsertPolicyImage(ctx, d, m, client)
}
func upsertPolicyImage(ctx context.Context, d *schema.ResourceData, m interface{}, client imaging.Imaging) diag.Diagnostics {
policyID, err := tools.GetStringValue("policy_id", d)
if err != nil {
return diag.FromErr(err)
}
contractID, err := tools.GetStringValue("contract_id", d)
if err != nil {
return diag.FromErr(err)
}
policySetID, err := tools.GetStringValue("policyset_id", d)
if err != nil {
return diag.FromErr(err)
}
var policy imaging.PolicyInputImage
policyJSON, err := tools.GetStringValue("json", d)
if err != nil {
return diag.FromErr(err)
}
if err = json.Unmarshal([]byte(policyJSON), &policy); err != nil {
return diag.FromErr(err)
}
// upsert on staging only when there was a change
if d.HasChangesExcept("activate_on_production") {
upsertPolicyRequest := imaging.UpsertPolicyRequest{
PolicyID: policyID,
Network: imaging.PolicyNetworkStaging,
ContractID: contractID,
PolicySetID: policySetID,
PolicyInput: &policy,
}
createPolicyResp, err := client.UpsertPolicy(ctx, upsertPolicyRequest)
if err != nil {
return diag.FromErr(err)
}
d.SetId(fmt.Sprintf("%s:%s", policySetID, createPolicyResp.ID))
}
activateOnProduction, err := tools.GetBoolValue("activate_on_production", d)
if err != nil && !errors.Is(err, tools.ErrNotFound) {
return diag.FromErr(err)
}
if activateOnProduction {
upsertPolicyRequest := imaging.UpsertPolicyRequest{
PolicyID: policyID,
Network: imaging.PolicyNetworkProduction,
ContractID: contractID,
PolicySetID: policySetID,
PolicyInput: &policy,
}
_, err := client.UpsertPolicy(ctx, upsertPolicyRequest)
if err != nil {
return diag.FromErr(err)
}
}
return resourcePolicyImageRead(ctx, d, m)
}
func resourcePolicyImageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
meta := akamai.Meta(m)
logger := meta.Log("Imaging", "resourcePolicyImageRead")
ctx = session.ContextWithOptions(
ctx,
session.WithContextLog(logger),
)
client := inst.Client(meta)
logger.Debug("Reading policy")
policyID, err := tools.GetStringValue("policy_id", d)
if err != nil {
return diag.FromErr(err)
}
contractID, err := tools.GetStringValue("contract_id", d)
if err != nil {
return diag.FromErr(err)
}
policysetID, err := tools.GetStringValue("policyset_id", d)
if err != nil {
return diag.FromErr(err)
}
policy, err := getPolicyImage(ctx, client, policyID, contractID, policysetID, imaging.PolicyNetworkStaging)
if err != nil {
return diag.FromErr(err)
}
policyInput, err := repackPolicyImageOutputToInput(policy)
if err != nil {
return diag.FromErr(err)
}
policyInput.RolloutDuration, err = getRolloutDuration(d)
if err != nil {
return diag.FromErr(err)
}
policyJSON, err := getPolicyImageJSON(policyInput)
if err != nil {
return diag.FromErr(err)
}
attrs := make(map[string]interface{})
attrs["json"] = policyJSON
attrs["version"] = policy.Version
if err := tools.SetAttrs(d, attrs); err != nil {
return diag.FromErr(err)
}
return nil
}
func repackPolicyImageOutputToInput(policy *imaging.PolicyOutputImage) (*imaging.PolicyInputImage, error) {
policyOutputJSON, err := json.Marshal(policy)
if err != nil {
return nil, err
}
policyInput := imaging.PolicyInputImage{}
err = json.Unmarshal(policyOutputJSON, &policyInput)
if err != nil {
return nil, err
}
return &policyInput, nil
}
func getPolicyImage(ctx context.Context, client imaging.Imaging, policyID, contractID, policySetID string, network imaging.PolicyNetwork) (*imaging.PolicyOutputImage, error) {
policyRequest := imaging.GetPolicyRequest{
PolicyID: policyID,
Network: network,
ContractID: contractID,
PolicySetID: policySetID,
}
policyOutput, err := client.GetPolicy(ctx, policyRequest)
if err != nil {
return nil, err
}
policy, ok := policyOutput.(*imaging.PolicyOutputImage)
if !ok {
return nil, fmt.Errorf("policy is not of type image")
}
return policy, nil
}
func getPolicyImageJSON(policy *imaging.PolicyInputImage) (string, error) {
policyJSON, err := json.MarshalIndent(policy, "", " ")
if err != nil {
return "", err
}
return string(policyJSON), nil
}
func resourcePolicyImageUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
meta := akamai.Meta(m)
logger := meta.Log("Imaging", "resourcePolicyImageUpdate")
ctx = session.ContextWithOptions(
ctx,
session.WithContextLog(logger),
)
client := inst.Client(meta)
logger.Debug("Updating policy")
return upsertPolicyImage(ctx, d, m, client)
}
func resourcePolicyImageDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
meta := akamai.Meta(m)
logger := meta.Log("Imaging", "resourcePolicyImageDelete")
ctx = session.ContextWithOptions(
ctx,
session.WithContextLog(logger),
)
client := inst.Client(meta)
logger.Debug("Deleting policy")
policyID, err := tools.GetStringValue("policy_id", d)
if err != nil {
return diag.FromErr(err)
}
// .auto policy cannot be removed alone, only via removal of policy set
if policyID == ".auto" {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Warning,
Summary: "Image and Video Manager API does not support '.auto' policy deletion, it can be removed when removing related policy set - resource will only be removed from state.",
},
}
}
contractID, err := tools.GetStringValue("contract_id", d)
if err != nil {
return diag.FromErr(err)
}
policySetID, err := tools.GetStringValue("policyset_id", d)
if err != nil {
return diag.FromErr(err)
}
// delete on staging
deletePolicyRequest := imaging.DeletePolicyRequest{
PolicyID: policyID,
Network: imaging.PolicyNetworkStaging,
ContractID: contractID,
PolicySetID: policySetID,
}
_, err = client.DeletePolicy(ctx, deletePolicyRequest)
if err != nil {
return diag.FromErr(err)
}
// delete on production, API returns success even if policy does not exist
// it is faster to attempt to delete on production than checking if there is policy on production first
deletePolicyRequest = imaging.DeletePolicyRequest{
PolicyID: policyID,
Network: imaging.PolicyNetworkProduction,
ContractID: contractID,
PolicySetID: policySetID,
}
_, err = client.DeletePolicy(ctx, deletePolicyRequest)
if err != nil {
return diag.FromErr(err)
}
d.SetId("")
return nil
}
func resourcePolicyImageImport(ctx context.Context, d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) {
meta := akamai.Meta(m)
logger := meta.Log("Imaging", "resourcePolicyImageImport")
ctx = session.ContextWithOptions(
ctx,
session.WithContextLog(logger),
)
client := inst.Client(meta)
parts := strings.Split(d.Id(), ":")
if len(parts) != 3 {
return nil, fmt.Errorf("colon-separated list of policy ID, policy set ID and contract ID has to be supplied in import: %s", d.Id())
}
policyID, policySetID, contractID := parts[0], parts[1], parts[2]
policyStaging, err := getPolicyImage(ctx, client, policyID, contractID, policySetID, imaging.PolicyNetworkStaging)
if err != nil {
return nil, err
}
policy, err := repackPolicyImageOutputToInput(policyStaging)
if err != nil {
return nil, err
}
policyStagingJSON, err := getPolicyImageJSON(policy)
if err != nil {
return nil, err
}
var activateOnProduction bool
policyProduction, err := getPolicyImage(ctx, client, policyID, contractID, policySetID, imaging.PolicyNetworkProduction)
if err != nil {
var e *imaging.Error
if ok := errors.As(err, &e); !ok || e.Status != http.StatusNotFound {
return nil, err
}
} else {
policy, err := repackPolicyImageOutputToInput(policyProduction)
if err != nil {
return nil, err
}
policyProductionJSON, err := getPolicyImageJSON(policy)
if err != nil {
return nil, err
}
activateOnProduction = equalPolicyImage(policyStagingJSON, policyProductionJSON)
}
attrs := make(map[string]interface{})
attrs["policy_id"] = policyID
attrs["contract_id"] = contractID
attrs["policyset_id"] = policySetID
attrs["activate_on_production"] = activateOnProduction
if err := tools.SetAttrs(d, attrs); err != nil {
return nil, err
}
d.SetId(fmt.Sprintf("%s:%s", policySetID, policyID))
return []*schema.ResourceData{d}, nil
}
func diffSuppressPolicyImage(_, old, new string, _ *schema.ResourceData) bool {
return equalPolicyImage(old, new)
}
func equalPolicyImage(old, new string) bool {
logger := akamai.Log("Imaging", "equalPolicyImage")
if old == new {
return true
}
var oldPolicy, newPolicy imaging.PolicyInputImage
if old == "" || new == "" {
return old == new
}
if err := json.Unmarshal([]byte(old), &oldPolicy); err != nil {
logger.Errorf("Unable to unmarshal 'old' JSON policy: %s", err)
return false
}
if err := json.Unmarshal([]byte(new), &newPolicy); err != nil {
logger.Errorf("Unable to unmarshal 'new' JSON policy: %s", err)
return false
}
return reflect.DeepEqual(oldPolicy, newPolicy)
}
// enforcePolicyImageVersionChange enforces that change to any field will most likely result in creating a new version
func enforcePolicyImageVersionChange(_ context.Context, diff *schema.ResourceDiff, _ interface{}) error {
o, n := diff.GetChange("json")
oldValue := o.(string)
newValue := n.(string)
if diff.HasChange("contract_id") ||
diff.HasChange("policy_id") ||
diff.HasChange("policyset_id") ||
!equalPolicyImage(oldValue, newValue) {
return diff.SetNewComputed("version")
}
return nil
}
func getRolloutDuration(d *schema.ResourceData) (*int, error) {
inputJSON, err := tools.GetStringValue("json", d)
if err != nil && !errors.Is(err, tools.ErrNotFound) {
return nil, err
}
if err == nil {
input := imaging.PolicyInputImage{}
err = json.Unmarshal([]byte(inputJSON), &input)
if err != nil {
return nil, err
}
return input.RolloutDuration, nil
}
return nil, nil
}