github.com/subuk/terraform@v0.6.14-0.20160317140351-de1567c2e732/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 ForceNew: true, 149 Default: true, 150 }, 151 152 "encrypted": &schema.Schema{ 153 Type: schema.TypeBool, 154 Optional: true, 155 Computed: true, 156 }, 157 158 "elastic_ip": &schema.Schema{ 159 Type: schema.TypeString, 160 Optional: true, 161 }, 162 163 "final_snapshot_identifier": &schema.Schema{ 164 Type: schema.TypeString, 165 Optional: true, 166 ValidateFunc: validateRedshiftClusterFinalSnapshotIdentifier, 167 }, 168 169 "skip_final_snapshot": &schema.Schema{ 170 Type: schema.TypeBool, 171 Optional: true, 172 Default: true, 173 }, 174 175 "endpoint": &schema.Schema{ 176 Type: schema.TypeString, 177 Optional: true, 178 Computed: true, 179 }, 180 181 "cluster_public_key": &schema.Schema{ 182 Type: schema.TypeString, 183 Optional: true, 184 Computed: true, 185 }, 186 187 "cluster_revision_number": &schema.Schema{ 188 Type: schema.TypeString, 189 Optional: true, 190 Computed: true, 191 }, 192 }, 193 } 194 } 195 196 func resourceAwsRedshiftClusterCreate(d *schema.ResourceData, meta interface{}) error { 197 conn := meta.(*AWSClient).redshiftconn 198 199 log.Printf("[INFO] Building Redshift Cluster Options") 200 createOpts := &redshift.CreateClusterInput{ 201 ClusterIdentifier: aws.String(d.Get("cluster_identifier").(string)), 202 Port: aws.Int64(int64(d.Get("port").(int))), 203 MasterUserPassword: aws.String(d.Get("master_password").(string)), 204 MasterUsername: aws.String(d.Get("master_username").(string)), 205 ClusterVersion: aws.String(d.Get("cluster_version").(string)), 206 NodeType: aws.String(d.Get("node_type").(string)), 207 DBName: aws.String(d.Get("database_name").(string)), 208 AllowVersionUpgrade: aws.Bool(d.Get("allow_version_upgrade").(bool)), 209 PubliclyAccessible: aws.Bool(d.Get("publicly_accessible").(bool)), 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("automated_snapshot_retention_period"); ok { 244 createOpts.AutomatedSnapshotRetentionPeriod = aws.Int64(int64(v.(int))) 245 } 246 247 if v, ok := d.GetOk("encrypted"); ok { 248 createOpts.Encrypted = aws.Bool(v.(bool)) 249 } 250 251 if v, ok := d.GetOk("elastic_ip"); ok { 252 createOpts.ElasticIp = aws.String(v.(string)) 253 } 254 255 log.Printf("[DEBUG] Redshift Cluster create options: %s", createOpts) 256 resp, err := conn.CreateCluster(createOpts) 257 if err != nil { 258 log.Printf("[ERROR] Error creating Redshift Cluster: %s", err) 259 return err 260 } 261 262 log.Printf("[DEBUG]: Cluster create response: %s", resp) 263 d.SetId(*resp.Cluster.ClusterIdentifier) 264 265 stateConf := &resource.StateChangeConf{ 266 Pending: []string{"creating", "backing-up", "modifying"}, 267 Target: []string{"available"}, 268 Refresh: resourceAwsRedshiftClusterStateRefreshFunc(d, meta), 269 Timeout: 5 * time.Minute, 270 MinTimeout: 3 * time.Second, 271 } 272 273 _, err = stateConf.WaitForState() 274 if err != nil { 275 return fmt.Errorf("[WARN] Error waiting for Redshift Cluster state to be \"available\": %s", err) 276 } 277 278 return resourceAwsRedshiftClusterRead(d, meta) 279 } 280 281 func resourceAwsRedshiftClusterRead(d *schema.ResourceData, meta interface{}) error { 282 conn := meta.(*AWSClient).redshiftconn 283 284 log.Printf("[INFO] Reading Redshift Cluster Information: %s", d.Id()) 285 resp, err := conn.DescribeClusters(&redshift.DescribeClustersInput{ 286 ClusterIdentifier: aws.String(d.Id()), 287 }) 288 289 if err != nil { 290 if awsErr, ok := err.(awserr.Error); ok { 291 if "ClusterNotFound" == awsErr.Code() { 292 d.SetId("") 293 log.Printf("[DEBUG] Redshift Cluster (%s) not found", d.Id()) 294 return nil 295 } 296 } 297 log.Printf("[DEBUG] Error describing Redshift Cluster (%s)", d.Id()) 298 return err 299 } 300 301 var rsc *redshift.Cluster 302 for _, c := range resp.Clusters { 303 if *c.ClusterIdentifier == d.Id() { 304 rsc = c 305 } 306 } 307 308 if rsc == nil { 309 log.Printf("[WARN] Redshift Cluster (%s) not found", d.Id()) 310 d.SetId("") 311 return nil 312 } 313 314 d.Set("database_name", rsc.DBName) 315 d.Set("cluster_subnet_group_name", rsc.ClusterSubnetGroupName) 316 d.Set("availability_zone", rsc.AvailabilityZone) 317 d.Set("encrypted", rsc.Encrypted) 318 d.Set("automated_snapshot_retention_period", rsc.AutomatedSnapshotRetentionPeriod) 319 d.Set("preferred_maintenance_window", rsc.PreferredMaintenanceWindow) 320 if rsc.Endpoint != nil && rsc.Endpoint.Address != nil { 321 endpoint := *rsc.Endpoint.Address 322 if rsc.Endpoint.Port != nil { 323 endpoint = fmt.Sprintf("%s:%d", endpoint, *rsc.Endpoint.Port) 324 } 325 d.Set("endpoint", endpoint) 326 } 327 d.Set("cluster_parameter_group_name", rsc.ClusterParameterGroups[0].ParameterGroupName) 328 if len(rsc.ClusterNodes) > 1 { 329 d.Set("cluster_type", "multi-node") 330 } else { 331 d.Set("cluster_type", "single-node") 332 } 333 334 var vpcg []string 335 for _, g := range rsc.VpcSecurityGroups { 336 vpcg = append(vpcg, *g.VpcSecurityGroupId) 337 } 338 if err := d.Set("vpc_security_group_ids", vpcg); err != nil { 339 return fmt.Errorf("[DEBUG] Error saving VPC Security Group IDs to state for Redshift Cluster (%s): %s", d.Id(), err) 340 } 341 342 var csg []string 343 for _, g := range rsc.ClusterSecurityGroups { 344 csg = append(csg, *g.ClusterSecurityGroupName) 345 } 346 if err := d.Set("cluster_security_groups", csg); err != nil { 347 return fmt.Errorf("[DEBUG] Error saving Cluster Security Group Names to state for Redshift Cluster (%s): %s", d.Id(), err) 348 } 349 350 d.Set("cluster_public_key", rsc.ClusterPublicKey) 351 d.Set("cluster_revision_number", rsc.ClusterRevisionNumber) 352 353 return nil 354 } 355 356 func resourceAwsRedshiftClusterUpdate(d *schema.ResourceData, meta interface{}) error { 357 conn := meta.(*AWSClient).redshiftconn 358 359 log.Printf("[INFO] Building Redshift Modify Cluster Options") 360 req := &redshift.ModifyClusterInput{ 361 ClusterIdentifier: aws.String(d.Id()), 362 } 363 364 if d.HasChange("cluster_type") { 365 req.ClusterType = aws.String(d.Get("cluster_type").(string)) 366 } 367 368 if d.HasChange("node_type") { 369 req.NodeType = aws.String(d.Get("node_type").(string)) 370 } 371 372 if d.HasChange("number_of_nodes") { 373 if v := d.Get("number_of_nodes").(int); v > 1 { 374 req.ClusterType = aws.String("multi-node") 375 req.NumberOfNodes = aws.Int64(int64(d.Get("number_of_nodes").(int))) 376 } else { 377 req.ClusterType = aws.String("single-node") 378 } 379 } 380 381 if d.HasChange("cluster_security_groups") { 382 req.ClusterSecurityGroups = expandStringList(d.Get("cluster_security_groups").(*schema.Set).List()) 383 } 384 385 if d.HasChange("vpc_security_group_ips") { 386 req.VpcSecurityGroupIds = expandStringList(d.Get("vpc_security_group_ips").(*schema.Set).List()) 387 } 388 389 if d.HasChange("master_password") { 390 req.MasterUserPassword = aws.String(d.Get("master_password").(string)) 391 } 392 393 if d.HasChange("cluster_parameter_group_name") { 394 req.ClusterParameterGroupName = aws.String(d.Get("cluster_parameter_group_name").(string)) 395 } 396 397 if d.HasChange("automated_snapshot_retention_period") { 398 req.AutomatedSnapshotRetentionPeriod = aws.Int64(int64(d.Get("automated_snapshot_retention_period").(int))) 399 } 400 401 if d.HasChange("preferred_maintenance_window") { 402 req.PreferredMaintenanceWindow = aws.String(d.Get("preferred_maintenance_window").(string)) 403 } 404 405 if d.HasChange("cluster_version") { 406 req.ClusterVersion = aws.String(d.Get("cluster_version").(string)) 407 } 408 409 if d.HasChange("allow_version_upgrade") { 410 req.AllowVersionUpgrade = aws.Bool(d.Get("allow_version_upgrade").(bool)) 411 } 412 413 log.Printf("[INFO] Modifying Redshift Cluster: %s", d.Id()) 414 log.Printf("[DEBUG] Redshift Cluster Modify options: %s", req) 415 _, err := conn.ModifyCluster(req) 416 if err != nil { 417 return fmt.Errorf("[WARN] Error modifying Redshift Cluster (%s): %s", d.Id(), err) 418 } 419 420 stateConf := &resource.StateChangeConf{ 421 Pending: []string{"creating", "deleting", "rebooting", "resizing", "renaming"}, 422 Target: []string{"available"}, 423 Refresh: resourceAwsRedshiftClusterStateRefreshFunc(d, meta), 424 Timeout: 10 * time.Minute, 425 MinTimeout: 5 * time.Second, 426 } 427 428 // Wait, catching any errors 429 _, err = stateConf.WaitForState() 430 if err != nil { 431 return fmt.Errorf("[WARN] Error Modifying Redshift Cluster (%s): %s", d.Id(), err) 432 } 433 434 return resourceAwsRedshiftClusterRead(d, meta) 435 } 436 437 func resourceAwsRedshiftClusterDelete(d *schema.ResourceData, meta interface{}) error { 438 conn := meta.(*AWSClient).redshiftconn 439 log.Printf("[DEBUG] Destroying Redshift Cluster (%s)", d.Id()) 440 441 deleteOpts := redshift.DeleteClusterInput{ 442 ClusterIdentifier: aws.String(d.Id()), 443 } 444 445 skipFinalSnapshot := d.Get("skip_final_snapshot").(bool) 446 deleteOpts.SkipFinalClusterSnapshot = aws.Bool(skipFinalSnapshot) 447 448 if !skipFinalSnapshot { 449 if name, present := d.GetOk("final_snapshot_identifier"); present { 450 deleteOpts.FinalClusterSnapshotIdentifier = aws.String(name.(string)) 451 } else { 452 return fmt.Errorf("Redshift Cluster Instance FinalSnapshotIdentifier is required when a final snapshot is required") 453 } 454 } 455 456 log.Printf("[DEBUG] Redshift Cluster delete options: %s", deleteOpts) 457 _, err := conn.DeleteCluster(&deleteOpts) 458 if err != nil { 459 return fmt.Errorf("[ERROR] Error deleting Redshift Cluster (%s): %s", d.Id(), err) 460 } 461 462 stateConf := &resource.StateChangeConf{ 463 Pending: []string{"available", "creating", "deleting", "rebooting", "resizing", "renaming"}, 464 Target: []string{"destroyed"}, 465 Refresh: resourceAwsRedshiftClusterStateRefreshFunc(d, meta), 466 Timeout: 40 * time.Minute, 467 MinTimeout: 5 * time.Second, 468 } 469 470 // Wait, catching any errors 471 _, err = stateConf.WaitForState() 472 if err != nil { 473 return fmt.Errorf("[ERROR] Error deleting Redshift Cluster (%s): %s", d.Id(), err) 474 } 475 476 log.Printf("[INFO] Redshift Cluster %s successfully deleted", d.Id()) 477 478 return nil 479 } 480 481 func resourceAwsRedshiftClusterStateRefreshFunc(d *schema.ResourceData, meta interface{}) resource.StateRefreshFunc { 482 return func() (interface{}, string, error) { 483 conn := meta.(*AWSClient).redshiftconn 484 485 log.Printf("[INFO] Reading Redshift Cluster Information: %s", d.Id()) 486 resp, err := conn.DescribeClusters(&redshift.DescribeClustersInput{ 487 ClusterIdentifier: aws.String(d.Id()), 488 }) 489 490 if err != nil { 491 if awsErr, ok := err.(awserr.Error); ok { 492 if "ClusterNotFound" == awsErr.Code() { 493 return 42, "destroyed", nil 494 } 495 } 496 log.Printf("[WARN] Error on retrieving Redshift Cluster (%s) when waiting: %s", d.Id(), err) 497 return nil, "", err 498 } 499 500 var rsc *redshift.Cluster 501 502 for _, c := range resp.Clusters { 503 if *c.ClusterIdentifier == d.Id() { 504 rsc = c 505 } 506 } 507 508 if rsc == nil { 509 return 42, "destroyed", nil 510 } 511 512 if rsc.ClusterStatus != nil { 513 log.Printf("[DEBUG] Redshift Cluster status (%s): %s", d.Id(), *rsc.ClusterStatus) 514 } 515 516 return rsc, *rsc.ClusterStatus, nil 517 } 518 } 519 520 func validateRedshiftClusterIdentifier(v interface{}, k string) (ws []string, errors []error) { 521 value := v.(string) 522 if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { 523 errors = append(errors, fmt.Errorf( 524 "only lowercase alphanumeric characters and hyphens allowed in %q", k)) 525 } 526 if !regexp.MustCompile(`^[a-z]`).MatchString(value) { 527 errors = append(errors, fmt.Errorf( 528 "first character of %q must be a letter", k)) 529 } 530 if regexp.MustCompile(`--`).MatchString(value) { 531 errors = append(errors, fmt.Errorf( 532 "%q cannot contain two consecutive hyphens", k)) 533 } 534 if regexp.MustCompile(`-$`).MatchString(value) { 535 errors = append(errors, fmt.Errorf( 536 "%q cannot end with a hyphen", k)) 537 } 538 return 539 } 540 541 func validateRedshiftClusterDbName(v interface{}, k string) (ws []string, errors []error) { 542 value := v.(string) 543 if !regexp.MustCompile(`^[a-z]+$`).MatchString(value) { 544 errors = append(errors, fmt.Errorf( 545 "only lowercase letters characters allowed in %q", k)) 546 } 547 if len(value) > 64 { 548 errors = append(errors, fmt.Errorf( 549 "%q cannot be longer than 64 characters: %q", k, value)) 550 } 551 if value == "" { 552 errors = append(errors, fmt.Errorf( 553 "%q cannot be an empty string", k)) 554 } 555 556 return 557 } 558 559 func validateRedshiftClusterFinalSnapshotIdentifier(v interface{}, k string) (ws []string, errors []error) { 560 value := v.(string) 561 if !regexp.MustCompile(`^[0-9A-Za-z-]+$`).MatchString(value) { 562 errors = append(errors, fmt.Errorf( 563 "only alphanumeric characters and hyphens allowed in %q", k)) 564 } 565 if regexp.MustCompile(`--`).MatchString(value) { 566 errors = append(errors, fmt.Errorf("%q cannot contain two consecutive hyphens", k)) 567 } 568 if regexp.MustCompile(`-$`).MatchString(value) { 569 errors = append(errors, fmt.Errorf("%q cannot end in a hyphen", k)) 570 } 571 if len(value) > 255 { 572 errors = append(errors, fmt.Errorf("%q cannot be more than 255 characters", k)) 573 } 574 return 575 } 576 577 func validateRedshiftClusterMasterUsername(v interface{}, k string) (ws []string, errors []error) { 578 value := v.(string) 579 if !regexp.MustCompile(`^[A-Za-z0-9]+$`).MatchString(value) { 580 errors = append(errors, fmt.Errorf( 581 "only alphanumeric characters in %q", k)) 582 } 583 if !regexp.MustCompile(`^[A-Za-z]`).MatchString(value) { 584 errors = append(errors, fmt.Errorf( 585 "first character of %q must be a letter", k)) 586 } 587 if len(value) > 128 { 588 errors = append(errors, fmt.Errorf("%q cannot be more than 128 characters", k)) 589 } 590 return 591 }