github.com/ottenhoff/terraform@v0.7.0-rc1.0.20160607213102-ac2d195cc560/builtin/providers/aws/resource_aws_sqs_queue.go (about)

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