forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_aws_cloudwatch_event_rule.go
287 lines (254 loc) · 8.26 KB
/
resource_aws_cloudwatch_event_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
package aws
import (
"fmt"
"log"
"regexp"
"time"
"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/errwrap"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsCloudWatchEventRule() *schema.Resource {
return &schema.Resource{
Create: resourceAwsCloudWatchEventRuleCreate,
Read: resourceAwsCloudWatchEventRuleRead,
Update: resourceAwsCloudWatchEventRuleUpdate,
Delete: resourceAwsCloudWatchEventRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateCloudWatchEventRuleName,
},
"schedule_expression": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateMaxLength(256),
},
"event_pattern": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateEventPatternValue(2048),
StateFunc: func(v interface{}) string {
json, _ := normalizeJsonString(v)
return json
},
},
"description": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateMaxLength(512),
},
"role_arn": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateMaxLength(1600),
},
"is_enabled": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"arn": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAwsCloudWatchEventRuleCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
input, err := buildPutRuleInputStruct(d)
if err != nil {
return errwrap.Wrapf("Creating CloudWatch Event Rule failed: {{err}}", err)
}
log.Printf("[DEBUG] Creating CloudWatch Event Rule: %s", input)
// IAM Roles take some time to propagate
var out *events.PutRuleOutput
err = resource.Retry(30*time.Second, func() *resource.RetryError {
var err error
out, err = conn.PutRule(input)
pattern := regexp.MustCompile("cannot be assumed by principal '[a-z]+\\.amazonaws\\.com'\\.$")
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == "ValidationException" && pattern.MatchString(awsErr.Message()) {
log.Printf("[DEBUG] Retrying creation of CloudWatch Event Rule %q", *input.Name)
return resource.RetryableError(err)
}
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return errwrap.Wrapf("Creating CloudWatch Event Rule failed: {{err}}", err)
}
d.Set("arn", out.RuleArn)
d.SetId(d.Get("name").(string))
log.Printf("[INFO] CloudWatch Event Rule %q created", *out.RuleArn)
return resourceAwsCloudWatchEventRuleUpdate(d, meta)
}
func resourceAwsCloudWatchEventRuleRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
input := events.DescribeRuleInput{
Name: aws.String(d.Id()),
}
log.Printf("[DEBUG] Reading CloudWatch Event Rule: %s", input)
out, err := conn.DescribeRule(&input)
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == "ResourceNotFoundException" {
log.Printf("[WARN] Removing CloudWatch Event Rule %q because it's gone.", d.Id())
d.SetId("")
return nil
}
}
if err != nil {
return err
}
log.Printf("[DEBUG] Found Event Rule: %s", out)
d.Set("arn", out.Arn)
d.Set("description", out.Description)
if out.EventPattern != nil {
pattern, err := normalizeJsonString(*out.EventPattern)
if err != nil {
return errwrap.Wrapf("event pattern contains an invalid JSON: {{err}}", err)
}
d.Set("event_pattern", pattern)
}
d.Set("name", out.Name)
d.Set("role_arn", out.RoleArn)
d.Set("schedule_expression", out.ScheduleExpression)
boolState, err := getBooleanStateFromString(*out.State)
if err != nil {
return err
}
log.Printf("[DEBUG] Setting boolean state: %t", boolState)
d.Set("is_enabled", boolState)
return nil
}
func resourceAwsCloudWatchEventRuleUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
if d.HasChange("is_enabled") && d.Get("is_enabled").(bool) {
log.Printf("[DEBUG] Enabling CloudWatch Event Rule %q", d.Id())
_, err := conn.EnableRule(&events.EnableRuleInput{
Name: aws.String(d.Id()),
})
if err != nil {
return err
}
log.Printf("[DEBUG] CloudWatch Event Rule (%q) enabled", d.Id())
}
input, err := buildPutRuleInputStruct(d)
if err != nil {
return errwrap.Wrapf("Updating CloudWatch Event Rule failed: {{err}}", err)
}
log.Printf("[DEBUG] Updating CloudWatch Event Rule: %s", input)
// IAM Roles take some time to propagate
err = resource.Retry(30*time.Second, func() *resource.RetryError {
_, err := conn.PutRule(input)
pattern := regexp.MustCompile("cannot be assumed by principal '[a-z]+\\.amazonaws\\.com'\\.$")
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == "ValidationException" && pattern.MatchString(awsErr.Message()) {
log.Printf("[DEBUG] Retrying update of CloudWatch Event Rule %q", *input.Name)
return resource.RetryableError(err)
}
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return errwrap.Wrapf("Updating CloudWatch Event Rule failed: {{err}}", err)
}
if d.HasChange("is_enabled") && !d.Get("is_enabled").(bool) {
log.Printf("[DEBUG] Disabling CloudWatch Event Rule %q", d.Id())
_, err := conn.DisableRule(&events.DisableRuleInput{
Name: aws.String(d.Id()),
})
if err != nil {
return err
}
log.Printf("[DEBUG] CloudWatch Event Rule (%q) disabled", d.Id())
}
return resourceAwsCloudWatchEventRuleRead(d, meta)
}
func resourceAwsCloudWatchEventRuleDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
log.Printf("[INFO] Deleting CloudWatch Event Rule: %s", d.Id())
_, err := conn.DeleteRule(&events.DeleteRuleInput{
Name: aws.String(d.Id()),
})
if err != nil {
return fmt.Errorf("Error deleting CloudWatch Event Rule: %s", err)
}
log.Println("[INFO] CloudWatch Event Rule deleted")
d.SetId("")
return nil
}
func buildPutRuleInputStruct(d *schema.ResourceData) (*events.PutRuleInput, error) {
input := events.PutRuleInput{
Name: aws.String(d.Get("name").(string)),
}
if v, ok := d.GetOk("description"); ok {
input.Description = aws.String(v.(string))
}
if v, ok := d.GetOk("event_pattern"); ok {
pattern, err := normalizeJsonString(v)
if err != nil {
return nil, errwrap.Wrapf("event pattern contains an invalid JSON: {{err}}", err)
}
input.EventPattern = aws.String(pattern)
}
if v, ok := d.GetOk("role_arn"); ok {
input.RoleArn = aws.String(v.(string))
}
if v, ok := d.GetOk("schedule_expression"); ok {
input.ScheduleExpression = aws.String(v.(string))
}
input.State = aws.String(getStringStateFromBoolean(d.Get("is_enabled").(bool)))
return &input, nil
}
// State is represented as (ENABLED|DISABLED) in the API
func getBooleanStateFromString(state string) (bool, error) {
if state == "ENABLED" {
return true, nil
} else if state == "DISABLED" {
return false, nil
}
// We don't just blindly trust AWS as they tend to return
// unexpected values in similar cases (different casing etc.)
return false, fmt.Errorf("Failed converting state %q into boolean", state)
}
// State is represented as (ENABLED|DISABLED) in the API
func getStringStateFromBoolean(isEnabled bool) string {
if isEnabled {
return "ENABLED"
}
return "DISABLED"
}
func validateEventPatternValue(length int) schema.SchemaValidateFunc {
return func(v interface{}, k string) (ws []string, errors []error) {
json, err := normalizeJsonString(v)
if err != nil {
errors = append(errors, fmt.Errorf("%q contains an invalid JSON: %s", k, err))
// Invalid JSON? Return immediately,
// there is no need to collect other
// errors.
return
}
// Check whether the normalized JSON is within the given length.
if len(json) > length {
errors = append(errors, fmt.Errorf(
"%q cannot be longer than %d characters: %q", k, length, json))
}
return
}
}