github.com/nathanielks/terraform@v0.6.1-0.20170509030759-13e1a62319dc/builtin/providers/aws/data_source_aws_sns.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  	"time"
     7  
     8  	"github.com/aws/aws-sdk-go/service/sns"
     9  	"github.com/hashicorp/errwrap"
    10  	"github.com/hashicorp/terraform/helper/schema"
    11  )
    12  
    13  func dataSourceAwsSnsTopic() *schema.Resource {
    14  	return &schema.Resource{
    15  		Read: dataSourceAwsSnsTopicsRead,
    16  		Schema: map[string]*schema.Schema{
    17  			"name": {
    18  				Type:     schema.TypeString,
    19  				Required: true,
    20  				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
    21  					value := v.(string)
    22  					validNamePattern := "^[A-Za-z0-9_-]+$"
    23  					validName, nameMatchErr := regexp.MatchString(validNamePattern, value)
    24  					if !validName || nameMatchErr != nil {
    25  						errors = append(errors, fmt.Errorf(
    26  							"%q must match regex '%v'", k, validNamePattern))
    27  					}
    28  					return
    29  				},
    30  			},
    31  			"arn": {
    32  				Type:     schema.TypeString,
    33  				Computed: true,
    34  			},
    35  		},
    36  	}
    37  }
    38  
    39  func dataSourceAwsSnsTopicsRead(d *schema.ResourceData, meta interface{}) error {
    40  	conn := meta.(*AWSClient).snsconn
    41  	params := &sns.ListTopicsInput{}
    42  
    43  	target := d.Get("name")
    44  	var arns []string
    45  	err := conn.ListTopicsPages(params, func(page *sns.ListTopicsOutput, lastPage bool) bool {
    46  		for _, topic := range page.Topics {
    47  			topicPattern := fmt.Sprintf(".*:%v$", target)
    48  			matched, regexpErr := regexp.MatchString(topicPattern, *topic.TopicArn)
    49  			if matched && regexpErr == nil {
    50  				arns = append(arns, *topic.TopicArn)
    51  			}
    52  		}
    53  
    54  		return true
    55  	})
    56  	if err != nil {
    57  		return errwrap.Wrapf("Error describing topics: {{err}}", err)
    58  	}
    59  
    60  	if len(arns) == 0 {
    61  		return fmt.Errorf("No topic with name %q found in this region.", target)
    62  	}
    63  	if len(arns) > 1 {
    64  		return fmt.Errorf("Multiple topics with name %q found in this region.", target)
    65  	}
    66  
    67  	d.SetId(time.Now().UTC().String())
    68  	d.Set("arn", arns[0])
    69  
    70  	return nil
    71  }