forked from hashicorp/terraform-provider-aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_aws_cloudwatch_event_target.go
399 lines (329 loc) · 10.8 KB
/
resource_aws_cloudwatch_event_target.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
package aws
import (
"fmt"
"log"
"math"
"regexp"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
events "github.com/aws/aws-sdk-go/service/cloudwatchevents"
"github.com/hashicorp/terraform/helper/validation"
)
func resourceAwsCloudWatchEventTarget() *schema.Resource {
return &schema.Resource{
Create: resourceAwsCloudWatchEventTargetCreate,
Read: resourceAwsCloudWatchEventTargetRead,
Update: resourceAwsCloudWatchEventTargetUpdate,
Delete: resourceAwsCloudWatchEventTargetDelete,
Schema: map[string]*schema.Schema{
"rule": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateCloudWatchEventRuleName,
},
"target_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validateCloudWatchEventTargetId,
},
"arn": {
Type: schema.TypeString,
Required: true,
},
"input": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"input_path"},
// We could be normalizing the JSON here,
// but for built-in targets input may not be JSON
},
"input_path": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"input"},
},
"role_arn": {
Type: schema.TypeString,
Optional: true,
},
"run_command_targets": {
Type: schema.TypeList,
Optional: true,
MaxItems: 5,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 128),
},
"values": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"ecs_target": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"task_count": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(1, math.MaxInt32),
},
"task_definition_arn": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 1600),
},
},
},
},
"input_transformer": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"input_paths": {
Type: schema.TypeMap,
Optional: true,
},
"input_template": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 8192),
},
},
},
},
},
}
}
func resourceAwsCloudWatchEventTargetCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
rule := d.Get("rule").(string)
var targetId string
if v, ok := d.GetOk("target_id"); ok {
targetId = v.(string)
} else {
targetId = resource.UniqueId()
d.Set("target_id", targetId)
}
input := buildPutTargetInputStruct(d)
log.Printf("[DEBUG] Creating CloudWatch Event Target: %s", input)
out, err := conn.PutTargets(input)
if err != nil {
return fmt.Errorf("Creating CloudWatch Event Target failed: %s", err)
}
if len(out.FailedEntries) > 0 {
return fmt.Errorf("Creating CloudWatch Event Target failed: %s",
out.FailedEntries)
}
id := rule + "-" + targetId
d.SetId(id)
log.Printf("[INFO] CloudWatch Event Target %q created", d.Id())
return resourceAwsCloudWatchEventTargetRead(d, meta)
}
func resourceAwsCloudWatchEventTargetRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
t, err := findEventTargetById(
d.Get("target_id").(string),
d.Get("rule").(string),
nil, conn)
if err != nil {
if regexp.MustCompile(" not found$").MatchString(err.Error()) {
log.Printf("[WARN] Removing CloudWatch Event Target %q because it's gone.", d.Id())
d.SetId("")
return nil
}
if awsErr, ok := err.(awserr.Error); ok {
// This should never happen, but it's useful
// for recovering from https://github.com/hashicorp/terraform/issues/5389
if awsErr.Code() == "ValidationException" {
log.Printf("[WARN] Removing CloudWatch Event Target %q because it never existed.", d.Id())
d.SetId("")
return nil
}
if awsErr.Code() == "ResourceNotFoundException" {
log.Printf("[WARN] CloudWatch Event Target (%q) not found. Removing it from state.", d.Id())
d.SetId("")
return nil
}
}
return err
}
log.Printf("[DEBUG] Found Event Target: %s", t)
d.Set("arn", t.Arn)
d.Set("target_id", t.Id)
d.Set("input", t.Input)
d.Set("input_path", t.InputPath)
d.Set("role_arn", t.RoleArn)
if t.RunCommandParameters != nil {
if err := d.Set("run_command_targets", flattenAwsCloudWatchEventTargetRunParameters(t.RunCommandParameters)); err != nil {
return fmt.Errorf("[DEBUG] Error setting run_command_targets error: %#v", err)
}
}
if t.EcsParameters != nil {
if err := d.Set("ecs_target", flattenAwsCloudWatchEventTargetEcsParameters(t.EcsParameters)); err != nil {
return fmt.Errorf("[DEBUG] Error setting ecs_target error: %#v", err)
}
}
if t.InputTransformer != nil {
if err := d.Set("input_transformer", flattenAwsCloudWatchInputTransformer(t.InputTransformer)); err != nil {
return fmt.Errorf("[DEBUG] Error setting input_transformer error: %#v", err)
}
}
return nil
}
func findEventTargetById(id, rule string, nextToken *string, conn *events.CloudWatchEvents) (*events.Target, error) {
input := events.ListTargetsByRuleInput{
Rule: aws.String(rule),
NextToken: nextToken,
Limit: aws.Int64(100), // Set limit to allowed maximum to prevent API throttling
}
log.Printf("[DEBUG] Reading CloudWatch Event Target: %s", input)
out, err := conn.ListTargetsByRule(&input)
if err != nil {
return nil, err
}
for _, t := range out.Targets {
if *t.Id == id {
return t, nil
}
}
if out.NextToken != nil {
return findEventTargetById(id, rule, nextToken, conn)
}
return nil, fmt.Errorf("CloudWatch Event Target %q (%q) not found", id, rule)
}
func resourceAwsCloudWatchEventTargetUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
input := buildPutTargetInputStruct(d)
log.Printf("[DEBUG] Updating CloudWatch Event Target: %s", input)
_, err := conn.PutTargets(input)
if err != nil {
return fmt.Errorf("Updating CloudWatch Event Target failed: %s", err)
}
return resourceAwsCloudWatchEventTargetRead(d, meta)
}
func resourceAwsCloudWatchEventTargetDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
input := events.RemoveTargetsInput{
Ids: []*string{aws.String(d.Get("target_id").(string))},
Rule: aws.String(d.Get("rule").(string)),
}
log.Printf("[INFO] Deleting CloudWatch Event Target: %s", input)
_, err := conn.RemoveTargets(&input)
if err != nil {
return fmt.Errorf("Error deleting CloudWatch Event Target: %s", err)
}
log.Println("[INFO] CloudWatch Event Target deleted")
d.SetId("")
return nil
}
func buildPutTargetInputStruct(d *schema.ResourceData) *events.PutTargetsInput {
e := &events.Target{
Arn: aws.String(d.Get("arn").(string)),
Id: aws.String(d.Get("target_id").(string)),
}
if v, ok := d.GetOk("input"); ok {
e.Input = aws.String(v.(string))
}
if v, ok := d.GetOk("input_path"); ok {
e.InputPath = aws.String(v.(string))
}
if v, ok := d.GetOk("role_arn"); ok {
e.RoleArn = aws.String(v.(string))
}
if v, ok := d.GetOk("run_command_targets"); ok {
e.RunCommandParameters = expandAwsCloudWatchEventTargetRunParameters(v.([]interface{}))
}
if v, ok := d.GetOk("ecs_target"); ok {
e.EcsParameters = expandAwsCloudWatchEventTargetEcsParameters(v.([]interface{}))
}
if v, ok := d.GetOk("input_transformer"); ok {
e.InputTransformer = expandAwsCloudWatchEventTransformerParameters(v.([]interface{}))
}
input := events.PutTargetsInput{
Rule: aws.String(d.Get("rule").(string)),
Targets: []*events.Target{e},
}
return &input
}
func expandAwsCloudWatchEventTargetRunParameters(config []interface{}) *events.RunCommandParameters {
commands := make([]*events.RunCommandTarget, 0)
for _, c := range config {
param := c.(map[string]interface{})
command := &events.RunCommandTarget{
Key: aws.String(param["key"].(string)),
Values: expandStringList(param["values"].([]interface{})),
}
commands = append(commands, command)
}
command := &events.RunCommandParameters{
RunCommandTargets: commands,
}
return command
}
func expandAwsCloudWatchEventTargetEcsParameters(config []interface{}) *events.EcsParameters {
ecsParameters := &events.EcsParameters{}
for _, c := range config {
param := c.(map[string]interface{})
ecsParameters.TaskCount = aws.Int64(int64(param["task_count"].(int)))
ecsParameters.TaskDefinitionArn = aws.String(param["task_definition_arn"].(string))
}
return ecsParameters
}
func expandAwsCloudWatchEventTransformerParameters(config []interface{}) *events.InputTransformer {
transformerParameters := &events.InputTransformer{}
inputPathsMaps := map[string]*string{}
for _, c := range config {
param := c.(map[string]interface{})
inputPaths := param["input_paths"].(map[string]interface{})
for k, v := range inputPaths {
inputPathsMaps[k] = aws.String(v.(string))
}
transformerParameters.InputTemplate = aws.String(param["input_template"].(string))
}
transformerParameters.InputPathsMap = inputPathsMaps
return transformerParameters
}
func flattenAwsCloudWatchEventTargetRunParameters(runCommand *events.RunCommandParameters) []map[string]interface{} {
result := make([]map[string]interface{}, 0)
for _, x := range runCommand.RunCommandTargets {
config := make(map[string]interface{})
config["key"] = *x.Key
config["values"] = flattenStringList(x.Values)
result = append(result, config)
}
return result
}
func flattenAwsCloudWatchEventTargetEcsParameters(ecsParameters *events.EcsParameters) []map[string]interface{} {
config := make(map[string]interface{})
config["task_count"] = *ecsParameters.TaskCount
config["task_definition_arn"] = *ecsParameters.TaskDefinitionArn
result := []map[string]interface{}{config}
return result
}
func flattenAwsCloudWatchInputTransformer(inputTransformer *events.InputTransformer) []map[string]interface{} {
config := make(map[string]interface{})
inputPathsMap := make(map[string]string)
for k, v := range inputTransformer.InputPathsMap {
inputPathsMap[k] = *v
}
config["input_template"] = *inputTransformer.InputTemplate
config["input_paths"] = inputPathsMap
result := []map[string]interface{}{config}
return result
}