-
Notifications
You must be signed in to change notification settings - Fork 132
/
resource_opsgenie_service_incident_rule.go
426 lines (377 loc) · 14 KB
/
resource_opsgenie_service_incident_rule.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
package opsgenie
import (
"context"
"fmt"
"github.com/opsgenie/opsgenie-go-sdk-v2/alert"
"github.com/opsgenie/opsgenie-go-sdk-v2/og"
"log"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
ogClient "github.com/opsgenie/opsgenie-go-sdk-v2/client"
"github.com/opsgenie/opsgenie-go-sdk-v2/service"
)
func resourceOpsGenieServiceIncidentRule() *schema.Resource {
return &schema.Resource{
Create: resourceOpsGenieServiceIncidentRuleCreate,
Read: handleNonExistentResource(resourceOpsGenieServiceIncidentRuleRead),
Update: resourceOpsGenieServiceIncidentRuleUpdate,
Delete: resourceOpsGenieServiceIncidentRuleDelete,
Importer: &schema.ResourceImporter{
State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
idParts := strings.Split(d.Id(), "/")
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
return nil, fmt.Errorf("Unexpected format of ID (%q), expected service_id/service_incident_rule_id", d.Id())
}
d.Set("service_id", idParts[0])
d.SetId(idParts[1])
return []*schema.ResourceData{d}, nil
},
},
Schema: map[string]*schema.Schema{
"service_id": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 130),
},
"incident_rule": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"condition_match_type": {
Type: schema.TypeString,
Optional: true,
Default: "match-all",
ValidateFunc: validation.StringInSlice([]string{"match-all", "match-any-condition", "match-all-conditions"}, false),
},
"conditions": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"field": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
"message", "description", "tags",
"extra-properties", "recipients", "teams", "priority",
"alias", "source", "entity", "actions", "details",
}, false),
},
"operation": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
"matches", "contains", "starts-with", "ends-with", "equals", "contains-key",
"contains-value", "greater-than", "less-than", "is-empty", "equals-ignore-whitespace",
}, false),
},
"key": {
Type: schema.TypeString,
Optional: true,
Description: "If 'field' is set as 'extra-properties', key could be used for key-value pair",
},
"not": {
Type: schema.TypeBool,
Optional: true,
Description: "Indicates behaviour of the given operation. Default value is false",
Default: false,
},
"expected_value": {
Type: schema.TypeString,
Optional: true,
Description: "User defined value that will be compared with alert field according to the operation. Default value is empty string",
ValidateFunc: validation.StringLenBetween(1, 15000),
},
},
},
},
"incident_properties": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"message": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 130),
},
"tags": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"details": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"description": {
Type: schema.TypeString,
Optional: true,
Default: "{{description}}",
ValidateFunc: validation.StringLenBetween(1, 10000),
},
"priority": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"P1", "P2", "P3", "P4", "P5"}, false),
},
"stakeholder_properties": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"message": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 15000),
},
},
},
},
},
},
},
},
},
},
},
}
}
func resourceOpsGenieServiceIncidentRuleCreate(d *schema.ResourceData, meta interface{}) error {
client, err := service.NewClient(meta.(*OpsgenieClient).client.Config)
if err != nil {
return err
}
service_id := d.Get("service_id").(string)
createRequest := &service.CreateIncidentRuleRequest{
ServiceId: service_id,
}
incident_rule := d.Get("incident_rule").([]interface{})
for _, v := range incident_rule {
config := v.(map[string]interface{})
createRequest.ConditionMatchType = og.ConditionMatchType(config["condition_match_type"].(string))
createRequest.Conditions = expandOpsGenieServiceIncidentRuleConditions(config["conditions"].(*schema.Set))
createRequest.IncidentProperties = expandOpsGenieServiceIncidentRuleIncidentProperties(config["incident_properties"].([]interface{}))
}
log.Printf("[INFO] Creating OpsGenie Service Incident Rule for service '%s'", d.Get("service_id").(string))
result, err := client.CreateIncidentRule(context.Background(), createRequest)
if err != nil {
return err
}
d.SetId(result.Id)
return resourceOpsGenieServiceIncidentRuleRead(d, meta)
}
func resourceOpsGenieServiceIncidentRuleRead(d *schema.ResourceData, meta interface{}) error {
client, err := service.NewClient(meta.(*OpsgenieClient).client.Config)
if err != nil {
return err
}
service_id := d.Get("service_id").(string)
incident_rule_id := d.Id()
log.Printf("[INFO] Reading OpsGenie Service Incident Rule for service: '%s' for rule ID: '%s'", service_id, incident_rule_id)
incident_rule_res, err := client.GetIncidentRules(context.Background(), &service.GetIncidentRulesRequest{
ServiceId: service_id,
})
if err != nil {
x := err.(*ogClient.ApiError)
if x.StatusCode == 404 {
log.Printf("[WARN] Removing Service Incident Rule because it's gone %s", service_id)
d.SetId("")
return nil
}
}
incidentRuleFound := false
for _, v := range incident_rule_res.IncidentRule {
if v.Id == incident_rule_id {
d.Set("service_id", service_id)
d.Set("incident_rule", flattenOpsGenieServiceIncidentRules(v))
incidentRuleFound = true
}
}
if !incidentRuleFound {
log.Printf("[WARN] Incident Rule with id: %s not found", d.Id())
d.SetId("")
}
return nil
}
func resourceOpsGenieServiceIncidentRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client, err := service.NewClient(meta.(*OpsgenieClient).client.Config)
if err != nil {
return err
}
service_id := d.Get("service_id").(string)
incident_rule_id := d.Id()
updateRequest := &service.UpdateIncidentRuleRequest{
ServiceId: service_id,
IncidentRuleId: incident_rule_id,
}
incident_rule := d.Get("incident_rule").([]interface{})
for _, v := range incident_rule {
config := v.(map[string]interface{})
updateRequest.ConditionMatchType = og.ConditionMatchType(config["condition_match_type"].(string))
updateRequest.Conditions = expandOpsGenieServiceIncidentRuleConditions(config["conditions"].(*schema.Set))
updateRequest.IncidentProperties = expandOpsGenieServiceIncidentRuleIncidentProperties(config["incident_properties"].([]interface{}))
}
log.Printf("[INFO] Updating Service Incident Rule for service: '%s' for rule ID: '%s'", service_id, incident_rule_id)
_, err = client.UpdateIncidentRule(context.Background(), updateRequest)
if err != nil {
return err
}
return nil
}
func resourceOpsGenieServiceIncidentRuleDelete(d *schema.ResourceData, meta interface{}) error {
service_id := d.Get("service_id").(string)
incident_rule_id := d.Id()
log.Printf("[INFO] Deleting OpsGenie ervice Incident Rule for service: '%s' for rule ID: '%s'", service_id, incident_rule_id)
client, err := service.NewClient(meta.(*OpsgenieClient).client.Config)
if err != nil {
return err
}
deleteRequest := &service.DeleteIncidentRuleRequest{
ServiceId: service_id,
IncidentRuleId: incident_rule_id,
}
_, err = client.DeleteIncidentRule(context.Background(), deleteRequest)
if err != nil {
return err
}
return nil
}
func flattenOpsGenieServiceIncidentRules(input service.IncidentRuleResult) []map[string]interface{} {
incident_rule := make(map[string]interface{})
conditions_list := make([]map[string]interface{}, 0, len(input.Conditions))
for _, v := range input.Conditions {
conditions := flattenOpsGenieServiceIncidentRuleConditions(v)
conditions_list = append(conditions_list, conditions)
}
incident_rule["conditions"] = conditions_list
incident_rule["condition_match_type"] = input.ConditionMatchType
incident_rule["incident_properties"] = flattenOpsGenieServiceIncidentRuleIncidentProperties(input.IncidentProperties)
return []map[string]interface{}{incident_rule}
}
func expandOpsGenieServiceIncidentRuleConditions(input *schema.Set) []og.Condition {
conditions := make([]og.Condition, 0, input.Len())
if input == nil {
return conditions
}
for _, v := range input.List() {
condition := og.Condition{}
config := v.(map[string]interface{})
not_value := config["not"].(bool)
condition.Field = og.ConditionFieldType(config["field"].(string))
condition.Operation = og.ConditionOperation(config["operation"].(string))
condition.IsNot = ¬_value
condition.ExpectedValue = config["expected_value"].(string)
if condition.Field == og.ExtraProperties {
key := config["key"].(string)
if key != "" {
condition.Key = config["key"].(string)
}
}
conditions = append(conditions, condition)
}
return conditions
}
func expandOpsGenieServiceIncidentRuleIncidentProperties(input []interface{}) service.IncidentProperties {
incident_properties := service.IncidentProperties{}
for _, v := range input {
config := v.(map[string]interface{})
incident_properties.Message = config["message"].(string)
if config["tags"].(*schema.Set).Len() > 0 {
incident_properties.Tags = flattenOpsgenieServiceIncidentRuleRequestTags(config["tags"].(*schema.Set))
}
if config["details"].(map[string]interface{}) != nil {
incident_properties.Details = flattenOpsgenieServiceIncidentRuleRequestDetails(config["details"].(map[string]interface{}))
}
incident_properties.Description = config["description"].(string)
incident_properties.Priority = alert.Priority(config["priority"].(string))
incident_properties.StakeholderProperties = expandOpsGenieServiceIncidentRuleStakeholderProperties(config["stakeholder_properties"].([]interface{}))
}
return incident_properties
}
func expandOpsGenieServiceIncidentRuleStakeholderProperties(input []interface{}) service.StakeholderProperties {
stakeholder_properties := service.StakeholderProperties{}
if input == nil {
return stakeholder_properties
}
for _, v := range input {
config := v.(map[string]interface{})
enable := config["enable"].(bool)
stakeholder_properties.Enable = &enable
stakeholder_properties.Message = config["message"].(string)
stakeholder_properties.Description = config["description"].(string)
}
return stakeholder_properties
}
func flattenOpsgenieServiceIncidentRuleRequestTags(input *schema.Set) []string {
tags := make([]string, len(input.List()))
if input == nil {
return tags
}
for k, v := range input.List() {
tags[k] = v.(string)
}
return tags
}
func flattenOpsgenieServiceIncidentRuleRequestDetails(input map[string]interface{}) map[string]string {
details := make(map[string]string)
if input == nil {
return details
}
for k, v := range input {
details[k] = v.(string)
}
return details
}
func flattenOpsGenieServiceIncidentRuleConditions(input og.Condition) map[string]interface{} {
condition := make(map[string]interface{})
condition["field"] = input.Field
condition["operation"] = input.Operation
condition["not"] = *input.IsNot
condition["expected_value"] = input.ExpectedValue
if input.Key != "" {
condition["key"] = input.Key
}
return condition
}
func flattenOpsGenieServiceIncidentRuleIncidentProperties(input service.IncidentProperties) []map[string]interface{} {
incident_properties := make(map[string]interface{})
if len(input.Tags) > 0 {
incident_properties["tags"] = schema.NewSet(schema.HashString, convertStringSliceToInterfaceSlice(input.Tags))
}
if len(input.Details) > 0 {
incident_properties["details"] = convertStringMapToInterfaceMap(input.Details)
}
if input.Description != "" {
incident_properties["description"] = input.Description
}
incident_properties["message"] = input.Message
incident_properties["priority"] = input.Priority
incident_properties["stakeholder_properties"] = flattenOpsGenieServiceIncidentRuleStakeholderProperties(input.StakeholderProperties)
return []map[string]interface{}{incident_properties}
}
func flattenOpsGenieServiceIncidentRuleStakeholderProperties(input service.StakeholderProperties) []map[string]interface{} {
stakeholders_properties := make(map[string]interface{})
stakeholders_properties["enable"] = *input.Enable
stakeholders_properties["message"] = input.Message
if input.Description != "" {
stakeholders_properties["description"] = input.Description
}
return []map[string]interface{}{stakeholders_properties}
}