github.com/willrstern/terraform@v0.6.7-0.20151106173844-fa471ddbb53a/builtin/providers/aws/resource_aws_elasticache_cluster.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"sort"
     7  	"strings"
     8  	"time"
     9  
    10  	"github.com/aws/aws-sdk-go/aws"
    11  	"github.com/aws/aws-sdk-go/aws/awserr"
    12  	"github.com/aws/aws-sdk-go/service/elasticache"
    13  	"github.com/aws/aws-sdk-go/service/iam"
    14  	"github.com/hashicorp/terraform/helper/hashcode"
    15  	"github.com/hashicorp/terraform/helper/resource"
    16  	"github.com/hashicorp/terraform/helper/schema"
    17  )
    18  
    19  func resourceAwsElasticacheCluster() *schema.Resource {
    20  	return &schema.Resource{
    21  		Create: resourceAwsElasticacheClusterCreate,
    22  		Read:   resourceAwsElasticacheClusterRead,
    23  		Update: resourceAwsElasticacheClusterUpdate,
    24  		Delete: resourceAwsElasticacheClusterDelete,
    25  
    26  		Schema: map[string]*schema.Schema{
    27  			"cluster_id": &schema.Schema{
    28  				Type:     schema.TypeString,
    29  				Required: true,
    30  				ForceNew: true,
    31  				StateFunc: func(val interface{}) string {
    32  					// Elasticache normalizes cluster ids to lowercase,
    33  					// so we have to do this too or else we can end up
    34  					// with non-converging diffs.
    35  					return strings.ToLower(val.(string))
    36  				},
    37  			},
    38  			"configuration_endpoint": &schema.Schema{
    39  				Type:     schema.TypeString,
    40  				Computed: true,
    41  			},
    42  			"engine": &schema.Schema{
    43  				Type:     schema.TypeString,
    44  				Required: true,
    45  			},
    46  			"node_type": &schema.Schema{
    47  				Type:     schema.TypeString,
    48  				Required: true,
    49  				ForceNew: true,
    50  			},
    51  			"num_cache_nodes": &schema.Schema{
    52  				Type:     schema.TypeInt,
    53  				Required: true,
    54  			},
    55  			"parameter_group_name": &schema.Schema{
    56  				Type:     schema.TypeString,
    57  				Optional: true,
    58  				Computed: true,
    59  			},
    60  			"port": &schema.Schema{
    61  				Type:     schema.TypeInt,
    62  				Required: true,
    63  				ForceNew: true,
    64  			},
    65  			"engine_version": &schema.Schema{
    66  				Type:     schema.TypeString,
    67  				Optional: true,
    68  				Computed: true,
    69  			},
    70  			"maintenance_window": &schema.Schema{
    71  				Type:     schema.TypeString,
    72  				Optional: true,
    73  				Computed: true,
    74  			},
    75  			"subnet_group_name": &schema.Schema{
    76  				Type:     schema.TypeString,
    77  				Optional: true,
    78  				Computed: true,
    79  				ForceNew: true,
    80  			},
    81  			"security_group_names": &schema.Schema{
    82  				Type:     schema.TypeSet,
    83  				Optional: true,
    84  				Computed: true,
    85  				ForceNew: true,
    86  				Elem:     &schema.Schema{Type: schema.TypeString},
    87  				Set: func(v interface{}) int {
    88  					return hashcode.String(v.(string))
    89  				},
    90  			},
    91  			"security_group_ids": &schema.Schema{
    92  				Type:     schema.TypeSet,
    93  				Optional: true,
    94  				Computed: true,
    95  				Elem:     &schema.Schema{Type: schema.TypeString},
    96  				Set: func(v interface{}) int {
    97  					return hashcode.String(v.(string))
    98  				},
    99  			},
   100  			// Exported Attributes
   101  			"cache_nodes": &schema.Schema{
   102  				Type:     schema.TypeList,
   103  				Computed: true,
   104  				Elem: &schema.Resource{
   105  					Schema: map[string]*schema.Schema{
   106  						"id": &schema.Schema{
   107  							Type:     schema.TypeString,
   108  							Computed: true,
   109  						},
   110  						"address": &schema.Schema{
   111  							Type:     schema.TypeString,
   112  							Computed: true,
   113  						},
   114  						"port": &schema.Schema{
   115  							Type:     schema.TypeInt,
   116  							Computed: true,
   117  						},
   118  					},
   119  				},
   120  			},
   121  			"notification_topic_arn": &schema.Schema{
   122  				Type:     schema.TypeString,
   123  				Optional: true,
   124  			},
   125  			// A single-element string list containing an Amazon Resource Name (ARN) that
   126  			// uniquely identifies a Redis RDB snapshot file stored in Amazon S3. The snapshot
   127  			// file will be used to populate the node group.
   128  			//
   129  			// See also:
   130  			// https://github.com/aws/aws-sdk-go/blob/4862a174f7fc92fb523fc39e68f00b87d91d2c3d/service/elasticache/api.go#L2079
   131  			"snapshot_arns": &schema.Schema{
   132  				Type:     schema.TypeSet,
   133  				Optional: true,
   134  				ForceNew: true,
   135  				Elem:     &schema.Schema{Type: schema.TypeString},
   136  				Set: func(v interface{}) int {
   137  					return hashcode.String(v.(string))
   138  				},
   139  			},
   140  
   141  			"tags": tagsSchema(),
   142  
   143  			// apply_immediately is used to determine when the update modifications
   144  			// take place.
   145  			// See http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_ModifyCacheCluster.html
   146  			"apply_immediately": &schema.Schema{
   147  				Type:     schema.TypeBool,
   148  				Optional: true,
   149  				Computed: true,
   150  			},
   151  		},
   152  	}
   153  }
   154  
   155  func resourceAwsElasticacheClusterCreate(d *schema.ResourceData, meta interface{}) error {
   156  	conn := meta.(*AWSClient).elasticacheconn
   157  
   158  	clusterId := d.Get("cluster_id").(string)
   159  	nodeType := d.Get("node_type").(string)           // e.g) cache.m1.small
   160  	numNodes := int64(d.Get("num_cache_nodes").(int)) // 2
   161  	engine := d.Get("engine").(string)                // memcached
   162  	engineVersion := d.Get("engine_version").(string) // 1.4.14
   163  	port := int64(d.Get("port").(int))                // e.g) 11211
   164  	subnetGroupName := d.Get("subnet_group_name").(string)
   165  	securityNameSet := d.Get("security_group_names").(*schema.Set)
   166  	securityIdSet := d.Get("security_group_ids").(*schema.Set)
   167  
   168  	securityNames := expandStringList(securityNameSet.List())
   169  	securityIds := expandStringList(securityIdSet.List())
   170  
   171  	tags := tagsFromMapEC(d.Get("tags").(map[string]interface{}))
   172  	req := &elasticache.CreateCacheClusterInput{
   173  		CacheClusterId:          aws.String(clusterId),
   174  		CacheNodeType:           aws.String(nodeType),
   175  		NumCacheNodes:           aws.Int64(numNodes),
   176  		Engine:                  aws.String(engine),
   177  		EngineVersion:           aws.String(engineVersion),
   178  		Port:                    aws.Int64(port),
   179  		CacheSubnetGroupName:    aws.String(subnetGroupName),
   180  		CacheSecurityGroupNames: securityNames,
   181  		SecurityGroupIds:        securityIds,
   182  		Tags:                    tags,
   183  	}
   184  
   185  	// parameter groups are optional and can be defaulted by AWS
   186  	if v, ok := d.GetOk("parameter_group_name"); ok {
   187  		req.CacheParameterGroupName = aws.String(v.(string))
   188  	}
   189  
   190  	if v, ok := d.GetOk("maintenance_window"); ok {
   191  		req.PreferredMaintenanceWindow = aws.String(v.(string))
   192  	}
   193  
   194  	if v, ok := d.GetOk("notification_topic_arn"); ok {
   195  		req.NotificationTopicArn = aws.String(v.(string))
   196  	}
   197  
   198  	snaps := d.Get("snapshot_arns").(*schema.Set).List()
   199  	if len(snaps) > 0 {
   200  		s := expandStringList(snaps)
   201  		req.SnapshotArns = s
   202  		log.Printf("[DEBUG] Restoring Redis cluster from S3 snapshot: %#v", s)
   203  	}
   204  
   205  	resp, err := conn.CreateCacheCluster(req)
   206  	if err != nil {
   207  		return fmt.Errorf("Error creating Elasticache: %s", err)
   208  	}
   209  
   210  	// Assign the cluster id as the resource ID
   211  	// Elasticache always retains the id in lower case, so we have to
   212  	// mimic that or else we won't be able to refresh a resource whose
   213  	// name contained uppercase characters.
   214  	d.SetId(strings.ToLower(*resp.CacheCluster.CacheClusterId))
   215  
   216  	pending := []string{"creating"}
   217  	stateConf := &resource.StateChangeConf{
   218  		Pending:    pending,
   219  		Target:     "available",
   220  		Refresh:    cacheClusterStateRefreshFunc(conn, d.Id(), "available", pending),
   221  		Timeout:    10 * time.Minute,
   222  		Delay:      10 * time.Second,
   223  		MinTimeout: 3 * time.Second,
   224  	}
   225  
   226  	log.Printf("[DEBUG] Waiting for state to become available: %v", d.Id())
   227  	_, sterr := stateConf.WaitForState()
   228  	if sterr != nil {
   229  		return fmt.Errorf("Error waiting for elasticache (%s) to be created: %s", d.Id(), sterr)
   230  	}
   231  
   232  	return resourceAwsElasticacheClusterRead(d, meta)
   233  }
   234  
   235  func resourceAwsElasticacheClusterRead(d *schema.ResourceData, meta interface{}) error {
   236  	conn := meta.(*AWSClient).elasticacheconn
   237  	req := &elasticache.DescribeCacheClustersInput{
   238  		CacheClusterId:    aws.String(d.Id()),
   239  		ShowCacheNodeInfo: aws.Bool(true),
   240  	}
   241  
   242  	res, err := conn.DescribeCacheClusters(req)
   243  	if err != nil {
   244  		if eccErr, ok := err.(awserr.Error); ok && eccErr.Code() == "CacheClusterNotFound" {
   245  			log.Printf("[WARN] ElastiCache Cluster (%s) not found", d.Id())
   246  			d.SetId("")
   247  			return nil
   248  		}
   249  
   250  		return err
   251  	}
   252  
   253  	if len(res.CacheClusters) == 1 {
   254  		c := res.CacheClusters[0]
   255  		d.Set("cluster_id", c.CacheClusterId)
   256  		d.Set("node_type", c.CacheNodeType)
   257  		d.Set("num_cache_nodes", c.NumCacheNodes)
   258  		d.Set("engine", c.Engine)
   259  		d.Set("engine_version", c.EngineVersion)
   260  		if c.ConfigurationEndpoint != nil {
   261  			d.Set("port", c.ConfigurationEndpoint.Port)
   262  			d.Set("configuration_endpoint", aws.String(fmt.Sprintf("%s:%d", *c.ConfigurationEndpoint.Address, *c.ConfigurationEndpoint.Port)))
   263  		}
   264  
   265  		d.Set("subnet_group_name", c.CacheSubnetGroupName)
   266  		d.Set("security_group_names", c.CacheSecurityGroups)
   267  		d.Set("security_group_ids", c.SecurityGroups)
   268  		d.Set("parameter_group_name", c.CacheParameterGroup)
   269  		d.Set("maintenance_window", c.PreferredMaintenanceWindow)
   270  		if c.NotificationConfiguration != nil {
   271  			if *c.NotificationConfiguration.TopicStatus == "active" {
   272  				d.Set("notification_topic_arn", c.NotificationConfiguration.TopicArn)
   273  			}
   274  		}
   275  
   276  		if err := setCacheNodeData(d, c); err != nil {
   277  			return err
   278  		}
   279  		// list tags for resource
   280  		// set tags
   281  		arn, err := buildECARN(d, meta)
   282  		if err != nil {
   283  			log.Printf("[DEBUG] Error building ARN for ElastiCache Cluster, not setting Tags for cluster %s", *c.CacheClusterId)
   284  		} else {
   285  			resp, err := conn.ListTagsForResource(&elasticache.ListTagsForResourceInput{
   286  				ResourceName: aws.String(arn),
   287  			})
   288  
   289  			if err != nil {
   290  				log.Printf("[DEBUG] Error retrieving tags for ARN: %s", arn)
   291  			}
   292  
   293  			var et []*elasticache.Tag
   294  			if len(resp.TagList) > 0 {
   295  				et = resp.TagList
   296  			}
   297  			d.Set("tags", tagsToMapEC(et))
   298  		}
   299  	}
   300  
   301  	return nil
   302  }
   303  
   304  func resourceAwsElasticacheClusterUpdate(d *schema.ResourceData, meta interface{}) error {
   305  	conn := meta.(*AWSClient).elasticacheconn
   306  	arn, err := buildECARN(d, meta)
   307  	if err != nil {
   308  		log.Printf("[DEBUG] Error building ARN for ElastiCache Cluster, not updating Tags for cluster %s", d.Id())
   309  	} else {
   310  		if err := setTagsEC(conn, d, arn); err != nil {
   311  			return err
   312  		}
   313  	}
   314  
   315  	req := &elasticache.ModifyCacheClusterInput{
   316  		CacheClusterId:   aws.String(d.Id()),
   317  		ApplyImmediately: aws.Bool(d.Get("apply_immediately").(bool)),
   318  	}
   319  
   320  	requestUpdate := false
   321  	if d.HasChange("security_group_ids") {
   322  		if attr := d.Get("security_group_ids").(*schema.Set); attr.Len() > 0 {
   323  			req.SecurityGroupIds = expandStringList(attr.List())
   324  			requestUpdate = true
   325  		}
   326  	}
   327  
   328  	if d.HasChange("parameter_group_name") {
   329  		req.CacheParameterGroupName = aws.String(d.Get("parameter_group_name").(string))
   330  		requestUpdate = true
   331  	}
   332  
   333  	if d.HasChange("maintenance_window") {
   334  		req.PreferredMaintenanceWindow = aws.String(d.Get("maintenance_window").(string))
   335  		requestUpdate = true
   336  	}
   337  
   338  	if d.HasChange("notification_topic_arn") {
   339  		v := d.Get("notification_topic_arn").(string)
   340  		req.NotificationTopicArn = aws.String(v)
   341  		if v == "" {
   342  			inactive := "inactive"
   343  			req.NotificationTopicStatus = &inactive
   344  		}
   345  		requestUpdate = true
   346  	}
   347  
   348  	if d.HasChange("engine_version") {
   349  		req.EngineVersion = aws.String(d.Get("engine_version").(string))
   350  		requestUpdate = true
   351  	}
   352  
   353  	if d.HasChange("num_cache_nodes") {
   354  		req.NumCacheNodes = aws.Int64(int64(d.Get("num_cache_nodes").(int)))
   355  		requestUpdate = true
   356  	}
   357  
   358  	if requestUpdate {
   359  		log.Printf("[DEBUG] Modifying ElastiCache Cluster (%s), opts:\n%s", d.Id(), req)
   360  		_, err := conn.ModifyCacheCluster(req)
   361  		if err != nil {
   362  			return fmt.Errorf("[WARN] Error updating ElastiCache cluster (%s), error: %s", d.Id(), err)
   363  		}
   364  
   365  		log.Printf("[DEBUG] Waiting for update: %s", d.Id())
   366  		pending := []string{"modifying", "rebooting cache cluster nodes", "snapshotting"}
   367  		stateConf := &resource.StateChangeConf{
   368  			Pending:    pending,
   369  			Target:     "available",
   370  			Refresh:    cacheClusterStateRefreshFunc(conn, d.Id(), "available", pending),
   371  			Timeout:    5 * time.Minute,
   372  			Delay:      5 * time.Second,
   373  			MinTimeout: 3 * time.Second,
   374  		}
   375  
   376  		_, sterr := stateConf.WaitForState()
   377  		if sterr != nil {
   378  			return fmt.Errorf("Error waiting for elasticache (%s) to update: %s", d.Id(), sterr)
   379  		}
   380  	}
   381  
   382  	return resourceAwsElasticacheClusterRead(d, meta)
   383  }
   384  
   385  func setCacheNodeData(d *schema.ResourceData, c *elasticache.CacheCluster) error {
   386  	sortedCacheNodes := make([]*elasticache.CacheNode, len(c.CacheNodes))
   387  	copy(sortedCacheNodes, c.CacheNodes)
   388  	sort.Sort(byCacheNodeId(sortedCacheNodes))
   389  
   390  	cacheNodeData := make([]map[string]interface{}, 0, len(sortedCacheNodes))
   391  
   392  	for _, node := range sortedCacheNodes {
   393  		if node.CacheNodeId == nil || node.Endpoint == nil || node.Endpoint.Address == nil || node.Endpoint.Port == nil {
   394  			return fmt.Errorf("Unexpected nil pointer in: %s", node)
   395  		}
   396  		cacheNodeData = append(cacheNodeData, map[string]interface{}{
   397  			"id":      *node.CacheNodeId,
   398  			"address": *node.Endpoint.Address,
   399  			"port":    int(*node.Endpoint.Port),
   400  		})
   401  	}
   402  
   403  	return d.Set("cache_nodes", cacheNodeData)
   404  }
   405  
   406  type byCacheNodeId []*elasticache.CacheNode
   407  
   408  func (b byCacheNodeId) Len() int      { return len(b) }
   409  func (b byCacheNodeId) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
   410  func (b byCacheNodeId) Less(i, j int) bool {
   411  	return b[i].CacheNodeId != nil && b[j].CacheNodeId != nil &&
   412  		*b[i].CacheNodeId < *b[j].CacheNodeId
   413  }
   414  
   415  func resourceAwsElasticacheClusterDelete(d *schema.ResourceData, meta interface{}) error {
   416  	conn := meta.(*AWSClient).elasticacheconn
   417  
   418  	req := &elasticache.DeleteCacheClusterInput{
   419  		CacheClusterId: aws.String(d.Id()),
   420  	}
   421  	_, err := conn.DeleteCacheCluster(req)
   422  	if err != nil {
   423  		return err
   424  	}
   425  
   426  	log.Printf("[DEBUG] Waiting for deletion: %v", d.Id())
   427  	stateConf := &resource.StateChangeConf{
   428  		Pending:    []string{"creating", "available", "deleting", "incompatible-parameters", "incompatible-network", "restore-failed"},
   429  		Target:     "",
   430  		Refresh:    cacheClusterStateRefreshFunc(conn, d.Id(), "", []string{}),
   431  		Timeout:    10 * time.Minute,
   432  		Delay:      10 * time.Second,
   433  		MinTimeout: 3 * time.Second,
   434  	}
   435  
   436  	_, sterr := stateConf.WaitForState()
   437  	if sterr != nil {
   438  		return fmt.Errorf("Error waiting for elasticache (%s) to delete: %s", d.Id(), sterr)
   439  	}
   440  
   441  	d.SetId("")
   442  
   443  	return nil
   444  }
   445  
   446  func cacheClusterStateRefreshFunc(conn *elasticache.ElastiCache, clusterID, givenState string, pending []string) resource.StateRefreshFunc {
   447  	return func() (interface{}, string, error) {
   448  		resp, err := conn.DescribeCacheClusters(&elasticache.DescribeCacheClustersInput{
   449  			CacheClusterId:    aws.String(clusterID),
   450  			ShowCacheNodeInfo: aws.Bool(true),
   451  		})
   452  		if err != nil {
   453  			apierr := err.(awserr.Error)
   454  			log.Printf("[DEBUG] message: %v, code: %v", apierr.Message(), apierr.Code())
   455  			if apierr.Message() == fmt.Sprintf("CacheCluster not found: %v", clusterID) {
   456  				log.Printf("[DEBUG] Detect deletion")
   457  				return nil, "", nil
   458  			}
   459  
   460  			log.Printf("[ERROR] CacheClusterStateRefreshFunc: %s", err)
   461  			return nil, "", err
   462  		}
   463  
   464  		if len(resp.CacheClusters) == 0 {
   465  			return nil, "", fmt.Errorf("[WARN] Error: no Cache Clusters found for id (%s)", clusterID)
   466  		}
   467  
   468  		var c *elasticache.CacheCluster
   469  		for _, cluster := range resp.CacheClusters {
   470  			if *cluster.CacheClusterId == clusterID {
   471  				log.Printf("[DEBUG] Found matching ElastiCache cluster: %s", *cluster.CacheClusterId)
   472  				c = cluster
   473  			}
   474  		}
   475  
   476  		if c == nil {
   477  			return nil, "", fmt.Errorf("[WARN] Error: no matching Elastic Cache cluster for id (%s)", clusterID)
   478  		}
   479  
   480  		log.Printf("[DEBUG] ElastiCache Cluster (%s) status: %v", clusterID, *c.CacheClusterStatus)
   481  
   482  		// return the current state if it's in the pending array
   483  		for _, p := range pending {
   484  			log.Printf("[DEBUG] ElastiCache: checking pending state (%s) for cluster (%s), cluster status: %s", pending, clusterID, *c.CacheClusterStatus)
   485  			s := *c.CacheClusterStatus
   486  			if p == s {
   487  				log.Printf("[DEBUG] Return with status: %v", *c.CacheClusterStatus)
   488  				return c, p, nil
   489  			}
   490  		}
   491  
   492  		// return given state if it's not in pending
   493  		if givenState != "" {
   494  			log.Printf("[DEBUG] ElastiCache: checking given state (%s) of cluster (%s) against cluster status (%s)", givenState, clusterID, *c.CacheClusterStatus)
   495  			// check to make sure we have the node count we're expecting
   496  			if int64(len(c.CacheNodes)) != *c.NumCacheNodes {
   497  				log.Printf("[DEBUG] Node count is not what is expected: %d found, %d expected", len(c.CacheNodes), *c.NumCacheNodes)
   498  				return nil, "creating", nil
   499  			}
   500  
   501  			log.Printf("[DEBUG] Node count matched (%d)", len(c.CacheNodes))
   502  			// loop the nodes and check their status as well
   503  			for _, n := range c.CacheNodes {
   504  				log.Printf("[DEBUG] Checking cache node for status: %s", n)
   505  				if n.CacheNodeStatus != nil && *n.CacheNodeStatus != "available" {
   506  					log.Printf("[DEBUG] Node (%s) is not yet available, status: %s", *n.CacheNodeId, *n.CacheNodeStatus)
   507  					return nil, "creating", nil
   508  				}
   509  				log.Printf("[DEBUG] Cache node not in expected state")
   510  			}
   511  			log.Printf("[DEBUG] ElastiCache returning given state (%s), cluster: %s", givenState, c)
   512  			return c, givenState, nil
   513  		}
   514  		log.Printf("[DEBUG] current status: %v", *c.CacheClusterStatus)
   515  		return c, *c.CacheClusterStatus, nil
   516  	}
   517  }
   518  
   519  func buildECARN(d *schema.ResourceData, meta interface{}) (string, error) {
   520  	iamconn := meta.(*AWSClient).iamconn
   521  	region := meta.(*AWSClient).region
   522  	// An zero value GetUserInput{} defers to the currently logged in user
   523  	resp, err := iamconn.GetUser(&iam.GetUserInput{})
   524  	if err != nil {
   525  		return "", err
   526  	}
   527  	userARN := *resp.User.Arn
   528  	accountID := strings.Split(userARN, ":")[4]
   529  	arn := fmt.Sprintf("arn:aws:elasticache:%s:%s:cluster:%s", region, accountID, d.Id())
   530  	return arn, nil
   531  }