github.com/mohanarpit/terraform@v0.6.16-0.20160909104007-291f29853544/builtin/providers/aws/resource_aws_sqs_queue.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net/url"
     7  	"strconv"
     8  
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  
    11  	"strings"
    12  
    13  	"github.com/aws/aws-sdk-go/aws"
    14  	"github.com/aws/aws-sdk-go/aws/awserr"
    15  	"github.com/aws/aws-sdk-go/service/sqs"
    16  )
    17  
    18  var AttributeMap = map[string]string{
    19  	"delay_seconds":              "DelaySeconds",
    20  	"max_message_size":           "MaximumMessageSize",
    21  	"message_retention_seconds":  "MessageRetentionPeriod",
    22  	"receive_wait_time_seconds":  "ReceiveMessageWaitTimeSeconds",
    23  	"visibility_timeout_seconds": "VisibilityTimeout",
    24  	"policy":                     "Policy",
    25  	"redrive_policy":             "RedrivePolicy",
    26  	"arn":                        "QueueArn",
    27  }
    28  
    29  // A number of these are marked as computed because if you don't
    30  // provide a value, SQS will provide you with defaults (which are the
    31  // default values specified below)
    32  func resourceAwsSqsQueue() *schema.Resource {
    33  	return &schema.Resource{
    34  		Create: resourceAwsSqsQueueCreate,
    35  		Read:   resourceAwsSqsQueueRead,
    36  		Update: resourceAwsSqsQueueUpdate,
    37  		Delete: resourceAwsSqsQueueDelete,
    38  		Importer: &schema.ResourceImporter{
    39  			State: schema.ImportStatePassthrough,
    40  		},
    41  
    42  		Schema: map[string]*schema.Schema{
    43  			"name": {
    44  				Type:     schema.TypeString,
    45  				Required: true,
    46  				ForceNew: true,
    47  			},
    48  			"delay_seconds": {
    49  				Type:     schema.TypeInt,
    50  				Optional: true,
    51  				Default:  0,
    52  			},
    53  			"max_message_size": {
    54  				Type:     schema.TypeInt,
    55  				Optional: true,
    56  				Default:  262144,
    57  			},
    58  			"message_retention_seconds": {
    59  				Type:     schema.TypeInt,
    60  				Optional: true,
    61  				Default:  345600,
    62  			},
    63  			"receive_wait_time_seconds": {
    64  				Type:     schema.TypeInt,
    65  				Optional: true,
    66  				Default:  0,
    67  			},
    68  			"visibility_timeout_seconds": {
    69  				Type:     schema.TypeInt,
    70  				Optional: true,
    71  				Default:  30,
    72  			},
    73  			"policy": {
    74  				Type:             schema.TypeString,
    75  				Optional:         true,
    76  				DiffSuppressFunc: suppressEquivalentAwsPolicyDiffs,
    77  				Computed:         true,
    78  			},
    79  			"redrive_policy": {
    80  				Type:      schema.TypeString,
    81  				Optional:  true,
    82  				StateFunc: normalizeJson,
    83  			},
    84  			"arn": {
    85  				Type:     schema.TypeString,
    86  				Computed: true,
    87  			},
    88  		},
    89  	}
    90  }
    91  
    92  func resourceAwsSqsQueueCreate(d *schema.ResourceData, meta interface{}) error {
    93  	sqsconn := meta.(*AWSClient).sqsconn
    94  
    95  	name := d.Get("name").(string)
    96  
    97  	log.Printf("[DEBUG] SQS queue create: %s", name)
    98  
    99  	req := &sqs.CreateQueueInput{
   100  		QueueName: aws.String(name),
   101  	}
   102  
   103  	attributes := make(map[string]*string)
   104  
   105  	resource := *resourceAwsSqsQueue()
   106  
   107  	for k, s := range resource.Schema {
   108  		if attrKey, ok := AttributeMap[k]; ok {
   109  			if value, ok := d.GetOk(k); ok {
   110  				if s.Type == schema.TypeInt {
   111  					attributes[attrKey] = aws.String(strconv.Itoa(value.(int)))
   112  				} else {
   113  					attributes[attrKey] = aws.String(value.(string))
   114  				}
   115  			}
   116  
   117  		}
   118  	}
   119  
   120  	if len(attributes) > 0 {
   121  		req.Attributes = attributes
   122  	}
   123  
   124  	output, err := sqsconn.CreateQueue(req)
   125  	if err != nil {
   126  		return fmt.Errorf("Error creating SQS queue: %s", err)
   127  	}
   128  
   129  	d.SetId(*output.QueueUrl)
   130  
   131  	return resourceAwsSqsQueueUpdate(d, meta)
   132  }
   133  
   134  func resourceAwsSqsQueueUpdate(d *schema.ResourceData, meta interface{}) error {
   135  	sqsconn := meta.(*AWSClient).sqsconn
   136  	attributes := make(map[string]*string)
   137  
   138  	resource := *resourceAwsSqsQueue()
   139  
   140  	for k, s := range resource.Schema {
   141  		if attrKey, ok := AttributeMap[k]; ok {
   142  			if d.HasChange(k) {
   143  				log.Printf("[DEBUG] Updating %s", attrKey)
   144  				_, n := d.GetChange(k)
   145  				if s.Type == schema.TypeInt {
   146  					attributes[attrKey] = aws.String(strconv.Itoa(n.(int)))
   147  				} else {
   148  					attributes[attrKey] = aws.String(n.(string))
   149  				}
   150  			}
   151  		}
   152  	}
   153  
   154  	if len(attributes) > 0 {
   155  		req := &sqs.SetQueueAttributesInput{
   156  			QueueUrl:   aws.String(d.Id()),
   157  			Attributes: attributes,
   158  		}
   159  		if _, err := sqsconn.SetQueueAttributes(req); err != nil {
   160  			return fmt.Errorf("[ERR] Error updating SQS attributes: %s", err)
   161  		}
   162  	}
   163  
   164  	return resourceAwsSqsQueueRead(d, meta)
   165  }
   166  
   167  func resourceAwsSqsQueueRead(d *schema.ResourceData, meta interface{}) error {
   168  	sqsconn := meta.(*AWSClient).sqsconn
   169  
   170  	attributeOutput, err := sqsconn.GetQueueAttributes(&sqs.GetQueueAttributesInput{
   171  		QueueUrl:       aws.String(d.Id()),
   172  		AttributeNames: []*string{aws.String("All")},
   173  	})
   174  
   175  	if err != nil {
   176  		if awsErr, ok := err.(awserr.Error); ok {
   177  			log.Printf("ERROR Found %s", awsErr.Code())
   178  			if "AWS.SimpleQueueService.NonExistentQueue" == awsErr.Code() {
   179  				d.SetId("")
   180  				log.Printf("[DEBUG] SQS Queue (%s) not found", d.Get("name").(string))
   181  				return nil
   182  			}
   183  		}
   184  		return err
   185  	}
   186  
   187  	name, err := extractNameFromSqsQueueUrl(d.Id())
   188  	if err != nil {
   189  		return err
   190  	}
   191  	d.Set("name", name)
   192  
   193  	if attributeOutput.Attributes != nil && len(attributeOutput.Attributes) > 0 {
   194  		attrmap := attributeOutput.Attributes
   195  		resource := *resourceAwsSqsQueue()
   196  		// iKey = internal struct key, oKey = AWS Attribute Map key
   197  		for iKey, oKey := range AttributeMap {
   198  			if attrmap[oKey] != nil {
   199  				if resource.Schema[iKey].Type == schema.TypeInt {
   200  					value, err := strconv.Atoi(*attrmap[oKey])
   201  					if err != nil {
   202  						return err
   203  					}
   204  					d.Set(iKey, value)
   205  					log.Printf("[DEBUG] Reading %s => %s -> %d", iKey, oKey, value)
   206  				} else {
   207  					log.Printf("[DEBUG] Reading %s => %s -> %s", iKey, oKey, *attrmap[oKey])
   208  					d.Set(iKey, *attrmap[oKey])
   209  				}
   210  			}
   211  		}
   212  	}
   213  
   214  	return nil
   215  }
   216  
   217  func resourceAwsSqsQueueDelete(d *schema.ResourceData, meta interface{}) error {
   218  	sqsconn := meta.(*AWSClient).sqsconn
   219  
   220  	log.Printf("[DEBUG] SQS Delete Queue: %s", d.Id())
   221  	_, err := sqsconn.DeleteQueue(&sqs.DeleteQueueInput{
   222  		QueueUrl: aws.String(d.Id()),
   223  	})
   224  	if err != nil {
   225  		return err
   226  	}
   227  	return nil
   228  }
   229  
   230  func extractNameFromSqsQueueUrl(queue string) (string, error) {
   231  	//http://sqs.us-west-2.amazonaws.com/123456789012/queueName
   232  	u, err := url.Parse(queue)
   233  	if err != nil {
   234  		return "", err
   235  	}
   236  	segments := strings.Split(u.Path, "/")
   237  	if len(segments) != 3 {
   238  		return "", fmt.Errorf("SQS Url not parsed correctly")
   239  	}
   240  
   241  	return segments[2], nil
   242  
   243  }