github.com/jdextraze/terraform@v0.6.17-0.20160511153921-e33847c8a8af/builtin/providers/aws/resource_aws_redshift_cluster.go (about) 1 package aws 2 3 import ( 4 "fmt" 5 "log" 6 "regexp" 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/redshift" 13 "github.com/hashicorp/terraform/helper/resource" 14 "github.com/hashicorp/terraform/helper/schema" 15 ) 16 17 func resourceAwsRedshiftCluster() *schema.Resource { 18 return &schema.Resource{ 19 Create: resourceAwsRedshiftClusterCreate, 20 Read: resourceAwsRedshiftClusterRead, 21 Update: resourceAwsRedshiftClusterUpdate, 22 Delete: resourceAwsRedshiftClusterDelete, 23 24 Schema: map[string]*schema.Schema{ 25 "database_name": &schema.Schema{ 26 Type: schema.TypeString, 27 Optional: true, 28 Computed: true, 29 ValidateFunc: validateRedshiftClusterDbName, 30 }, 31 32 "cluster_identifier": &schema.Schema{ 33 Type: schema.TypeString, 34 Required: true, 35 ForceNew: true, 36 ValidateFunc: validateRedshiftClusterIdentifier, 37 }, 38 "cluster_type": &schema.Schema{ 39 Type: schema.TypeString, 40 Optional: true, 41 Computed: true, 42 }, 43 44 "node_type": &schema.Schema{ 45 Type: schema.TypeString, 46 Required: true, 47 }, 48 49 "master_username": &schema.Schema{ 50 Type: schema.TypeString, 51 Required: true, 52 ValidateFunc: validateRedshiftClusterMasterUsername, 53 }, 54 55 "master_password": &schema.Schema{ 56 Type: schema.TypeString, 57 Required: true, 58 }, 59 60 "cluster_security_groups": &schema.Schema{ 61 Type: schema.TypeSet, 62 Optional: true, 63 Computed: true, 64 Elem: &schema.Schema{Type: schema.TypeString}, 65 Set: schema.HashString, 66 }, 67 68 "vpc_security_group_ids": &schema.Schema{ 69 Type: schema.TypeSet, 70 Optional: true, 71 Computed: true, 72 Elem: &schema.Schema{Type: schema.TypeString}, 73 Set: schema.HashString, 74 }, 75 76 "cluster_subnet_group_name": &schema.Schema{ 77 Type: schema.TypeString, 78 Optional: true, 79 ForceNew: true, 80 Computed: true, 81 }, 82 83 "availability_zone": &schema.Schema{ 84 Type: schema.TypeString, 85 Optional: true, 86 Computed: true, 87 }, 88 89 "preferred_maintenance_window": &schema.Schema{ 90 Type: schema.TypeString, 91 Optional: true, 92 Computed: true, 93 StateFunc: func(val interface{}) string { 94 if val == nil { 95 return "" 96 } 97 return strings.ToLower(val.(string)) 98 }, 99 }, 100 101 "cluster_parameter_group_name": &schema.Schema{ 102 Type: schema.TypeString, 103 Optional: true, 104 Computed: true, 105 }, 106 107 "automated_snapshot_retention_period": &schema.Schema{ 108 Type: schema.TypeInt, 109 Optional: true, 110 Default: 1, 111 ValidateFunc: func(v interface{}, k string) (ws []string, es []error) { 112 value := v.(int) 113 if value > 35 { 114 es = append(es, fmt.Errorf( 115 "backup retention period cannot be more than 35 days")) 116 } 117 return 118 }, 119 }, 120 121 "port": &schema.Schema{ 122 Type: schema.TypeInt, 123 Optional: true, 124 Default: 5439, 125 }, 126 127 "cluster_version": &schema.Schema{ 128 Type: schema.TypeString, 129 Optional: true, 130 Default: "1.0", 131 }, 132 133 "allow_version_upgrade": &schema.Schema{ 134 Type: schema.TypeBool, 135 Optional: true, 136 Default: true, 137 }, 138 139 "number_of_nodes": &schema.Schema{ 140 Type: schema.TypeInt, 141 Optional: true, 142 Default: 1, 143 }, 144 145 "publicly_accessible": &schema.Schema{ 146 Type: schema.TypeBool, 147 Optional: true, 148 Default: true, 149 }, 150 151 "encrypted": &schema.Schema{ 152 Type: schema.TypeBool, 153 Optional: true, 154 Computed: true, 155 }, 156 157 "elastic_ip": &schema.Schema{ 158 Type: schema.TypeString, 159 Optional: true, 160 }, 161 162 "final_snapshot_identifier": &schema.Schema{ 163 Type: schema.TypeString, 164 Optional: true, 165 ValidateFunc: validateRedshiftClusterFinalSnapshotIdentifier, 166 }, 167 168 "skip_final_snapshot": &schema.Schema{ 169 Type: schema.TypeBool, 170 Optional: true, 171 Default: true, 172 }, 173 174 "endpoint": &schema.Schema{ 175 Type: schema.TypeString, 176 Optional: true, 177 Computed: true, 178 }, 179 180 "cluster_public_key": &schema.Schema{ 181 Type: schema.TypeString, 182 Optional: true, 183 Computed: true, 184 }, 185 186 "cluster_revision_number": &schema.Schema{ 187 Type: schema.TypeString, 188 Optional: true, 189 Computed: true, 190 }, 191 }, 192 } 193 } 194 195 func resourceAwsRedshiftClusterCreate(d *schema.ResourceData, meta interface{}) error { 196 conn := meta.(*AWSClient).redshiftconn 197 198 log.Printf("[INFO] Building Redshift Cluster Options") 199 createOpts := &redshift.CreateClusterInput{ 200 ClusterIdentifier: aws.String(d.Get("cluster_identifier").(string)), 201 Port: aws.Int64(int64(d.Get("port").(int))), 202 MasterUserPassword: aws.String(d.Get("master_password").(string)), 203 MasterUsername: aws.String(d.Get("master_username").(string)), 204 ClusterVersion: aws.String(d.Get("cluster_version").(string)), 205 NodeType: aws.String(d.Get("node_type").(string)), 206 DBName: aws.String(d.Get("database_name").(string)), 207 AllowVersionUpgrade: aws.Bool(d.Get("allow_version_upgrade").(bool)), 208 PubliclyAccessible: aws.Bool(d.Get("publicly_accessible").(bool)), 209 AutomatedSnapshotRetentionPeriod: aws.Int64(int64(d.Get("automated_snapshot_retention_period").(int))), 210 } 211 212 if v := d.Get("number_of_nodes").(int); v > 1 { 213 createOpts.ClusterType = aws.String("multi-node") 214 createOpts.NumberOfNodes = aws.Int64(int64(d.Get("number_of_nodes").(int))) 215 } else { 216 createOpts.ClusterType = aws.String("single-node") 217 } 218 219 if v := d.Get("cluster_security_groups").(*schema.Set); v.Len() > 0 { 220 createOpts.ClusterSecurityGroups = expandStringList(v.List()) 221 } 222 223 if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 { 224 createOpts.VpcSecurityGroupIds = expandStringList(v.List()) 225 } 226 227 if v, ok := d.GetOk("cluster_subnet_group_name"); ok { 228 createOpts.ClusterSubnetGroupName = aws.String(v.(string)) 229 } 230 231 if v, ok := d.GetOk("availability_zone"); ok { 232 createOpts.AvailabilityZone = aws.String(v.(string)) 233 } 234 235 if v, ok := d.GetOk("preferred_maintenance_window"); ok { 236 createOpts.PreferredMaintenanceWindow = aws.String(v.(string)) 237 } 238 239 if v, ok := d.GetOk("cluster_parameter_group_name"); ok { 240 createOpts.ClusterParameterGroupName = aws.String(v.(string)) 241 } 242 243 if v, ok := d.GetOk("encrypted"); ok { 244 createOpts.Encrypted = aws.Bool(v.(bool)) 245 } 246 247 if v, ok := d.GetOk("elastic_ip"); ok { 248 createOpts.ElasticIp = aws.String(v.(string)) 249 } 250 251 log.Printf("[DEBUG] Redshift Cluster create options: %s", createOpts) 252 resp, err := conn.CreateCluster(createOpts) 253 if err != nil { 254 log.Printf("[ERROR] Error creating Redshift Cluster: %s", err) 255 return err 256 } 257 258 log.Printf("[DEBUG]: Cluster create response: %s", resp) 259 d.SetId(*resp.Cluster.ClusterIdentifier) 260 261 stateConf := &resource.StateChangeConf{ 262 Pending: []string{"creating", "backing-up", "modifying"}, 263 Target: []string{"available"}, 264 Refresh: resourceAwsRedshiftClusterStateRefreshFunc(d, meta), 265 Timeout: 40 * time.Minute, 266 MinTimeout: 10 * time.Second, 267 } 268 269 _, err = stateConf.WaitForState() 270 if err != nil { 271 return fmt.Errorf("[WARN] Error waiting for Redshift Cluster state to be \"available\": %s", err) 272 } 273 274 return resourceAwsRedshiftClusterRead(d, meta) 275 } 276 277 func resourceAwsRedshiftClusterRead(d *schema.ResourceData, meta interface{}) error { 278 conn := meta.(*AWSClient).redshiftconn 279 280 log.Printf("[INFO] Reading Redshift Cluster Information: %s", d.Id()) 281 resp, err := conn.DescribeClusters(&redshift.DescribeClustersInput{ 282 ClusterIdentifier: aws.String(d.Id()), 283 }) 284 285 if err != nil { 286 if awsErr, ok := err.(awserr.Error); ok { 287 if "ClusterNotFound" == awsErr.Code() { 288 d.SetId("") 289 log.Printf("[DEBUG] Redshift Cluster (%s) not found", d.Id()) 290 return nil 291 } 292 } 293 log.Printf("[DEBUG] Error describing Redshift Cluster (%s)", d.Id()) 294 return err 295 } 296 297 var rsc *redshift.Cluster 298 for _, c := range resp.Clusters { 299 if *c.ClusterIdentifier == d.Id() { 300 rsc = c 301 } 302 } 303 304 if rsc == nil { 305 log.Printf("[WARN] Redshift Cluster (%s) not found", d.Id()) 306 d.SetId("") 307 return nil 308 } 309 310 d.Set("database_name", rsc.DBName) 311 d.Set("cluster_subnet_group_name", rsc.ClusterSubnetGroupName) 312 d.Set("availability_zone", rsc.AvailabilityZone) 313 d.Set("encrypted", rsc.Encrypted) 314 d.Set("automated_snapshot_retention_period", rsc.AutomatedSnapshotRetentionPeriod) 315 d.Set("preferred_maintenance_window", rsc.PreferredMaintenanceWindow) 316 if rsc.Endpoint != nil && rsc.Endpoint.Address != nil { 317 endpoint := *rsc.Endpoint.Address 318 if rsc.Endpoint.Port != nil { 319 endpoint = fmt.Sprintf("%s:%d", endpoint, *rsc.Endpoint.Port) 320 } 321 d.Set("endpoint", endpoint) 322 } 323 d.Set("cluster_parameter_group_name", rsc.ClusterParameterGroups[0].ParameterGroupName) 324 if len(rsc.ClusterNodes) > 1 { 325 d.Set("cluster_type", "multi-node") 326 } else { 327 d.Set("cluster_type", "single-node") 328 } 329 330 var vpcg []string 331 for _, g := range rsc.VpcSecurityGroups { 332 vpcg = append(vpcg, *g.VpcSecurityGroupId) 333 } 334 if err := d.Set("vpc_security_group_ids", vpcg); err != nil { 335 return fmt.Errorf("[DEBUG] Error saving VPC Security Group IDs to state for Redshift Cluster (%s): %s", d.Id(), err) 336 } 337 338 var csg []string 339 for _, g := range rsc.ClusterSecurityGroups { 340 csg = append(csg, *g.ClusterSecurityGroupName) 341 } 342 if err := d.Set("cluster_security_groups", csg); err != nil { 343 return fmt.Errorf("[DEBUG] Error saving Cluster Security Group Names to state for Redshift Cluster (%s): %s", d.Id(), err) 344 } 345 346 d.Set("cluster_public_key", rsc.ClusterPublicKey) 347 d.Set("cluster_revision_number", rsc.ClusterRevisionNumber) 348 349 return nil 350 } 351 352 func resourceAwsRedshiftClusterUpdate(d *schema.ResourceData, meta interface{}) error { 353 conn := meta.(*AWSClient).redshiftconn 354 355 log.Printf("[INFO] Building Redshift Modify Cluster Options") 356 req := &redshift.ModifyClusterInput{ 357 ClusterIdentifier: aws.String(d.Id()), 358 } 359 360 if d.HasChange("cluster_type") { 361 req.ClusterType = aws.String(d.Get("cluster_type").(string)) 362 } 363 364 if d.HasChange("node_type") { 365 req.NodeType = aws.String(d.Get("node_type").(string)) 366 } 367 368 if d.HasChange("number_of_nodes") { 369 if v := d.Get("number_of_nodes").(int); v > 1 { 370 req.ClusterType = aws.String("multi-node") 371 req.NumberOfNodes = aws.Int64(int64(d.Get("number_of_nodes").(int))) 372 } else { 373 req.ClusterType = aws.String("single-node") 374 } 375 req.NodeType = aws.String(d.Get("node_type").(string)) 376 } 377 378 if d.HasChange("cluster_security_groups") { 379 req.ClusterSecurityGroups = expandStringList(d.Get("cluster_security_groups").(*schema.Set).List()) 380 } 381 382 if d.HasChange("vpc_security_group_ips") { 383 req.VpcSecurityGroupIds = expandStringList(d.Get("vpc_security_group_ips").(*schema.Set).List()) 384 } 385 386 if d.HasChange("master_password") { 387 req.MasterUserPassword = aws.String(d.Get("master_password").(string)) 388 } 389 390 if d.HasChange("cluster_parameter_group_name") { 391 req.ClusterParameterGroupName = aws.String(d.Get("cluster_parameter_group_name").(string)) 392 } 393 394 if d.HasChange("automated_snapshot_retention_period") { 395 req.AutomatedSnapshotRetentionPeriod = aws.Int64(int64(d.Get("automated_snapshot_retention_period").(int))) 396 } 397 398 if d.HasChange("preferred_maintenance_window") { 399 req.PreferredMaintenanceWindow = aws.String(d.Get("preferred_maintenance_window").(string)) 400 } 401 402 if d.HasChange("cluster_version") { 403 req.ClusterVersion = aws.String(d.Get("cluster_version").(string)) 404 } 405 406 if d.HasChange("allow_version_upgrade") { 407 req.AllowVersionUpgrade = aws.Bool(d.Get("allow_version_upgrade").(bool)) 408 } 409 410 if d.HasChange("publicly_accessible") { 411 req.PubliclyAccessible = aws.Bool(d.Get("publicly_accessible").(bool)) 412 } 413 414 log.Printf("[INFO] Modifying Redshift Cluster: %s", d.Id()) 415 log.Printf("[DEBUG] Redshift Cluster Modify options: %s", req) 416 _, err := conn.ModifyCluster(req) 417 if err != nil { 418 return fmt.Errorf("[WARN] Error modifying Redshift Cluster (%s): %s", d.Id(), err) 419 } 420 421 stateConf := &resource.StateChangeConf{ 422 Pending: []string{"creating", "deleting", "rebooting", "resizing", "renaming", "modifying"}, 423 Target: []string{"available"}, 424 Refresh: resourceAwsRedshiftClusterStateRefreshFunc(d, meta), 425 Timeout: 40 * time.Minute, 426 MinTimeout: 10 * time.Second, 427 } 428 429 // Wait, catching any errors 430 _, err = stateConf.WaitForState() 431 if err != nil { 432 return fmt.Errorf("[WARN] Error Modifying Redshift Cluster (%s): %s", d.Id(), err) 433 } 434 435 return resourceAwsRedshiftClusterRead(d, meta) 436 } 437 438 func resourceAwsRedshiftClusterDelete(d *schema.ResourceData, meta interface{}) error { 439 conn := meta.(*AWSClient).redshiftconn 440 log.Printf("[DEBUG] Destroying Redshift Cluster (%s)", d.Id()) 441 442 deleteOpts := redshift.DeleteClusterInput{ 443 ClusterIdentifier: aws.String(d.Id()), 444 } 445 446 skipFinalSnapshot := d.Get("skip_final_snapshot").(bool) 447 deleteOpts.SkipFinalClusterSnapshot = aws.Bool(skipFinalSnapshot) 448 449 if !skipFinalSnapshot { 450 if name, present := d.GetOk("final_snapshot_identifier"); present { 451 deleteOpts.FinalClusterSnapshotIdentifier = aws.String(name.(string)) 452 } else { 453 return fmt.Errorf("Redshift Cluster Instance FinalSnapshotIdentifier is required when a final snapshot is required") 454 } 455 } 456 457 log.Printf("[DEBUG] Redshift Cluster delete options: %s", deleteOpts) 458 _, err := conn.DeleteCluster(&deleteOpts) 459 if err != nil { 460 return fmt.Errorf("[ERROR] Error deleting Redshift Cluster (%s): %s", d.Id(), err) 461 } 462 463 stateConf := &resource.StateChangeConf{ 464 Pending: []string{"available", "creating", "deleting", "rebooting", "resizing", "renaming"}, 465 Target: []string{"destroyed"}, 466 Refresh: resourceAwsRedshiftClusterStateRefreshFunc(d, meta), 467 Timeout: 40 * time.Minute, 468 MinTimeout: 5 * time.Second, 469 } 470 471 // Wait, catching any errors 472 _, err = stateConf.WaitForState() 473 if err != nil { 474 return fmt.Errorf("[ERROR] Error deleting Redshift Cluster (%s): %s", d.Id(), err) 475 } 476 477 log.Printf("[INFO] Redshift Cluster %s successfully deleted", d.Id()) 478 479 return nil 480 } 481 482 func resourceAwsRedshiftClusterStateRefreshFunc(d *schema.ResourceData, meta interface{}) resource.StateRefreshFunc { 483 return func() (interface{}, string, error) { 484 conn := meta.(*AWSClient).redshiftconn 485 486 log.Printf("[INFO] Reading Redshift Cluster Information: %s", d.Id()) 487 resp, err := conn.DescribeClusters(&redshift.DescribeClustersInput{ 488 ClusterIdentifier: aws.String(d.Id()), 489 }) 490 491 if err != nil { 492 if awsErr, ok := err.(awserr.Error); ok { 493 if "ClusterNotFound" == awsErr.Code() { 494 return 42, "destroyed", nil 495 } 496 } 497 log.Printf("[WARN] Error on retrieving Redshift Cluster (%s) when waiting: %s", d.Id(), err) 498 return nil, "", err 499 } 500 501 var rsc *redshift.Cluster 502 503 for _, c := range resp.Clusters { 504 if *c.ClusterIdentifier == d.Id() { 505 rsc = c 506 } 507 } 508 509 if rsc == nil { 510 return 42, "destroyed", nil 511 } 512 513 if rsc.ClusterStatus != nil { 514 log.Printf("[DEBUG] Redshift Cluster status (%s): %s", d.Id(), *rsc.ClusterStatus) 515 } 516 517 return rsc, *rsc.ClusterStatus, nil 518 } 519 } 520 521 func validateRedshiftClusterIdentifier(v interface{}, k string) (ws []string, errors []error) { 522 value := v.(string) 523 if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { 524 errors = append(errors, fmt.Errorf( 525 "only lowercase alphanumeric characters and hyphens allowed in %q", k)) 526 } 527 if !regexp.MustCompile(`^[a-z]`).MatchString(value) { 528 errors = append(errors, fmt.Errorf( 529 "first character of %q must be a letter", k)) 530 } 531 if regexp.MustCompile(`--`).MatchString(value) { 532 errors = append(errors, fmt.Errorf( 533 "%q cannot contain two consecutive hyphens", k)) 534 } 535 if regexp.MustCompile(`-$`).MatchString(value) { 536 errors = append(errors, fmt.Errorf( 537 "%q cannot end with a hyphen", k)) 538 } 539 return 540 } 541 542 func validateRedshiftClusterDbName(v interface{}, k string) (ws []string, errors []error) { 543 value := v.(string) 544 if !regexp.MustCompile(`^[a-z]+$`).MatchString(value) { 545 errors = append(errors, fmt.Errorf( 546 "only lowercase letters characters allowed in %q", k)) 547 } 548 if len(value) > 64 { 549 errors = append(errors, fmt.Errorf( 550 "%q cannot be longer than 64 characters: %q", k, value)) 551 } 552 if value == "" { 553 errors = append(errors, fmt.Errorf( 554 "%q cannot be an empty string", k)) 555 } 556 557 return 558 } 559 560 func validateRedshiftClusterFinalSnapshotIdentifier(v interface{}, k string) (ws []string, errors []error) { 561 value := v.(string) 562 if !regexp.MustCompile(`^[0-9A-Za-z-]+$`).MatchString(value) { 563 errors = append(errors, fmt.Errorf( 564 "only alphanumeric characters and hyphens allowed in %q", k)) 565 } 566 if regexp.MustCompile(`--`).MatchString(value) { 567 errors = append(errors, fmt.Errorf("%q cannot contain two consecutive hyphens", k)) 568 } 569 if regexp.MustCompile(`-$`).MatchString(value) { 570 errors = append(errors, fmt.Errorf("%q cannot end in a hyphen", k)) 571 } 572 if len(value) > 255 { 573 errors = append(errors, fmt.Errorf("%q cannot be more than 255 characters", k)) 574 } 575 return 576 } 577 578 func validateRedshiftClusterMasterUsername(v interface{}, k string) (ws []string, errors []error) { 579 value := v.(string) 580 if !regexp.MustCompile(`^\w+$`).MatchString(value) { 581 errors = append(errors, fmt.Errorf( 582 "only alphanumeric characters in %q", k)) 583 } 584 if !regexp.MustCompile(`^[A-Za-z]`).MatchString(value) { 585 errors = append(errors, fmt.Errorf( 586 "first character of %q must be a letter", k)) 587 } 588 if len(value) > 128 { 589 errors = append(errors, fmt.Errorf("%q cannot be more than 128 characters", k)) 590 } 591 return 592 }