github.com/mohanarpit/terraform@v0.6.16-0.20160909104007-291f29853544/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/hashicorp/terraform/helper/resource"
    14  	"github.com/hashicorp/terraform/helper/schema"
    15  )
    16  
    17  func resourceAwsElastiCacheCommonSchema() map[string]*schema.Schema {
    18  
    19  	return map[string]*schema.Schema{
    20  		"availability_zones": &schema.Schema{
    21  			Type:     schema.TypeSet,
    22  			Optional: true,
    23  			ForceNew: true,
    24  			Elem:     &schema.Schema{Type: schema.TypeString},
    25  			Set:      schema.HashString,
    26  		},
    27  		"node_type": &schema.Schema{
    28  			Type:     schema.TypeString,
    29  			Required: true,
    30  		},
    31  		"engine": &schema.Schema{
    32  			Type:     schema.TypeString,
    33  			Required: true,
    34  		},
    35  		"engine_version": &schema.Schema{
    36  			Type:     schema.TypeString,
    37  			Optional: true,
    38  			Computed: true,
    39  		},
    40  		"parameter_group_name": &schema.Schema{
    41  			Type:     schema.TypeString,
    42  			Optional: true,
    43  			Computed: true,
    44  		},
    45  		"subnet_group_name": &schema.Schema{
    46  			Type:     schema.TypeString,
    47  			Optional: true,
    48  			Computed: true,
    49  			ForceNew: true,
    50  		},
    51  		"security_group_names": &schema.Schema{
    52  			Type:     schema.TypeSet,
    53  			Optional: true,
    54  			Computed: true,
    55  			ForceNew: true,
    56  			Elem:     &schema.Schema{Type: schema.TypeString},
    57  			Set:      schema.HashString,
    58  		},
    59  		"security_group_ids": &schema.Schema{
    60  			Type:     schema.TypeSet,
    61  			Optional: true,
    62  			Computed: true,
    63  			Elem:     &schema.Schema{Type: schema.TypeString},
    64  			Set:      schema.HashString,
    65  		},
    66  		// A single-element string list containing an Amazon Resource Name (ARN) that
    67  		// uniquely identifies a Redis RDB snapshot file stored in Amazon S3. The snapshot
    68  		// file will be used to populate the node group.
    69  		//
    70  		// See also:
    71  		// https://github.com/aws/aws-sdk-go/blob/4862a174f7fc92fb523fc39e68f00b87d91d2c3d/service/elasticache/api.go#L2079
    72  		"snapshot_arns": &schema.Schema{
    73  			Type:     schema.TypeSet,
    74  			Optional: true,
    75  			ForceNew: true,
    76  			Elem:     &schema.Schema{Type: schema.TypeString},
    77  			Set:      schema.HashString,
    78  		},
    79  		"snapshot_window": &schema.Schema{
    80  			Type:     schema.TypeString,
    81  			Optional: true,
    82  			Computed: true,
    83  		},
    84  		"snapshot_name": &schema.Schema{
    85  			Type:     schema.TypeString,
    86  			Optional: true,
    87  			ForceNew: true,
    88  		},
    89  
    90  		"maintenance_window": &schema.Schema{
    91  			Type:     schema.TypeString,
    92  			Optional: true,
    93  			Computed: true,
    94  			StateFunc: func(val interface{}) string {
    95  				// Elasticache always changes the maintenance
    96  				// to lowercase
    97  				return strings.ToLower(val.(string))
    98  			},
    99  		},
   100  		"port": &schema.Schema{
   101  			Type:     schema.TypeInt,
   102  			Required: true,
   103  			ForceNew: true,
   104  		},
   105  		"notification_topic_arn": &schema.Schema{
   106  			Type:     schema.TypeString,
   107  			Optional: true,
   108  		},
   109  
   110  		"snapshot_retention_limit": &schema.Schema{
   111  			Type:     schema.TypeInt,
   112  			Optional: true,
   113  			ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
   114  				value := v.(int)
   115  				if value > 35 {
   116  					es = append(es, fmt.Errorf(
   117  						"snapshot retention limit cannot be more than 35 days"))
   118  				}
   119  				return
   120  			},
   121  		},
   122  
   123  		"apply_immediately": &schema.Schema{
   124  			Type:     schema.TypeBool,
   125  			Optional: true,
   126  			Computed: true,
   127  		},
   128  
   129  		"tags": tagsSchema(),
   130  	}
   131  }
   132  
   133  func resourceAwsElasticacheCluster() *schema.Resource {
   134  	resourceSchema := resourceAwsElastiCacheCommonSchema()
   135  
   136  	resourceSchema["cluster_id"] = &schema.Schema{
   137  		Type:     schema.TypeString,
   138  		Required: true,
   139  		ForceNew: true,
   140  		StateFunc: func(val interface{}) string {
   141  			// Elasticache normalizes cluster ids to lowercase,
   142  			// so we have to do this too or else we can end up
   143  			// with non-converging diffs.
   144  			return strings.ToLower(val.(string))
   145  		},
   146  		ValidateFunc: validateElastiCacheClusterId,
   147  	}
   148  
   149  	resourceSchema["num_cache_nodes"] = &schema.Schema{
   150  		Type:     schema.TypeInt,
   151  		Required: true,
   152  	}
   153  
   154  	resourceSchema["az_mode"] = &schema.Schema{
   155  		Type:     schema.TypeString,
   156  		Optional: true,
   157  		Computed: true,
   158  		ForceNew: true,
   159  	}
   160  
   161  	resourceSchema["availability_zone"] = &schema.Schema{
   162  		Type:     schema.TypeString,
   163  		Optional: true,
   164  		Computed: true,
   165  		ForceNew: true,
   166  	}
   167  
   168  	resourceSchema["configuration_endpoint"] = &schema.Schema{
   169  		Type:     schema.TypeString,
   170  		Computed: true,
   171  	}
   172  
   173  	resourceSchema["replication_group_id"] = &schema.Schema{
   174  		Type:     schema.TypeString,
   175  		Computed: true,
   176  	}
   177  
   178  	resourceSchema["cache_nodes"] = &schema.Schema{
   179  		Type:     schema.TypeList,
   180  		Computed: true,
   181  		Elem: &schema.Resource{
   182  			Schema: map[string]*schema.Schema{
   183  				"id": &schema.Schema{
   184  					Type:     schema.TypeString,
   185  					Computed: true,
   186  				},
   187  				"address": &schema.Schema{
   188  					Type:     schema.TypeString,
   189  					Computed: true,
   190  				},
   191  				"port": &schema.Schema{
   192  					Type:     schema.TypeInt,
   193  					Computed: true,
   194  				},
   195  				"availability_zone": &schema.Schema{
   196  					Type:     schema.TypeString,
   197  					Computed: true,
   198  				},
   199  			},
   200  		},
   201  	}
   202  
   203  	return &schema.Resource{
   204  		Create: resourceAwsElasticacheClusterCreate,
   205  		Read:   resourceAwsElasticacheClusterRead,
   206  		Update: resourceAwsElasticacheClusterUpdate,
   207  		Delete: resourceAwsElasticacheClusterDelete,
   208  
   209  		Schema: resourceSchema,
   210  	}
   211  }
   212  
   213  func resourceAwsElasticacheClusterCreate(d *schema.ResourceData, meta interface{}) error {
   214  	conn := meta.(*AWSClient).elasticacheconn
   215  
   216  	clusterId := d.Get("cluster_id").(string)
   217  	nodeType := d.Get("node_type").(string)           // e.g) cache.m1.small
   218  	numNodes := int64(d.Get("num_cache_nodes").(int)) // 2
   219  	engine := d.Get("engine").(string)                // memcached
   220  	engineVersion := d.Get("engine_version").(string) // 1.4.14
   221  	port := int64(d.Get("port").(int))                // e.g) 11211
   222  	subnetGroupName := d.Get("subnet_group_name").(string)
   223  	securityNameSet := d.Get("security_group_names").(*schema.Set)
   224  	securityIdSet := d.Get("security_group_ids").(*schema.Set)
   225  
   226  	securityNames := expandStringList(securityNameSet.List())
   227  	securityIds := expandStringList(securityIdSet.List())
   228  	tags := tagsFromMapEC(d.Get("tags").(map[string]interface{}))
   229  
   230  	req := &elasticache.CreateCacheClusterInput{
   231  		CacheClusterId:          aws.String(clusterId),
   232  		CacheNodeType:           aws.String(nodeType),
   233  		NumCacheNodes:           aws.Int64(numNodes),
   234  		Engine:                  aws.String(engine),
   235  		EngineVersion:           aws.String(engineVersion),
   236  		Port:                    aws.Int64(port),
   237  		CacheSubnetGroupName:    aws.String(subnetGroupName),
   238  		CacheSecurityGroupNames: securityNames,
   239  		SecurityGroupIds:        securityIds,
   240  		Tags:                    tags,
   241  	}
   242  
   243  	// parameter groups are optional and can be defaulted by AWS
   244  	if v, ok := d.GetOk("parameter_group_name"); ok {
   245  		req.CacheParameterGroupName = aws.String(v.(string))
   246  	}
   247  
   248  	if v, ok := d.GetOk("snapshot_retention_limit"); ok {
   249  		req.SnapshotRetentionLimit = aws.Int64(int64(v.(int)))
   250  	}
   251  
   252  	if v, ok := d.GetOk("snapshot_window"); ok {
   253  		req.SnapshotWindow = aws.String(v.(string))
   254  	}
   255  
   256  	if v, ok := d.GetOk("maintenance_window"); ok {
   257  		req.PreferredMaintenanceWindow = aws.String(v.(string))
   258  	}
   259  
   260  	if v, ok := d.GetOk("notification_topic_arn"); ok {
   261  		req.NotificationTopicArn = aws.String(v.(string))
   262  	}
   263  
   264  	snaps := d.Get("snapshot_arns").(*schema.Set).List()
   265  	if len(snaps) > 0 {
   266  		s := expandStringList(snaps)
   267  		req.SnapshotArns = s
   268  		log.Printf("[DEBUG] Restoring Redis cluster from S3 snapshot: %#v", s)
   269  	}
   270  
   271  	if v, ok := d.GetOk("snapshot_name"); ok {
   272  		req.SnapshotName = aws.String(v.(string))
   273  	}
   274  
   275  	if v, ok := d.GetOk("az_mode"); ok {
   276  		req.AZMode = aws.String(v.(string))
   277  	}
   278  
   279  	if v, ok := d.GetOk("availability_zone"); ok {
   280  		req.PreferredAvailabilityZone = aws.String(v.(string))
   281  	}
   282  
   283  	preferred_azs := d.Get("availability_zones").(*schema.Set).List()
   284  	if len(preferred_azs) > 0 {
   285  		azs := expandStringList(preferred_azs)
   286  		req.PreferredAvailabilityZones = azs
   287  	}
   288  
   289  	if v, ok := d.GetOk("replication_group_id"); ok {
   290  		req.ReplicationGroupId = aws.String(v.(string))
   291  	}
   292  
   293  	resp, err := conn.CreateCacheCluster(req)
   294  	if err != nil {
   295  		return fmt.Errorf("Error creating Elasticache: %s", err)
   296  	}
   297  
   298  	// Assign the cluster id as the resource ID
   299  	// Elasticache always retains the id in lower case, so we have to
   300  	// mimic that or else we won't be able to refresh a resource whose
   301  	// name contained uppercase characters.
   302  	d.SetId(strings.ToLower(*resp.CacheCluster.CacheClusterId))
   303  
   304  	pending := []string{"creating", "modifying", "restoring"}
   305  	stateConf := &resource.StateChangeConf{
   306  		Pending:    pending,
   307  		Target:     []string{"available"},
   308  		Refresh:    cacheClusterStateRefreshFunc(conn, d.Id(), "available", pending),
   309  		Timeout:    40 * time.Minute,
   310  		MinTimeout: 10 * time.Second,
   311  		Delay:      30 * time.Second,
   312  	}
   313  
   314  	log.Printf("[DEBUG] Waiting for state to become available: %v", d.Id())
   315  	_, sterr := stateConf.WaitForState()
   316  	if sterr != nil {
   317  		return fmt.Errorf("Error waiting for elasticache (%s) to be created: %s", d.Id(), sterr)
   318  	}
   319  
   320  	return resourceAwsElasticacheClusterRead(d, meta)
   321  }
   322  
   323  func resourceAwsElasticacheClusterRead(d *schema.ResourceData, meta interface{}) error {
   324  	conn := meta.(*AWSClient).elasticacheconn
   325  	req := &elasticache.DescribeCacheClustersInput{
   326  		CacheClusterId:    aws.String(d.Id()),
   327  		ShowCacheNodeInfo: aws.Bool(true),
   328  	}
   329  
   330  	res, err := conn.DescribeCacheClusters(req)
   331  	if err != nil {
   332  		if eccErr, ok := err.(awserr.Error); ok && eccErr.Code() == "CacheClusterNotFound" {
   333  			log.Printf("[WARN] ElastiCache Cluster (%s) not found", d.Id())
   334  			d.SetId("")
   335  			return nil
   336  		}
   337  
   338  		return err
   339  	}
   340  
   341  	if len(res.CacheClusters) == 1 {
   342  		c := res.CacheClusters[0]
   343  		d.Set("cluster_id", c.CacheClusterId)
   344  		d.Set("node_type", c.CacheNodeType)
   345  		d.Set("num_cache_nodes", c.NumCacheNodes)
   346  		d.Set("engine", c.Engine)
   347  		d.Set("engine_version", c.EngineVersion)
   348  		if c.ConfigurationEndpoint != nil {
   349  			d.Set("port", c.ConfigurationEndpoint.Port)
   350  			d.Set("configuration_endpoint", aws.String(fmt.Sprintf("%s:%d", *c.ConfigurationEndpoint.Address, *c.ConfigurationEndpoint.Port)))
   351  		}
   352  
   353  		if c.ReplicationGroupId != nil {
   354  			d.Set("replication_group_id", c.ReplicationGroupId)
   355  		}
   356  
   357  		d.Set("subnet_group_name", c.CacheSubnetGroupName)
   358  		d.Set("security_group_names", c.CacheSecurityGroups)
   359  		d.Set("security_group_ids", c.SecurityGroups)
   360  		d.Set("parameter_group_name", c.CacheParameterGroup)
   361  		d.Set("maintenance_window", c.PreferredMaintenanceWindow)
   362  		d.Set("snapshot_window", c.SnapshotWindow)
   363  		d.Set("snapshot_retention_limit", c.SnapshotRetentionLimit)
   364  		if c.NotificationConfiguration != nil {
   365  			if *c.NotificationConfiguration.TopicStatus == "active" {
   366  				d.Set("notification_topic_arn", c.NotificationConfiguration.TopicArn)
   367  			}
   368  		}
   369  		d.Set("availability_zone", c.PreferredAvailabilityZone)
   370  
   371  		if err := setCacheNodeData(d, c); err != nil {
   372  			return err
   373  		}
   374  		// list tags for resource
   375  		// set tags
   376  		arn, err := buildECARN(d.Id(), meta.(*AWSClient).accountid, meta.(*AWSClient).region)
   377  		if err != nil {
   378  			log.Printf("[DEBUG] Error building ARN for ElastiCache Cluster, not setting Tags for cluster %s", *c.CacheClusterId)
   379  		} else {
   380  			resp, err := conn.ListTagsForResource(&elasticache.ListTagsForResourceInput{
   381  				ResourceName: aws.String(arn),
   382  			})
   383  
   384  			if err != nil {
   385  				log.Printf("[DEBUG] Error retrieving tags for ARN: %s", arn)
   386  			}
   387  
   388  			var et []*elasticache.Tag
   389  			if len(resp.TagList) > 0 {
   390  				et = resp.TagList
   391  			}
   392  			d.Set("tags", tagsToMapEC(et))
   393  		}
   394  	}
   395  
   396  	return nil
   397  }
   398  
   399  func resourceAwsElasticacheClusterUpdate(d *schema.ResourceData, meta interface{}) error {
   400  	conn := meta.(*AWSClient).elasticacheconn
   401  	arn, err := buildECARN(d.Id(), meta.(*AWSClient).accountid, meta.(*AWSClient).region)
   402  	if err != nil {
   403  		log.Printf("[DEBUG] Error building ARN for ElastiCache Cluster, not updating Tags for cluster %s", d.Id())
   404  	} else {
   405  		if err := setTagsEC(conn, d, arn); err != nil {
   406  			return err
   407  		}
   408  	}
   409  
   410  	req := &elasticache.ModifyCacheClusterInput{
   411  		CacheClusterId:   aws.String(d.Id()),
   412  		ApplyImmediately: aws.Bool(d.Get("apply_immediately").(bool)),
   413  	}
   414  
   415  	requestUpdate := false
   416  	if d.HasChange("security_group_ids") {
   417  		if attr := d.Get("security_group_ids").(*schema.Set); attr.Len() > 0 {
   418  			req.SecurityGroupIds = expandStringList(attr.List())
   419  			requestUpdate = true
   420  		}
   421  	}
   422  
   423  	if d.HasChange("parameter_group_name") {
   424  		req.CacheParameterGroupName = aws.String(d.Get("parameter_group_name").(string))
   425  		requestUpdate = true
   426  	}
   427  
   428  	if d.HasChange("maintenance_window") {
   429  		req.PreferredMaintenanceWindow = aws.String(d.Get("maintenance_window").(string))
   430  		requestUpdate = true
   431  	}
   432  
   433  	if d.HasChange("notification_topic_arn") {
   434  		v := d.Get("notification_topic_arn").(string)
   435  		req.NotificationTopicArn = aws.String(v)
   436  		if v == "" {
   437  			inactive := "inactive"
   438  			req.NotificationTopicStatus = &inactive
   439  		}
   440  		requestUpdate = true
   441  	}
   442  
   443  	if d.HasChange("engine_version") {
   444  		req.EngineVersion = aws.String(d.Get("engine_version").(string))
   445  		requestUpdate = true
   446  	}
   447  
   448  	if d.HasChange("snapshot_window") {
   449  		req.SnapshotWindow = aws.String(d.Get("snapshot_window").(string))
   450  		requestUpdate = true
   451  	}
   452  
   453  	if d.HasChange("node_type") {
   454  		req.CacheNodeType = aws.String(d.Get("node_type").(string))
   455  		requestUpdate = true
   456  	}
   457  
   458  	if d.HasChange("snapshot_retention_limit") {
   459  		req.SnapshotRetentionLimit = aws.Int64(int64(d.Get("snapshot_retention_limit").(int)))
   460  		requestUpdate = true
   461  	}
   462  
   463  	if d.HasChange("num_cache_nodes") {
   464  		oraw, nraw := d.GetChange("num_cache_nodes")
   465  		o := oraw.(int)
   466  		n := nraw.(int)
   467  		if v, ok := d.GetOk("az_mode"); ok && v.(string) == "cross-az" && n == 1 {
   468  			return fmt.Errorf("[WARN] Error updateing Elasticache cluster (%s), error: Cross-AZ mode is not supported in a single cache node.", d.Id())
   469  		}
   470  		if n < o {
   471  			log.Printf("[INFO] Cluster %s is marked for Decreasing cache nodes from %d to %d", d.Id(), o, n)
   472  			nodesToRemove := getCacheNodesToRemove(d, o, o-n)
   473  			req.CacheNodeIdsToRemove = nodesToRemove
   474  		}
   475  
   476  		req.NumCacheNodes = aws.Int64(int64(d.Get("num_cache_nodes").(int)))
   477  		requestUpdate = true
   478  
   479  	}
   480  
   481  	if requestUpdate {
   482  		log.Printf("[DEBUG] Modifying ElastiCache Cluster (%s), opts:\n%s", d.Id(), req)
   483  		_, err := conn.ModifyCacheCluster(req)
   484  		if err != nil {
   485  			return fmt.Errorf("[WARN] Error updating ElastiCache cluster (%s), error: %s", d.Id(), err)
   486  		}
   487  
   488  		log.Printf("[DEBUG] Waiting for update: %s", d.Id())
   489  		pending := []string{"modifying", "rebooting cache cluster nodes", "snapshotting"}
   490  		stateConf := &resource.StateChangeConf{
   491  			Pending:    pending,
   492  			Target:     []string{"available"},
   493  			Refresh:    cacheClusterStateRefreshFunc(conn, d.Id(), "available", pending),
   494  			Timeout:    80 * time.Minute,
   495  			MinTimeout: 10 * time.Second,
   496  			Delay:      30 * time.Second,
   497  		}
   498  
   499  		_, sterr := stateConf.WaitForState()
   500  		if sterr != nil {
   501  			return fmt.Errorf("Error waiting for elasticache (%s) to update: %s", d.Id(), sterr)
   502  		}
   503  	}
   504  
   505  	return resourceAwsElasticacheClusterRead(d, meta)
   506  }
   507  
   508  func getCacheNodesToRemove(d *schema.ResourceData, oldNumberOfNodes int, cacheNodesToRemove int) []*string {
   509  	nodesIdsToRemove := []*string{}
   510  	for i := oldNumberOfNodes; i > oldNumberOfNodes-cacheNodesToRemove && i > 0; i-- {
   511  		s := fmt.Sprintf("%04d", i)
   512  		nodesIdsToRemove = append(nodesIdsToRemove, &s)
   513  	}
   514  
   515  	return nodesIdsToRemove
   516  }
   517  
   518  func setCacheNodeData(d *schema.ResourceData, c *elasticache.CacheCluster) error {
   519  	sortedCacheNodes := make([]*elasticache.CacheNode, len(c.CacheNodes))
   520  	copy(sortedCacheNodes, c.CacheNodes)
   521  	sort.Sort(byCacheNodeId(sortedCacheNodes))
   522  
   523  	cacheNodeData := make([]map[string]interface{}, 0, len(sortedCacheNodes))
   524  
   525  	for _, node := range sortedCacheNodes {
   526  		if node.CacheNodeId == nil || node.Endpoint == nil || node.Endpoint.Address == nil || node.Endpoint.Port == nil || node.CustomerAvailabilityZone == nil {
   527  			return fmt.Errorf("Unexpected nil pointer in: %s", node)
   528  		}
   529  		cacheNodeData = append(cacheNodeData, map[string]interface{}{
   530  			"id":                *node.CacheNodeId,
   531  			"address":           *node.Endpoint.Address,
   532  			"port":              int(*node.Endpoint.Port),
   533  			"availability_zone": *node.CustomerAvailabilityZone,
   534  		})
   535  	}
   536  
   537  	return d.Set("cache_nodes", cacheNodeData)
   538  }
   539  
   540  type byCacheNodeId []*elasticache.CacheNode
   541  
   542  func (b byCacheNodeId) Len() int      { return len(b) }
   543  func (b byCacheNodeId) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
   544  func (b byCacheNodeId) Less(i, j int) bool {
   545  	return b[i].CacheNodeId != nil && b[j].CacheNodeId != nil &&
   546  		*b[i].CacheNodeId < *b[j].CacheNodeId
   547  }
   548  
   549  func resourceAwsElasticacheClusterDelete(d *schema.ResourceData, meta interface{}) error {
   550  	conn := meta.(*AWSClient).elasticacheconn
   551  
   552  	req := &elasticache.DeleteCacheClusterInput{
   553  		CacheClusterId: aws.String(d.Id()),
   554  	}
   555  	_, err := conn.DeleteCacheCluster(req)
   556  	if err != nil {
   557  		return err
   558  	}
   559  
   560  	log.Printf("[DEBUG] Waiting for deletion: %v", d.Id())
   561  	stateConf := &resource.StateChangeConf{
   562  		Pending:    []string{"creating", "available", "deleting", "incompatible-parameters", "incompatible-network", "restore-failed"},
   563  		Target:     []string{},
   564  		Refresh:    cacheClusterStateRefreshFunc(conn, d.Id(), "", []string{}),
   565  		Timeout:    40 * time.Minute,
   566  		MinTimeout: 10 * time.Second,
   567  		Delay:      30 * time.Second,
   568  	}
   569  
   570  	_, sterr := stateConf.WaitForState()
   571  	if sterr != nil {
   572  		return fmt.Errorf("Error waiting for elasticache (%s) to delete: %s", d.Id(), sterr)
   573  	}
   574  
   575  	d.SetId("")
   576  
   577  	return nil
   578  }
   579  
   580  func cacheClusterStateRefreshFunc(conn *elasticache.ElastiCache, clusterID, givenState string, pending []string) resource.StateRefreshFunc {
   581  	return func() (interface{}, string, error) {
   582  		resp, err := conn.DescribeCacheClusters(&elasticache.DescribeCacheClustersInput{
   583  			CacheClusterId:    aws.String(clusterID),
   584  			ShowCacheNodeInfo: aws.Bool(true),
   585  		})
   586  		if err != nil {
   587  			apierr := err.(awserr.Error)
   588  			log.Printf("[DEBUG] message: %v, code: %v", apierr.Message(), apierr.Code())
   589  			if apierr.Message() == fmt.Sprintf("CacheCluster not found: %v", clusterID) {
   590  				log.Printf("[DEBUG] Detect deletion")
   591  				return nil, "", nil
   592  			}
   593  
   594  			log.Printf("[ERROR] CacheClusterStateRefreshFunc: %s", err)
   595  			return nil, "", err
   596  		}
   597  
   598  		if len(resp.CacheClusters) == 0 {
   599  			return nil, "", fmt.Errorf("[WARN] Error: no Cache Clusters found for id (%s)", clusterID)
   600  		}
   601  
   602  		var c *elasticache.CacheCluster
   603  		for _, cluster := range resp.CacheClusters {
   604  			if *cluster.CacheClusterId == clusterID {
   605  				log.Printf("[DEBUG] Found matching ElastiCache cluster: %s", *cluster.CacheClusterId)
   606  				c = cluster
   607  			}
   608  		}
   609  
   610  		if c == nil {
   611  			return nil, "", fmt.Errorf("[WARN] Error: no matching Elastic Cache cluster for id (%s)", clusterID)
   612  		}
   613  
   614  		log.Printf("[DEBUG] ElastiCache Cluster (%s) status: %v", clusterID, *c.CacheClusterStatus)
   615  
   616  		// return the current state if it's in the pending array
   617  		for _, p := range pending {
   618  			log.Printf("[DEBUG] ElastiCache: checking pending state (%s) for cluster (%s), cluster status: %s", pending, clusterID, *c.CacheClusterStatus)
   619  			s := *c.CacheClusterStatus
   620  			if p == s {
   621  				log.Printf("[DEBUG] Return with status: %v", *c.CacheClusterStatus)
   622  				return c, p, nil
   623  			}
   624  		}
   625  
   626  		// return given state if it's not in pending
   627  		if givenState != "" {
   628  			log.Printf("[DEBUG] ElastiCache: checking given state (%s) of cluster (%s) against cluster status (%s)", givenState, clusterID, *c.CacheClusterStatus)
   629  			// check to make sure we have the node count we're expecting
   630  			if int64(len(c.CacheNodes)) != *c.NumCacheNodes {
   631  				log.Printf("[DEBUG] Node count is not what is expected: %d found, %d expected", len(c.CacheNodes), *c.NumCacheNodes)
   632  				return nil, "creating", nil
   633  			}
   634  
   635  			log.Printf("[DEBUG] Node count matched (%d)", len(c.CacheNodes))
   636  			// loop the nodes and check their status as well
   637  			for _, n := range c.CacheNodes {
   638  				log.Printf("[DEBUG] Checking cache node for status: %s", n)
   639  				if n.CacheNodeStatus != nil && *n.CacheNodeStatus != "available" {
   640  					log.Printf("[DEBUG] Node (%s) is not yet available, status: %s", *n.CacheNodeId, *n.CacheNodeStatus)
   641  					return nil, "creating", nil
   642  				}
   643  				log.Printf("[DEBUG] Cache node not in expected state")
   644  			}
   645  			log.Printf("[DEBUG] ElastiCache returning given state (%s), cluster: %s", givenState, c)
   646  			return c, givenState, nil
   647  		}
   648  		log.Printf("[DEBUG] current status: %v", *c.CacheClusterStatus)
   649  		return c, *c.CacheClusterStatus, nil
   650  	}
   651  }
   652  
   653  func buildECARN(identifier, accountid, region string) (string, error) {
   654  	if accountid == "" {
   655  		return "", fmt.Errorf("Unable to construct ElastiCache ARN because of missing AWS Account ID")
   656  	}
   657  	arn := fmt.Sprintf("arn:aws:elasticache:%s:%s:cluster:%s", region, accountid, identifier)
   658  	return arn, nil
   659  
   660  }