/
resource_aws_sns_platform_application.go
288 lines (250 loc) · 8.61 KB
/
resource_aws_sns_platform_application.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
package aws
import (
"crypto/sha256"
"fmt"
"log"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/service/sns"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
var snsPlatformRequiresPlatformPrincipal = map[string]bool{
"APNS": true,
"APNS_SANDBOX": true,
}
// Mutable attributes
// http://docs.aws.amazon.com/sns/latest/api/API_SetPlatformApplicationAttributes.html
var snsPlatformApplicationAttributeMap = map[string]string{
"event_delivery_failure_topic_arn": "EventDeliveryFailure",
"event_endpoint_created_topic_arn": "EventEndpointCreated",
"event_endpoint_deleted_topic_arn": "EventEndpointDeleted",
"event_endpoint_updated_topic_arn": "EventEndpointUpdated",
"failure_feedback_role_arn": "FailureFeedbackRoleArn",
"platform_principal": "PlatformPrincipal",
"success_feedback_role_arn": "SuccessFeedbackRoleArn",
"success_feedback_sample_rate": "SuccessFeedbackSampleRate",
}
func resourceAwsSnsPlatformApplication() *schema.Resource {
return &schema.Resource{
Create: resourceAwsSnsPlatformApplicationCreate,
Read: resourceAwsSnsPlatformApplicationRead,
Update: resourceAwsSnsPlatformApplicationUpdate,
Delete: resourceAwsSnsPlatformApplicationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
CustomizeDiff: func(diff *schema.ResourceDiff, v interface{}) error {
return validateAwsSnsPlatformApplication(diff)
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"platform": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"platform_credential": {
Type: schema.TypeString,
Required: true,
StateFunc: hashSum,
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
"event_delivery_failure_topic_arn": {
Type: schema.TypeString,
Optional: true,
},
"event_endpoint_created_topic_arn": {
Type: schema.TypeString,
Optional: true,
},
"event_endpoint_deleted_topic_arn": {
Type: schema.TypeString,
Optional: true,
},
"event_endpoint_updated_topic_arn": {
Type: schema.TypeString,
Optional: true,
},
"failure_feedback_role_arn": {
Type: schema.TypeString,
Optional: true,
},
"platform_principal": {
Type: schema.TypeString,
Optional: true,
StateFunc: hashSum,
},
"success_feedback_role_arn": {
Type: schema.TypeString,
Optional: true,
},
"success_feedback_sample_rate": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAwsSnsPlatformApplicationCreate(d *schema.ResourceData, meta interface{}) error {
snsconn := meta.(*AWSClient).snsconn
attributes := make(map[string]*string)
name := d.Get("name").(string)
platform := d.Get("platform").(string)
attributes["PlatformCredential"] = aws.String(d.Get("platform_credential").(string))
if v, ok := d.GetOk("platform_principal"); ok {
attributes["PlatformPrincipal"] = aws.String(v.(string))
}
req := &sns.CreatePlatformApplicationInput{
Name: aws.String(name),
Platform: aws.String(platform),
Attributes: attributes,
}
log.Printf("[DEBUG] SNS create application: %s", req)
output, err := snsconn.CreatePlatformApplication(req)
if err != nil {
return fmt.Errorf("Error creating SNS platform application: %s", err)
}
d.SetId(*output.PlatformApplicationArn)
return resourceAwsSnsPlatformApplicationUpdate(d, meta)
}
func resourceAwsSnsPlatformApplicationUpdate(d *schema.ResourceData, meta interface{}) error {
snsconn := meta.(*AWSClient).snsconn
attributes := make(map[string]*string)
for k := range resourceAwsSnsPlatformApplication().Schema {
if attrKey, ok := snsPlatformApplicationAttributeMap[k]; ok {
if d.HasChange(k) {
log.Printf("[DEBUG] Updating %s", attrKey)
_, n := d.GetChange(k)
attributes[attrKey] = aws.String(n.(string))
}
}
}
if d.HasChange("platform_credential") {
attributes["PlatformCredential"] = aws.String(d.Get("platform_credential").(string))
// If the platform requires a principal it must also be specified, even if it didn't change
// since credential is stored as a hash, the only way to update principal is to update both
// as they must be specified together in the request.
if v, ok := d.GetOk("platform_principal"); ok {
attributes["PlatformPrincipal"] = aws.String(v.(string))
}
}
// Make API call to update attributes
req := &sns.SetPlatformApplicationAttributesInput{
PlatformApplicationArn: aws.String(d.Id()),
Attributes: attributes,
}
err := resource.Retry(1*time.Minute, func() *resource.RetryError {
_, err := snsconn.SetPlatformApplicationAttributes(req)
if err != nil {
if isAWSErr(err, sns.ErrCodeInvalidParameterException, "is not a valid role to allow SNS to write to Cloudwatch Logs") {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return fmt.Errorf("Error updating SNS platform application: %s", err)
}
return resourceAwsSnsPlatformApplicationRead(d, meta)
}
func resourceAwsSnsPlatformApplicationRead(d *schema.ResourceData, meta interface{}) error {
snsconn := meta.(*AWSClient).snsconn
// There is no SNS Describe/GetPlatformApplication to fetch attributes like name and platform
// We will use the ID, which should be a platform application ARN, to:
// * Validate its an appropriate ARN on import
// * Parse out the name and platform
arn, name, platform, err := decodeResourceAwsSnsPlatformApplicationID(d.Id())
if err != nil {
return err
}
d.Set("arn", arn)
d.Set("name", name)
d.Set("platform", platform)
attributeOutput, err := snsconn.GetPlatformApplicationAttributes(&sns.GetPlatformApplicationAttributesInput{
PlatformApplicationArn: aws.String(arn),
})
if err != nil {
if isAWSErr(err, sns.ErrCodeNotFoundException, "") {
log.Printf("[WARN] SNS Platform Application (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
return err
}
if attributeOutput.Attributes != nil && len(attributeOutput.Attributes) > 0 {
attrmap := attributeOutput.Attributes
resource := *resourceAwsSnsPlatformApplication()
// iKey = internal struct key, oKey = AWS Attribute Map key
for iKey, oKey := range snsPlatformApplicationAttributeMap {
log.Printf("[DEBUG] Updating %s => %s", iKey, oKey)
if attrmap[oKey] != nil {
// Some of the fetched attributes are stateful properties such as
// the number of subscriptions, the owner, etc. skip those
if resource.Schema[iKey] != nil {
value := *attrmap[oKey]
log.Printf("[DEBUG] Updating %s => %s -> %s", iKey, oKey, value)
d.Set(iKey, *attrmap[oKey])
}
}
}
}
return nil
}
func resourceAwsSnsPlatformApplicationDelete(d *schema.ResourceData, meta interface{}) error {
snsconn := meta.(*AWSClient).snsconn
log.Printf("[DEBUG] SNS Delete Application: %s", d.Id())
_, err := snsconn.DeletePlatformApplication(&sns.DeletePlatformApplicationInput{
PlatformApplicationArn: aws.String(d.Id()),
})
return err
}
func decodeResourceAwsSnsPlatformApplicationID(input string) (arnS, name, platform string, err error) {
platformApplicationArn, err := arn.Parse(input)
if err != nil {
err = fmt.Errorf(
"SNS Platform Application ID must be of the form "+
"arn:PARTITION:sns:REGION:ACCOUNTID:app/PLATFORM/NAME, "+
"was provided %q and received error: %s", input, err)
return
}
platformApplicationArnResourceParts := strings.Split(platformApplicationArn.Resource, "/")
if len(platformApplicationArnResourceParts) != 3 || platformApplicationArnResourceParts[0] != "app" {
err = fmt.Errorf(
"SNS Platform Application ID must be of the form "+
"arn:PARTITION:sns:REGION:ACCOUNTID:app/PLATFORM/NAME, "+
"was provided: %s", input)
return
}
arnS = platformApplicationArn.String()
name = platformApplicationArnResourceParts[2]
platform = platformApplicationArnResourceParts[1]
return
}
func hashSum(contents interface{}) string {
return fmt.Sprintf("%x", sha256.Sum256([]byte(contents.(string))))
}
func validateAwsSnsPlatformApplication(d *schema.ResourceDiff) error {
platform := d.Get("platform").(string)
if snsPlatformRequiresPlatformPrincipal[platform] {
if v, ok := d.GetOk("platform_principal"); ok {
value := v.(string)
if len(value) == 0 {
return fmt.Errorf("platform_principal must be non-empty when platform = %s", platform)
}
return nil
}
return fmt.Errorf("platform_principal is required when platform = %s", platform)
}
return nil
}