terraform/builtin/providers/aws/resource_aws_sns_topic.go

222 lines
6.0 KiB
Go
Raw Normal View History

2015-05-15 01:17:18 +02:00
package aws
import (
"fmt"
"log"
"strings"
"time"
2015-05-15 01:17:18 +02:00
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/sns"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
2015-05-15 01:17:18 +02:00
)
// Mutable attributes
var SNSAttributeMap = map[string]string{
2016-04-21 17:18:04 +02:00
"arn": "TopicArn",
"display_name": "DisplayName",
"policy": "Policy",
2015-05-15 01:17:18 +02:00
"delivery_policy": "DeliveryPolicy",
}
func resourceAwsSnsTopic() *schema.Resource {
return &schema.Resource{
Create: resourceAwsSnsTopicCreate,
Read: resourceAwsSnsTopicRead,
Update: resourceAwsSnsTopicUpdate,
Delete: resourceAwsSnsTopicDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
2015-05-15 01:17:18 +02:00
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"display_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: false,
2015-05-15 01:17:18 +02:00
},
"policy": &schema.Schema{
provider/aws: Add DiffSupressionFunc to `aws_elasticsearch_domain`, `aws_sqs_queue` and `aws_sns_topic` ``` SQS Queue Tests: %make testacc TEST=./builtin/providers/aws TESTARGS='-run=TestAccAWSSQSQueue' 2 ↵ ✹ ==> Checking that code complies with gofmt requirements... go generate $(go list ./... | grep -v /terraform/vendor/) 2016/09/05 09:46:04 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/aws -v -run=TestAccAWSSQSQueue -timeout 120m === RUN TestAccAWSSQSQueue_importBasic --- PASS: TestAccAWSSQSQueue_importBasic (18.99s) === RUN TestAccAWSSQSQueue_basic --- PASS: TestAccAWSSQSQueue_basic (44.31s) === RUN TestAccAWSSQSQueue_policy --- PASS: TestAccAWSSQSQueue_policy (32.76s) === RUN TestAccAWSSQSQueue_redrivePolicy --- PASS: TestAccAWSSQSQueue_redrivePolicy (66.42s) === RUN TestAccAWSSQSQueue_Policybasic --- PASS: TestAccAWSSQSQueue_Policybasic (32.40s) PASS ok github.com/hashicorp/terraform/builtin/providers/aws 194.895s ``` SNS Topic Tests: % make testacc TEST=./builtin/providers/aws % TESTARGS='-run=TestAccAWSSNSTopic_' ==> Checking that code complies with gofmt requirements... go generate $(go list ./... | grep -v /terraform/vendor/) 2016/09/04 22:56:26 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/aws -v -run=TestAccAWSSNSTopic_ -timeout 120m === RUN TestAccAWSSNSTopic_importBasic --- PASS: TestAccAWSSNSTopic_importBasic (17.67s) === RUN TestAccAWSSNSTopic_basic --- PASS: TestAccAWSSNSTopic_basic (17.92s) === RUN TestAccAWSSNSTopic_policy --- PASS: TestAccAWSSNSTopic_policy (20.99s) === RUN TestAccAWSSNSTopic_withIAMRole --- PASS: TestAccAWSSNSTopic_withIAMRole (26.51s) PASS ok github.com/hashicorp/terraform/builtin/providers/aws 83.112s ```
2016-09-04 11:04:10 +02:00
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validateJsonString,
provider/aws: Add DiffSupressionFunc to `aws_elasticsearch_domain`, `aws_sqs_queue` and `aws_sns_topic` ``` SQS Queue Tests: %make testacc TEST=./builtin/providers/aws TESTARGS='-run=TestAccAWSSQSQueue' 2 ↵ ✹ ==> Checking that code complies with gofmt requirements... go generate $(go list ./... | grep -v /terraform/vendor/) 2016/09/05 09:46:04 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/aws -v -run=TestAccAWSSQSQueue -timeout 120m === RUN TestAccAWSSQSQueue_importBasic --- PASS: TestAccAWSSQSQueue_importBasic (18.99s) === RUN TestAccAWSSQSQueue_basic --- PASS: TestAccAWSSQSQueue_basic (44.31s) === RUN TestAccAWSSQSQueue_policy --- PASS: TestAccAWSSQSQueue_policy (32.76s) === RUN TestAccAWSSQSQueue_redrivePolicy --- PASS: TestAccAWSSQSQueue_redrivePolicy (66.42s) === RUN TestAccAWSSQSQueue_Policybasic --- PASS: TestAccAWSSQSQueue_Policybasic (32.40s) PASS ok github.com/hashicorp/terraform/builtin/providers/aws 194.895s ``` SNS Topic Tests: % make testacc TEST=./builtin/providers/aws % TESTARGS='-run=TestAccAWSSNSTopic_' ==> Checking that code complies with gofmt requirements... go generate $(go list ./... | grep -v /terraform/vendor/) 2016/09/04 22:56:26 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/aws -v -run=TestAccAWSSNSTopic_ -timeout 120m === RUN TestAccAWSSNSTopic_importBasic --- PASS: TestAccAWSSNSTopic_importBasic (17.67s) === RUN TestAccAWSSNSTopic_basic --- PASS: TestAccAWSSNSTopic_basic (17.92s) === RUN TestAccAWSSNSTopic_policy --- PASS: TestAccAWSSNSTopic_policy (20.99s) === RUN TestAccAWSSNSTopic_withIAMRole --- PASS: TestAccAWSSNSTopic_withIAMRole (26.51s) PASS ok github.com/hashicorp/terraform/builtin/providers/aws 83.112s ```
2016-09-04 11:04:10 +02:00
DiffSuppressFunc: suppressEquivalentAwsPolicyDiffs,
StateFunc: func(v interface{}) string {
json, _ := normalizeJsonString(v)
return json
},
2015-05-15 01:17:18 +02:00
},
"delivery_policy": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: false,
2015-05-15 01:17:18 +02:00
},
"arn": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
2015-05-15 01:17:18 +02:00
},
}
}
func resourceAwsSnsTopicCreate(d *schema.ResourceData, meta interface{}) error {
snsconn := meta.(*AWSClient).snsconn
name := d.Get("name").(string)
log.Printf("[DEBUG] SNS create topic: %s", name)
req := &sns.CreateTopicInput{
Name: aws.String(name),
}
output, err := snsconn.CreateTopic(req)
if err != nil {
return fmt.Errorf("Error creating SNS topic: %s", err)
}
d.SetId(*output.TopicArn)
2015-05-15 01:17:18 +02:00
// Write the ARN to the 'arn' field for export
d.Set("arn", *output.TopicArn)
2015-05-15 01:17:18 +02:00
return resourceAwsSnsTopicUpdate(d, meta)
}
func resourceAwsSnsTopicUpdate(d *schema.ResourceData, meta interface{}) error {
r := *resourceAwsSnsTopic()
2015-05-15 01:17:18 +02:00
for k, _ := range r.Schema {
2015-05-15 01:17:18 +02:00
if attrKey, ok := SNSAttributeMap[k]; ok {
if d.HasChange(k) {
log.Printf("[DEBUG] Updating %s", attrKey)
_, n := d.GetChange(k)
// Ignore an empty policy
if !(k == "policy" && n == "") {
// Make API call to update attributes
req := sns.SetTopicAttributesInput{
TopicArn: aws.String(d.Id()),
AttributeName: aws.String(attrKey),
2015-05-15 01:17:18 +02:00
AttributeValue: aws.String(n.(string)),
}
// Retry the update in the event of an eventually consistent style of
// error, where say an IAM resource is successfully created but not
// actually available. See https://github.com/hashicorp/terraform/issues/3660
log.Printf("[DEBUG] Updating SNS Topic (%s) attributes request: %s", d.Id(), req)
stateConf := &resource.StateChangeConf{
Pending: []string{"retrying"},
Target: []string{"success"},
Refresh: resourceAwsSNSUpdateRefreshFunc(meta, req),
Timeout: 1 * time.Minute,
MinTimeout: 3 * time.Second,
}
_, err := stateConf.WaitForState()
if err != nil {
return err
}
2015-05-15 01:17:18 +02:00
}
}
}
}
return resourceAwsSnsTopicRead(d, meta)
}
func resourceAwsSNSUpdateRefreshFunc(
meta interface{}, params sns.SetTopicAttributesInput) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
snsconn := meta.(*AWSClient).snsconn
if _, err := snsconn.SetTopicAttributes(&params); err != nil {
log.Printf("[WARN] Erroring updating topic attributes: %s", err)
if awsErr, ok := err.(awserr.Error); ok {
// if the error contains the PrincipalNotFound message, we can retry
if strings.Contains(awsErr.Message(), "PrincipalNotFound") {
log.Printf("[DEBUG] Retrying AWS SNS Topic Update: %s", params)
return nil, "retrying", nil
}
}
return nil, "failed", err
}
return 42, "success", nil
}
}
2015-05-15 01:17:18 +02:00
func resourceAwsSnsTopicRead(d *schema.ResourceData, meta interface{}) error {
snsconn := meta.(*AWSClient).snsconn
attributeOutput, err := snsconn.GetTopicAttributes(&sns.GetTopicAttributesInput{
TopicArn: aws.String(d.Id()),
2015-05-15 01:17:18 +02:00
})
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NotFound" {
log.Printf("[WARN] SNS Topic (%s) not found, error code (404)", d.Id())
d.SetId("")
return nil
}
2015-05-15 01:17:18 +02:00
return err
}
if attributeOutput.Attributes != nil && len(attributeOutput.Attributes) > 0 {
attrmap := attributeOutput.Attributes
2015-05-15 01:17:18 +02:00
resource := *resourceAwsSnsTopic()
// iKey = internal struct key, oKey = AWS Attribute Map key
for iKey, oKey := range SNSAttributeMap {
log.Printf("[DEBUG] Reading %s => %s", iKey, oKey)
2015-05-15 01:17:18 +02:00
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 {
var value string
if iKey == "policy" {
value, err = normalizeJsonString(*attrmap[oKey])
if err != nil {
return errwrap.Wrapf("policy contains an invalid JSON: {{err}}", err)
}
} else {
value = *attrmap[oKey]
}
log.Printf("[DEBUG] Reading %s => %s -> %s", iKey, oKey, value)
d.Set(iKey, value)
2015-05-15 01:17:18 +02:00
}
}
}
}
2016-04-21 17:18:04 +02:00
// If we have no name set (import) then determine it from the ARN.
// This is a bit of a heuristic for now since AWS provides no other
// way to get it.
if _, ok := d.GetOk("name"); !ok {
arn := d.Get("arn").(string)
idx := strings.LastIndex(arn, ":")
if idx > -1 {
d.Set("name", arn[idx+1:])
}
}
2015-05-15 01:17:18 +02:00
return nil
}
func resourceAwsSnsTopicDelete(d *schema.ResourceData, meta interface{}) error {
snsconn := meta.(*AWSClient).snsconn
log.Printf("[DEBUG] SNS Delete Topic: %s", d.Id())
_, err := snsconn.DeleteTopic(&sns.DeleteTopicInput{
TopicArn: aws.String(d.Id()),
2015-05-15 01:17:18 +02:00
})
if err != nil {
return err
}
return nil
}