github.com/richardbowden/terraform@v0.6.12-0.20160901200758-30ea22c25211/builtin/providers/aws/structure.go (about) 1 package aws 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "reflect" 8 "sort" 9 "strconv" 10 "strings" 11 12 "github.com/aws/aws-sdk-go/aws" 13 "github.com/aws/aws-sdk-go/service/apigateway" 14 "github.com/aws/aws-sdk-go/service/autoscaling" 15 "github.com/aws/aws-sdk-go/service/cloudformation" 16 "github.com/aws/aws-sdk-go/service/cloudwatchlogs" 17 "github.com/aws/aws-sdk-go/service/directoryservice" 18 "github.com/aws/aws-sdk-go/service/ec2" 19 "github.com/aws/aws-sdk-go/service/ecs" 20 "github.com/aws/aws-sdk-go/service/elasticache" 21 "github.com/aws/aws-sdk-go/service/elasticbeanstalk" 22 elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" 23 "github.com/aws/aws-sdk-go/service/elb" 24 "github.com/aws/aws-sdk-go/service/kinesis" 25 "github.com/aws/aws-sdk-go/service/lambda" 26 "github.com/aws/aws-sdk-go/service/rds" 27 "github.com/aws/aws-sdk-go/service/redshift" 28 "github.com/aws/aws-sdk-go/service/route53" 29 "github.com/hashicorp/terraform/helper/schema" 30 ) 31 32 // Takes the result of flatmap.Expand for an array of listeners and 33 // returns ELB API compatible objects 34 func expandListeners(configured []interface{}) ([]*elb.Listener, error) { 35 listeners := make([]*elb.Listener, 0, len(configured)) 36 37 // Loop over our configured listeners and create 38 // an array of aws-sdk-go compatabile objects 39 for _, lRaw := range configured { 40 data := lRaw.(map[string]interface{}) 41 42 ip := int64(data["instance_port"].(int)) 43 lp := int64(data["lb_port"].(int)) 44 l := &elb.Listener{ 45 InstancePort: &ip, 46 InstanceProtocol: aws.String(data["instance_protocol"].(string)), 47 LoadBalancerPort: &lp, 48 Protocol: aws.String(data["lb_protocol"].(string)), 49 } 50 51 if v, ok := data["ssl_certificate_id"]; ok { 52 l.SSLCertificateId = aws.String(v.(string)) 53 } 54 55 var valid bool 56 if l.SSLCertificateId != nil && *l.SSLCertificateId != "" { 57 // validate the protocol is correct 58 for _, p := range []string{"https", "ssl"} { 59 if (strings.ToLower(*l.InstanceProtocol) == p) || (strings.ToLower(*l.Protocol) == p) { 60 valid = true 61 } 62 } 63 } else { 64 valid = true 65 } 66 67 if valid { 68 listeners = append(listeners, l) 69 } else { 70 return nil, fmt.Errorf("[ERR] ELB Listener: ssl_certificate_id may be set only when protocol is 'https' or 'ssl'") 71 } 72 } 73 74 return listeners, nil 75 } 76 77 // Takes the result of flatmap. Expand for an array of listeners and 78 // returns ECS Volume compatible objects 79 func expandEcsVolumes(configured []interface{}) ([]*ecs.Volume, error) { 80 volumes := make([]*ecs.Volume, 0, len(configured)) 81 82 // Loop over our configured volumes and create 83 // an array of aws-sdk-go compatible objects 84 for _, lRaw := range configured { 85 data := lRaw.(map[string]interface{}) 86 87 l := &ecs.Volume{ 88 Name: aws.String(data["name"].(string)), 89 } 90 91 hostPath := data["host_path"].(string) 92 if hostPath != "" { 93 l.Host = &ecs.HostVolumeProperties{ 94 SourcePath: aws.String(hostPath), 95 } 96 } 97 98 volumes = append(volumes, l) 99 } 100 101 return volumes, nil 102 } 103 104 // Takes JSON in a string. Decodes JSON into 105 // an array of ecs.ContainerDefinition compatible objects 106 func expandEcsContainerDefinitions(rawDefinitions string) ([]*ecs.ContainerDefinition, error) { 107 var definitions []*ecs.ContainerDefinition 108 109 err := json.Unmarshal([]byte(rawDefinitions), &definitions) 110 if err != nil { 111 return nil, fmt.Errorf("Error decoding JSON: %s", err) 112 } 113 114 return definitions, nil 115 } 116 117 // Takes the result of flatmap. Expand for an array of load balancers and 118 // returns ecs.LoadBalancer compatible objects 119 func expandEcsLoadBalancers(configured []interface{}) []*ecs.LoadBalancer { 120 loadBalancers := make([]*ecs.LoadBalancer, 0, len(configured)) 121 122 // Loop over our configured load balancers and create 123 // an array of aws-sdk-go compatible objects 124 for _, lRaw := range configured { 125 data := lRaw.(map[string]interface{}) 126 127 l := &ecs.LoadBalancer{ 128 ContainerName: aws.String(data["container_name"].(string)), 129 ContainerPort: aws.Int64(int64(data["container_port"].(int))), 130 } 131 132 if v, ok := data["elb_name"]; ok && v.(string) != "" { 133 l.LoadBalancerName = aws.String(v.(string)) 134 } 135 if v, ok := data["target_group_arn"]; ok && v.(string) != "" { 136 l.TargetGroupArn = aws.String(v.(string)) 137 } 138 139 loadBalancers = append(loadBalancers, l) 140 } 141 142 return loadBalancers 143 } 144 145 // Takes the result of flatmap.Expand for an array of ingress/egress security 146 // group rules and returns EC2 API compatible objects. This function will error 147 // if it finds invalid permissions input, namely a protocol of "-1" with either 148 // to_port or from_port set to a non-zero value. 149 func expandIPPerms( 150 group *ec2.SecurityGroup, configured []interface{}) ([]*ec2.IpPermission, error) { 151 vpc := group.VpcId != nil && *group.VpcId != "" 152 153 perms := make([]*ec2.IpPermission, len(configured)) 154 for i, mRaw := range configured { 155 var perm ec2.IpPermission 156 m := mRaw.(map[string]interface{}) 157 158 perm.FromPort = aws.Int64(int64(m["from_port"].(int))) 159 perm.ToPort = aws.Int64(int64(m["to_port"].(int))) 160 perm.IpProtocol = aws.String(m["protocol"].(string)) 161 162 // When protocol is "-1", AWS won't store any ports for the 163 // rule, but also won't error if the user specifies ports other 164 // than '0'. Force the user to make a deliberate '0' port 165 // choice when specifying a "-1" protocol, and tell them about 166 // AWS's behavior in the error message. 167 if *perm.IpProtocol == "-1" && (*perm.FromPort != 0 || *perm.ToPort != 0) { 168 return nil, fmt.Errorf( 169 "from_port (%d) and to_port (%d) must both be 0 to use the the 'ALL' \"-1\" protocol!", 170 *perm.FromPort, *perm.ToPort) 171 } 172 173 var groups []string 174 if raw, ok := m["security_groups"]; ok { 175 list := raw.(*schema.Set).List() 176 for _, v := range list { 177 groups = append(groups, v.(string)) 178 } 179 } 180 if v, ok := m["self"]; ok && v.(bool) { 181 if vpc { 182 groups = append(groups, *group.GroupId) 183 } else { 184 groups = append(groups, *group.GroupName) 185 } 186 } 187 188 if len(groups) > 0 { 189 perm.UserIdGroupPairs = make([]*ec2.UserIdGroupPair, len(groups)) 190 for i, name := range groups { 191 ownerId, id := "", name 192 if items := strings.Split(id, "/"); len(items) > 1 { 193 ownerId, id = items[0], items[1] 194 } 195 196 perm.UserIdGroupPairs[i] = &ec2.UserIdGroupPair{ 197 GroupId: aws.String(id), 198 } 199 200 if ownerId != "" { 201 perm.UserIdGroupPairs[i].UserId = aws.String(ownerId) 202 } 203 204 if !vpc { 205 perm.UserIdGroupPairs[i].GroupId = nil 206 perm.UserIdGroupPairs[i].GroupName = aws.String(id) 207 } 208 } 209 } 210 211 if raw, ok := m["cidr_blocks"]; ok { 212 list := raw.([]interface{}) 213 for _, v := range list { 214 perm.IpRanges = append(perm.IpRanges, &ec2.IpRange{CidrIp: aws.String(v.(string))}) 215 } 216 } 217 218 if raw, ok := m["prefix_list_ids"]; ok { 219 list := raw.([]interface{}) 220 for _, v := range list { 221 perm.PrefixListIds = append(perm.PrefixListIds, &ec2.PrefixListId{PrefixListId: aws.String(v.(string))}) 222 } 223 } 224 225 perms[i] = &perm 226 } 227 228 return perms, nil 229 } 230 231 // Takes the result of flatmap.Expand for an array of parameters and 232 // returns Parameter API compatible objects 233 func expandParameters(configured []interface{}) ([]*rds.Parameter, error) { 234 var parameters []*rds.Parameter 235 236 // Loop over our configured parameters and create 237 // an array of aws-sdk-go compatabile objects 238 for _, pRaw := range configured { 239 data := pRaw.(map[string]interface{}) 240 241 if data["name"].(string) == "" { 242 continue 243 } 244 245 p := &rds.Parameter{ 246 ApplyMethod: aws.String(data["apply_method"].(string)), 247 ParameterName: aws.String(data["name"].(string)), 248 ParameterValue: aws.String(data["value"].(string)), 249 } 250 251 parameters = append(parameters, p) 252 } 253 254 return parameters, nil 255 } 256 257 func expandRedshiftParameters(configured []interface{}) ([]*redshift.Parameter, error) { 258 var parameters []*redshift.Parameter 259 260 // Loop over our configured parameters and create 261 // an array of aws-sdk-go compatabile objects 262 for _, pRaw := range configured { 263 data := pRaw.(map[string]interface{}) 264 265 if data["name"].(string) == "" { 266 continue 267 } 268 269 p := &redshift.Parameter{ 270 ParameterName: aws.String(data["name"].(string)), 271 ParameterValue: aws.String(data["value"].(string)), 272 } 273 274 parameters = append(parameters, p) 275 } 276 277 return parameters, nil 278 } 279 280 func expandOptionConfiguration(configured []interface{}) ([]*rds.OptionConfiguration, error) { 281 var option []*rds.OptionConfiguration 282 283 for _, pRaw := range configured { 284 data := pRaw.(map[string]interface{}) 285 286 o := &rds.OptionConfiguration{ 287 OptionName: aws.String(data["option_name"].(string)), 288 } 289 290 if raw, ok := data["port"]; ok { 291 port := raw.(int) 292 if port != 0 { 293 o.Port = aws.Int64(int64(port)) 294 } 295 } 296 297 if raw, ok := data["db_security_group_memberships"]; ok { 298 memberships := expandStringList(raw.(*schema.Set).List()) 299 if len(memberships) > 0 { 300 o.DBSecurityGroupMemberships = memberships 301 } 302 } 303 304 if raw, ok := data["vpc_security_group_memberships"]; ok { 305 memberships := expandStringList(raw.(*schema.Set).List()) 306 if len(memberships) > 0 { 307 o.VpcSecurityGroupMemberships = memberships 308 } 309 } 310 311 if raw, ok := data["option_settings"]; ok { 312 o.OptionSettings = expandOptionSetting(raw.(*schema.Set).List()) 313 } 314 315 option = append(option, o) 316 } 317 318 return option, nil 319 } 320 321 func expandOptionSetting(list []interface{}) []*rds.OptionSetting { 322 options := make([]*rds.OptionSetting, 0, len(list)) 323 324 for _, oRaw := range list { 325 data := oRaw.(map[string]interface{}) 326 327 o := &rds.OptionSetting{ 328 Name: aws.String(data["name"].(string)), 329 Value: aws.String(data["value"].(string)), 330 } 331 332 options = append(options, o) 333 } 334 335 return options 336 } 337 338 // Takes the result of flatmap.Expand for an array of parameters and 339 // returns Parameter API compatible objects 340 func expandElastiCacheParameters(configured []interface{}) ([]*elasticache.ParameterNameValue, error) { 341 parameters := make([]*elasticache.ParameterNameValue, 0, len(configured)) 342 343 // Loop over our configured parameters and create 344 // an array of aws-sdk-go compatabile objects 345 for _, pRaw := range configured { 346 data := pRaw.(map[string]interface{}) 347 348 p := &elasticache.ParameterNameValue{ 349 ParameterName: aws.String(data["name"].(string)), 350 ParameterValue: aws.String(data["value"].(string)), 351 } 352 353 parameters = append(parameters, p) 354 } 355 356 return parameters, nil 357 } 358 359 // Flattens an access log into something that flatmap.Flatten() can handle 360 func flattenAccessLog(l *elb.AccessLog) []map[string]interface{} { 361 result := make([]map[string]interface{}, 0, 1) 362 363 if l != nil && *l.Enabled { 364 r := make(map[string]interface{}) 365 if l.S3BucketName != nil { 366 r["bucket"] = *l.S3BucketName 367 } 368 369 if l.S3BucketPrefix != nil { 370 r["bucket_prefix"] = *l.S3BucketPrefix 371 } 372 373 if l.EmitInterval != nil { 374 r["interval"] = *l.EmitInterval 375 } 376 377 if l.Enabled != nil { 378 r["enabled"] = *l.Enabled 379 } 380 381 result = append(result, r) 382 } 383 384 return result 385 } 386 387 // Takes the result of flatmap.Expand for an array of step adjustments and 388 // returns a []*autoscaling.StepAdjustment. 389 func expandStepAdjustments(configured []interface{}) ([]*autoscaling.StepAdjustment, error) { 390 var adjustments []*autoscaling.StepAdjustment 391 392 // Loop over our configured step adjustments and create an array 393 // of aws-sdk-go compatible objects. We're forced to convert strings 394 // to floats here because there's no way to detect whether or not 395 // an uninitialized, optional schema element is "0.0" deliberately. 396 // With strings, we can test for "", which is definitely an empty 397 // struct value. 398 for _, raw := range configured { 399 data := raw.(map[string]interface{}) 400 a := &autoscaling.StepAdjustment{ 401 ScalingAdjustment: aws.Int64(int64(data["scaling_adjustment"].(int))), 402 } 403 if data["metric_interval_lower_bound"] != "" { 404 bound := data["metric_interval_lower_bound"] 405 switch bound := bound.(type) { 406 case string: 407 f, err := strconv.ParseFloat(bound, 64) 408 if err != nil { 409 return nil, fmt.Errorf( 410 "metric_interval_lower_bound must be a float value represented as a string") 411 } 412 a.MetricIntervalLowerBound = aws.Float64(f) 413 default: 414 return nil, fmt.Errorf( 415 "metric_interval_lower_bound isn't a string. This is a bug. Please file an issue.") 416 } 417 } 418 if data["metric_interval_upper_bound"] != "" { 419 bound := data["metric_interval_upper_bound"] 420 switch bound := bound.(type) { 421 case string: 422 f, err := strconv.ParseFloat(bound, 64) 423 if err != nil { 424 return nil, fmt.Errorf( 425 "metric_interval_upper_bound must be a float value represented as a string") 426 } 427 a.MetricIntervalUpperBound = aws.Float64(f) 428 default: 429 return nil, fmt.Errorf( 430 "metric_interval_upper_bound isn't a string. This is a bug. Please file an issue.") 431 } 432 } 433 adjustments = append(adjustments, a) 434 } 435 436 return adjustments, nil 437 } 438 439 // Flattens a health check into something that flatmap.Flatten() 440 // can handle 441 func flattenHealthCheck(check *elb.HealthCheck) []map[string]interface{} { 442 result := make([]map[string]interface{}, 0, 1) 443 444 chk := make(map[string]interface{}) 445 chk["unhealthy_threshold"] = *check.UnhealthyThreshold 446 chk["healthy_threshold"] = *check.HealthyThreshold 447 chk["target"] = *check.Target 448 chk["timeout"] = *check.Timeout 449 chk["interval"] = *check.Interval 450 451 result = append(result, chk) 452 453 return result 454 } 455 456 // Flattens an array of UserSecurityGroups into a []*ec2.GroupIdentifier 457 func flattenSecurityGroups(list []*ec2.UserIdGroupPair, ownerId *string) []*ec2.GroupIdentifier { 458 result := make([]*ec2.GroupIdentifier, 0, len(list)) 459 for _, g := range list { 460 var userId *string 461 if g.UserId != nil && *g.UserId != "" && (ownerId == nil || *ownerId != *g.UserId) { 462 userId = g.UserId 463 } 464 // userid nil here for same vpc groups 465 466 vpc := g.GroupName == nil || *g.GroupName == "" 467 var id *string 468 if vpc { 469 id = g.GroupId 470 } else { 471 id = g.GroupName 472 } 473 474 // id is groupid for vpcs 475 // id is groupname for non vpc (classic) 476 477 if userId != nil { 478 id = aws.String(*userId + "/" + *id) 479 } 480 481 if vpc { 482 result = append(result, &ec2.GroupIdentifier{ 483 GroupId: id, 484 }) 485 } else { 486 result = append(result, &ec2.GroupIdentifier{ 487 GroupId: g.GroupId, 488 GroupName: id, 489 }) 490 } 491 } 492 return result 493 } 494 495 // Flattens an array of Instances into a []string 496 func flattenInstances(list []*elb.Instance) []string { 497 result := make([]string, 0, len(list)) 498 for _, i := range list { 499 result = append(result, *i.InstanceId) 500 } 501 return result 502 } 503 504 // Expands an array of String Instance IDs into a []Instances 505 func expandInstanceString(list []interface{}) []*elb.Instance { 506 result := make([]*elb.Instance, 0, len(list)) 507 for _, i := range list { 508 result = append(result, &elb.Instance{InstanceId: aws.String(i.(string))}) 509 } 510 return result 511 } 512 513 // Flattens an array of Backend Descriptions into a a map of instance_port to policy names. 514 func flattenBackendPolicies(backends []*elb.BackendServerDescription) map[int64][]string { 515 policies := make(map[int64][]string) 516 for _, i := range backends { 517 for _, p := range i.PolicyNames { 518 policies[*i.InstancePort] = append(policies[*i.InstancePort], *p) 519 } 520 sort.Strings(policies[*i.InstancePort]) 521 } 522 return policies 523 } 524 525 // Flattens an array of Listeners into a []map[string]interface{} 526 func flattenListeners(list []*elb.ListenerDescription) []map[string]interface{} { 527 result := make([]map[string]interface{}, 0, len(list)) 528 for _, i := range list { 529 l := map[string]interface{}{ 530 "instance_port": *i.Listener.InstancePort, 531 "instance_protocol": strings.ToLower(*i.Listener.InstanceProtocol), 532 "lb_port": *i.Listener.LoadBalancerPort, 533 "lb_protocol": strings.ToLower(*i.Listener.Protocol), 534 } 535 // SSLCertificateID is optional, and may be nil 536 if i.Listener.SSLCertificateId != nil { 537 l["ssl_certificate_id"] = *i.Listener.SSLCertificateId 538 } 539 result = append(result, l) 540 } 541 return result 542 } 543 544 // Flattens an array of Volumes into a []map[string]interface{} 545 func flattenEcsVolumes(list []*ecs.Volume) []map[string]interface{} { 546 result := make([]map[string]interface{}, 0, len(list)) 547 for _, volume := range list { 548 l := map[string]interface{}{ 549 "name": *volume.Name, 550 } 551 552 if volume.Host.SourcePath != nil { 553 l["host_path"] = *volume.Host.SourcePath 554 } 555 556 result = append(result, l) 557 } 558 return result 559 } 560 561 // Flattens an array of ECS LoadBalancers into a []map[string]interface{} 562 func flattenEcsLoadBalancers(list []*ecs.LoadBalancer) []map[string]interface{} { 563 result := make([]map[string]interface{}, 0, len(list)) 564 for _, loadBalancer := range list { 565 l := map[string]interface{}{ 566 "container_name": *loadBalancer.ContainerName, 567 "container_port": *loadBalancer.ContainerPort, 568 } 569 570 if loadBalancer.LoadBalancerName != nil { 571 l["elb_name"] = *loadBalancer.LoadBalancerName 572 } 573 574 if loadBalancer.TargetGroupArn != nil { 575 l["target_group_arn"] = *loadBalancer.TargetGroupArn 576 } 577 578 result = append(result, l) 579 } 580 return result 581 } 582 583 // Encodes an array of ecs.ContainerDefinitions into a JSON string 584 func flattenEcsContainerDefinitions(definitions []*ecs.ContainerDefinition) (string, error) { 585 byteArray, err := json.Marshal(definitions) 586 if err != nil { 587 return "", fmt.Errorf("Error encoding to JSON: %s", err) 588 } 589 590 n := bytes.Index(byteArray, []byte{0}) 591 return string(byteArray[:n]), nil 592 } 593 594 // Flattens an array of Options into a []map[string]interface{} 595 func flattenOptions(list []*rds.Option) []map[string]interface{} { 596 result := make([]map[string]interface{}, 0, len(list)) 597 for _, i := range list { 598 if i.OptionName != nil { 599 r := make(map[string]interface{}) 600 r["option_name"] = strings.ToLower(*i.OptionName) 601 // Default empty string, guard against nil parameter values 602 r["port"] = "" 603 if i.Port != nil { 604 r["port"] = int(*i.Port) 605 } 606 if i.VpcSecurityGroupMemberships != nil { 607 vpcs := make([]string, 0, len(i.VpcSecurityGroupMemberships)) 608 for _, vpc := range i.VpcSecurityGroupMemberships { 609 id := vpc.VpcSecurityGroupId 610 vpcs = append(vpcs, *id) 611 } 612 613 r["vpc_security_group_memberships"] = vpcs 614 } 615 if i.DBSecurityGroupMemberships != nil { 616 dbs := make([]string, 0, len(i.DBSecurityGroupMemberships)) 617 for _, db := range i.DBSecurityGroupMemberships { 618 id := db.DBSecurityGroupName 619 dbs = append(dbs, *id) 620 } 621 622 r["db_security_group_memberships"] = dbs 623 } 624 if i.OptionSettings != nil { 625 settings := make([]map[string]interface{}, 0, len(i.OptionSettings)) 626 for _, j := range i.OptionSettings { 627 settings = append(settings, map[string]interface{}{ 628 "name": *j.Name, 629 "value": *j.Value, 630 }) 631 } 632 633 r["option_settings"] = settings 634 } 635 result = append(result, r) 636 } 637 } 638 return result 639 } 640 641 // Flattens an array of Parameters into a []map[string]interface{} 642 func flattenParameters(list []*rds.Parameter) []map[string]interface{} { 643 result := make([]map[string]interface{}, 0, len(list)) 644 for _, i := range list { 645 if i.ParameterName != nil { 646 r := make(map[string]interface{}) 647 r["name"] = strings.ToLower(*i.ParameterName) 648 // Default empty string, guard against nil parameter values 649 r["value"] = "" 650 if i.ParameterValue != nil { 651 r["value"] = strings.ToLower(*i.ParameterValue) 652 } 653 result = append(result, r) 654 } 655 } 656 return result 657 } 658 659 // Flattens an array of Redshift Parameters into a []map[string]interface{} 660 func flattenRedshiftParameters(list []*redshift.Parameter) []map[string]interface{} { 661 result := make([]map[string]interface{}, 0, len(list)) 662 for _, i := range list { 663 result = append(result, map[string]interface{}{ 664 "name": strings.ToLower(*i.ParameterName), 665 "value": strings.ToLower(*i.ParameterValue), 666 }) 667 } 668 return result 669 } 670 671 // Flattens an array of Parameters into a []map[string]interface{} 672 func flattenElastiCacheParameters(list []*elasticache.Parameter) []map[string]interface{} { 673 result := make([]map[string]interface{}, 0, len(list)) 674 for _, i := range list { 675 if i.ParameterValue != nil { 676 result = append(result, map[string]interface{}{ 677 "name": strings.ToLower(*i.ParameterName), 678 "value": strings.ToLower(*i.ParameterValue), 679 }) 680 } 681 } 682 return result 683 } 684 685 // Takes the result of flatmap.Expand for an array of strings 686 // and returns a []*string 687 func expandStringList(configured []interface{}) []*string { 688 vs := make([]*string, 0, len(configured)) 689 for _, v := range configured { 690 vs = append(vs, aws.String(v.(string))) 691 } 692 return vs 693 } 694 695 // Takes the result of schema.Set of strings and returns a []*string 696 func expandStringSet(configured *schema.Set) []*string { 697 return expandStringList(configured.List()) 698 } 699 700 // Takes list of pointers to strings. Expand to an array 701 // of raw strings and returns a []interface{} 702 // to keep compatibility w/ schema.NewSetschema.NewSet 703 func flattenStringList(list []*string) []interface{} { 704 vs := make([]interface{}, 0, len(list)) 705 for _, v := range list { 706 vs = append(vs, *v) 707 } 708 return vs 709 } 710 711 //Flattens an array of private ip addresses into a []string, where the elements returned are the IP strings e.g. "192.168.0.0" 712 func flattenNetworkInterfacesPrivateIPAddresses(dtos []*ec2.NetworkInterfacePrivateIpAddress) []string { 713 ips := make([]string, 0, len(dtos)) 714 for _, v := range dtos { 715 ip := *v.PrivateIpAddress 716 ips = append(ips, ip) 717 } 718 return ips 719 } 720 721 //Flattens security group identifiers into a []string, where the elements returned are the GroupIDs 722 func flattenGroupIdentifiers(dtos []*ec2.GroupIdentifier) []string { 723 ids := make([]string, 0, len(dtos)) 724 for _, v := range dtos { 725 group_id := *v.GroupId 726 ids = append(ids, group_id) 727 } 728 return ids 729 } 730 731 //Expands an array of IPs into a ec2 Private IP Address Spec 732 func expandPrivateIPAddresses(ips []interface{}) []*ec2.PrivateIpAddressSpecification { 733 dtos := make([]*ec2.PrivateIpAddressSpecification, 0, len(ips)) 734 for i, v := range ips { 735 new_private_ip := &ec2.PrivateIpAddressSpecification{ 736 PrivateIpAddress: aws.String(v.(string)), 737 } 738 739 new_private_ip.Primary = aws.Bool(i == 0) 740 741 dtos = append(dtos, new_private_ip) 742 } 743 return dtos 744 } 745 746 //Flattens network interface attachment into a map[string]interface 747 func flattenAttachment(a *ec2.NetworkInterfaceAttachment) map[string]interface{} { 748 att := make(map[string]interface{}) 749 if a.InstanceId != nil { 750 att["instance"] = *a.InstanceId 751 } 752 att["device_index"] = *a.DeviceIndex 753 att["attachment_id"] = *a.AttachmentId 754 return att 755 } 756 757 // Flattens step adjustments into a list of map[string]interface. 758 func flattenStepAdjustments(adjustments []*autoscaling.StepAdjustment) []map[string]interface{} { 759 result := make([]map[string]interface{}, 0, len(adjustments)) 760 for _, raw := range adjustments { 761 a := map[string]interface{}{ 762 "scaling_adjustment": *raw.ScalingAdjustment, 763 } 764 if raw.MetricIntervalUpperBound != nil { 765 a["metric_interval_upper_bound"] = *raw.MetricIntervalUpperBound 766 } 767 if raw.MetricIntervalLowerBound != nil { 768 a["metric_interval_lower_bound"] = *raw.MetricIntervalLowerBound 769 } 770 result = append(result, a) 771 } 772 return result 773 } 774 775 func flattenResourceRecords(recs []*route53.ResourceRecord) []string { 776 strs := make([]string, 0, len(recs)) 777 for _, r := range recs { 778 if r.Value != nil { 779 s := strings.Replace(*r.Value, "\"", "", 2) 780 strs = append(strs, s) 781 } 782 } 783 return strs 784 } 785 786 func expandResourceRecords(recs []interface{}, typeStr string) []*route53.ResourceRecord { 787 records := make([]*route53.ResourceRecord, 0, len(recs)) 788 for _, r := range recs { 789 s := r.(string) 790 switch typeStr { 791 case "TXT", "SPF": 792 str := fmt.Sprintf("\"%s\"", s) 793 records = append(records, &route53.ResourceRecord{Value: aws.String(str)}) 794 default: 795 records = append(records, &route53.ResourceRecord{Value: aws.String(s)}) 796 } 797 } 798 return records 799 } 800 801 func expandESClusterConfig(m map[string]interface{}) *elasticsearch.ElasticsearchClusterConfig { 802 config := elasticsearch.ElasticsearchClusterConfig{} 803 804 if v, ok := m["dedicated_master_enabled"]; ok { 805 isEnabled := v.(bool) 806 config.DedicatedMasterEnabled = aws.Bool(isEnabled) 807 808 if isEnabled { 809 if v, ok := m["dedicated_master_count"]; ok && v.(int) > 0 { 810 config.DedicatedMasterCount = aws.Int64(int64(v.(int))) 811 } 812 if v, ok := m["dedicated_master_type"]; ok && v.(string) != "" { 813 config.DedicatedMasterType = aws.String(v.(string)) 814 } 815 } 816 } 817 818 if v, ok := m["instance_count"]; ok { 819 config.InstanceCount = aws.Int64(int64(v.(int))) 820 } 821 if v, ok := m["instance_type"]; ok { 822 config.InstanceType = aws.String(v.(string)) 823 } 824 825 if v, ok := m["zone_awareness_enabled"]; ok { 826 config.ZoneAwarenessEnabled = aws.Bool(v.(bool)) 827 } 828 829 return &config 830 } 831 832 func flattenESClusterConfig(c *elasticsearch.ElasticsearchClusterConfig) []map[string]interface{} { 833 m := map[string]interface{}{} 834 835 if c.DedicatedMasterCount != nil { 836 m["dedicated_master_count"] = *c.DedicatedMasterCount 837 } 838 if c.DedicatedMasterEnabled != nil { 839 m["dedicated_master_enabled"] = *c.DedicatedMasterEnabled 840 } 841 if c.DedicatedMasterType != nil { 842 m["dedicated_master_type"] = *c.DedicatedMasterType 843 } 844 if c.InstanceCount != nil { 845 m["instance_count"] = *c.InstanceCount 846 } 847 if c.InstanceType != nil { 848 m["instance_type"] = *c.InstanceType 849 } 850 if c.ZoneAwarenessEnabled != nil { 851 m["zone_awareness_enabled"] = *c.ZoneAwarenessEnabled 852 } 853 854 return []map[string]interface{}{m} 855 } 856 857 func flattenESEBSOptions(o *elasticsearch.EBSOptions) []map[string]interface{} { 858 m := map[string]interface{}{} 859 860 if o.EBSEnabled != nil { 861 m["ebs_enabled"] = *o.EBSEnabled 862 } 863 if o.Iops != nil { 864 m["iops"] = *o.Iops 865 } 866 if o.VolumeSize != nil { 867 m["volume_size"] = *o.VolumeSize 868 } 869 if o.VolumeType != nil { 870 m["volume_type"] = *o.VolumeType 871 } 872 873 return []map[string]interface{}{m} 874 } 875 876 func expandESEBSOptions(m map[string]interface{}) *elasticsearch.EBSOptions { 877 options := elasticsearch.EBSOptions{} 878 879 if v, ok := m["ebs_enabled"]; ok { 880 options.EBSEnabled = aws.Bool(v.(bool)) 881 } 882 if v, ok := m["iops"]; ok && v.(int) > 0 { 883 options.Iops = aws.Int64(int64(v.(int))) 884 } 885 if v, ok := m["volume_size"]; ok && v.(int) > 0 { 886 options.VolumeSize = aws.Int64(int64(v.(int))) 887 } 888 if v, ok := m["volume_type"]; ok && v.(string) != "" { 889 options.VolumeType = aws.String(v.(string)) 890 } 891 892 return &options 893 } 894 895 func pointersMapToStringList(pointers map[string]*string) map[string]interface{} { 896 list := make(map[string]interface{}, len(pointers)) 897 for i, v := range pointers { 898 list[i] = *v 899 } 900 return list 901 } 902 903 func stringMapToPointers(m map[string]interface{}) map[string]*string { 904 list := make(map[string]*string, len(m)) 905 for i, v := range m { 906 list[i] = aws.String(v.(string)) 907 } 908 return list 909 } 910 911 func flattenDSVpcSettings( 912 s *directoryservice.DirectoryVpcSettingsDescription) []map[string]interface{} { 913 settings := make(map[string]interface{}, 0) 914 915 if s == nil { 916 return nil 917 } 918 919 settings["subnet_ids"] = schema.NewSet(schema.HashString, flattenStringList(s.SubnetIds)) 920 settings["vpc_id"] = *s.VpcId 921 922 return []map[string]interface{}{settings} 923 } 924 925 func flattenLambdaVpcConfigResponse(s *lambda.VpcConfigResponse) []map[string]interface{} { 926 settings := make(map[string]interface{}, 0) 927 928 if s == nil { 929 return nil 930 } 931 932 if len(s.SubnetIds) == 0 && len(s.SecurityGroupIds) == 0 && s.VpcId == nil { 933 return nil 934 } 935 936 settings["subnet_ids"] = schema.NewSet(schema.HashString, flattenStringList(s.SubnetIds)) 937 settings["security_group_ids"] = schema.NewSet(schema.HashString, flattenStringList(s.SecurityGroupIds)) 938 if s.VpcId != nil { 939 settings["vpc_id"] = *s.VpcId 940 } 941 942 return []map[string]interface{}{settings} 943 } 944 945 func flattenDSConnectSettings( 946 customerDnsIps []*string, 947 s *directoryservice.DirectoryConnectSettingsDescription) []map[string]interface{} { 948 if s == nil { 949 return nil 950 } 951 952 settings := make(map[string]interface{}, 0) 953 954 settings["customer_dns_ips"] = schema.NewSet(schema.HashString, flattenStringList(customerDnsIps)) 955 settings["connect_ips"] = schema.NewSet(schema.HashString, flattenStringList(s.ConnectIps)) 956 settings["customer_username"] = *s.CustomerUserName 957 settings["subnet_ids"] = schema.NewSet(schema.HashString, flattenStringList(s.SubnetIds)) 958 settings["vpc_id"] = *s.VpcId 959 960 return []map[string]interface{}{settings} 961 } 962 963 func expandCloudFormationParameters(params map[string]interface{}) []*cloudformation.Parameter { 964 var cfParams []*cloudformation.Parameter 965 for k, v := range params { 966 cfParams = append(cfParams, &cloudformation.Parameter{ 967 ParameterKey: aws.String(k), 968 ParameterValue: aws.String(v.(string)), 969 }) 970 } 971 972 return cfParams 973 } 974 975 // flattenCloudFormationParameters is flattening list of 976 // *cloudformation.Parameters and only returning existing 977 // parameters to avoid clash with default values 978 func flattenCloudFormationParameters(cfParams []*cloudformation.Parameter, 979 originalParams map[string]interface{}) map[string]interface{} { 980 params := make(map[string]interface{}, len(cfParams)) 981 for _, p := range cfParams { 982 _, isConfigured := originalParams[*p.ParameterKey] 983 if isConfigured { 984 params[*p.ParameterKey] = *p.ParameterValue 985 } 986 } 987 return params 988 } 989 990 func expandCloudFormationTags(tags map[string]interface{}) []*cloudformation.Tag { 991 var cfTags []*cloudformation.Tag 992 for k, v := range tags { 993 cfTags = append(cfTags, &cloudformation.Tag{ 994 Key: aws.String(k), 995 Value: aws.String(v.(string)), 996 }) 997 } 998 return cfTags 999 } 1000 1001 func flattenCloudFormationTags(cfTags []*cloudformation.Tag) map[string]string { 1002 tags := make(map[string]string, len(cfTags)) 1003 for _, t := range cfTags { 1004 tags[*t.Key] = *t.Value 1005 } 1006 return tags 1007 } 1008 1009 func flattenCloudFormationOutputs(cfOutputs []*cloudformation.Output) map[string]string { 1010 outputs := make(map[string]string, len(cfOutputs)) 1011 for _, o := range cfOutputs { 1012 outputs[*o.OutputKey] = *o.OutputValue 1013 } 1014 return outputs 1015 } 1016 1017 func flattenAsgEnabledMetrics(list []*autoscaling.EnabledMetric) []string { 1018 strs := make([]string, 0, len(list)) 1019 for _, r := range list { 1020 if r.Metric != nil { 1021 strs = append(strs, *r.Metric) 1022 } 1023 } 1024 return strs 1025 } 1026 1027 func flattenKinesisShardLevelMetrics(list []*kinesis.EnhancedMetrics) []string { 1028 if len(list) == 0 { 1029 return []string{} 1030 } 1031 strs := make([]string, 0, len(list[0].ShardLevelMetrics)) 1032 for _, s := range list[0].ShardLevelMetrics { 1033 strs = append(strs, *s) 1034 } 1035 return strs 1036 } 1037 1038 func flattenApiGatewayStageKeys(keys []*string) []map[string]interface{} { 1039 stageKeys := make([]map[string]interface{}, 0, len(keys)) 1040 for _, o := range keys { 1041 key := make(map[string]interface{}) 1042 parts := strings.Split(*o, "/") 1043 key["stage_name"] = parts[1] 1044 key["rest_api_id"] = parts[0] 1045 1046 stageKeys = append(stageKeys, key) 1047 } 1048 return stageKeys 1049 } 1050 1051 func expandApiGatewayStageKeys(d *schema.ResourceData) []*apigateway.StageKey { 1052 var stageKeys []*apigateway.StageKey 1053 1054 if stageKeyData, ok := d.GetOk("stage_key"); ok { 1055 params := stageKeyData.(*schema.Set).List() 1056 for k := range params { 1057 data := params[k].(map[string]interface{}) 1058 stageKeys = append(stageKeys, &apigateway.StageKey{ 1059 RestApiId: aws.String(data["rest_api_id"].(string)), 1060 StageName: aws.String(data["stage_name"].(string)), 1061 }) 1062 } 1063 } 1064 1065 return stageKeys 1066 } 1067 1068 func expandApiGatewayRequestResponseModelOperations(d *schema.ResourceData, key string, prefix string) []*apigateway.PatchOperation { 1069 operations := make([]*apigateway.PatchOperation, 0) 1070 1071 oldModels, newModels := d.GetChange(key) 1072 oldModelMap := oldModels.(map[string]interface{}) 1073 newModelMap := newModels.(map[string]interface{}) 1074 1075 for k, _ := range oldModelMap { 1076 operation := apigateway.PatchOperation{ 1077 Op: aws.String("remove"), 1078 Path: aws.String(fmt.Sprintf("/%s/%s", prefix, strings.Replace(k, "/", "~1", -1))), 1079 } 1080 1081 for nK, nV := range newModelMap { 1082 if nK == k { 1083 operation.Op = aws.String("replace") 1084 operation.Value = aws.String(nV.(string)) 1085 } 1086 } 1087 1088 operations = append(operations, &operation) 1089 } 1090 1091 for nK, nV := range newModelMap { 1092 exists := false 1093 for k, _ := range oldModelMap { 1094 if k == nK { 1095 exists = true 1096 } 1097 } 1098 if !exists { 1099 operation := apigateway.PatchOperation{ 1100 Op: aws.String("add"), 1101 Path: aws.String(fmt.Sprintf("/%s/%s", prefix, strings.Replace(nK, "/", "~1", -1))), 1102 Value: aws.String(nV.(string)), 1103 } 1104 operations = append(operations, &operation) 1105 } 1106 } 1107 1108 return operations 1109 } 1110 1111 func deprecatedExpandApiGatewayMethodParametersJSONOperations(d *schema.ResourceData, key string, prefix string) ([]*apigateway.PatchOperation, error) { 1112 operations := make([]*apigateway.PatchOperation, 0) 1113 oldParameters, newParameters := d.GetChange(key) 1114 oldParametersMap := make(map[string]interface{}) 1115 newParametersMap := make(map[string]interface{}) 1116 1117 if err := json.Unmarshal([]byte(oldParameters.(string)), &oldParametersMap); err != nil { 1118 err := fmt.Errorf("Error unmarshaling old %s: %s", key, err) 1119 return operations, err 1120 } 1121 1122 if err := json.Unmarshal([]byte(newParameters.(string)), &newParametersMap); err != nil { 1123 err := fmt.Errorf("Error unmarshaling new %s: %s", key, err) 1124 return operations, err 1125 } 1126 1127 for k, _ := range oldParametersMap { 1128 operation := apigateway.PatchOperation{ 1129 Op: aws.String("remove"), 1130 Path: aws.String(fmt.Sprintf("/%s/%s", prefix, k)), 1131 } 1132 1133 for nK, nV := range newParametersMap { 1134 if nK == k { 1135 operation.Op = aws.String("replace") 1136 operation.Value = aws.String(strconv.FormatBool(nV.(bool))) 1137 } 1138 } 1139 1140 operations = append(operations, &operation) 1141 } 1142 1143 for nK, nV := range newParametersMap { 1144 exists := false 1145 for k, _ := range oldParametersMap { 1146 if k == nK { 1147 exists = true 1148 } 1149 } 1150 if !exists { 1151 operation := apigateway.PatchOperation{ 1152 Op: aws.String("add"), 1153 Path: aws.String(fmt.Sprintf("/%s/%s", prefix, nK)), 1154 Value: aws.String(strconv.FormatBool(nV.(bool))), 1155 } 1156 operations = append(operations, &operation) 1157 } 1158 } 1159 1160 return operations, nil 1161 } 1162 1163 func expandApiGatewayMethodParametersOperations(d *schema.ResourceData, key string, prefix string) ([]*apigateway.PatchOperation, error) { 1164 operations := make([]*apigateway.PatchOperation, 0) 1165 1166 oldParameters, newParameters := d.GetChange(key) 1167 oldParametersMap := oldParameters.(map[string]interface{}) 1168 newParametersMap := newParameters.(map[string]interface{}) 1169 1170 for k, _ := range oldParametersMap { 1171 operation := apigateway.PatchOperation{ 1172 Op: aws.String("remove"), 1173 Path: aws.String(fmt.Sprintf("/%s/%s", prefix, k)), 1174 } 1175 1176 for nK, nV := range newParametersMap { 1177 b, ok := nV.(bool) 1178 if !ok { 1179 value, _ := strconv.ParseBool(nV.(string)) 1180 b = value 1181 } 1182 if nK == k { 1183 operation.Op = aws.String("replace") 1184 operation.Value = aws.String(strconv.FormatBool(b)) 1185 } 1186 } 1187 1188 operations = append(operations, &operation) 1189 } 1190 1191 for nK, nV := range newParametersMap { 1192 exists := false 1193 for k, _ := range oldParametersMap { 1194 if k == nK { 1195 exists = true 1196 } 1197 } 1198 if !exists { 1199 b, ok := nV.(bool) 1200 if !ok { 1201 value, _ := strconv.ParseBool(nV.(string)) 1202 b = value 1203 } 1204 operation := apigateway.PatchOperation{ 1205 Op: aws.String("add"), 1206 Path: aws.String(fmt.Sprintf("/%s/%s", prefix, nK)), 1207 Value: aws.String(strconv.FormatBool(b)), 1208 } 1209 operations = append(operations, &operation) 1210 } 1211 } 1212 1213 return operations, nil 1214 } 1215 1216 func expandApiGatewayStageKeyOperations(d *schema.ResourceData) []*apigateway.PatchOperation { 1217 operations := make([]*apigateway.PatchOperation, 0) 1218 1219 prev, curr := d.GetChange("stage_key") 1220 prevList := prev.(*schema.Set).List() 1221 currList := curr.(*schema.Set).List() 1222 1223 for i := range prevList { 1224 p := prevList[i].(map[string]interface{}) 1225 exists := false 1226 1227 for j := range currList { 1228 c := currList[j].(map[string]interface{}) 1229 if c["rest_api_id"].(string) == p["rest_api_id"].(string) && c["stage_name"].(string) == p["stage_name"].(string) { 1230 exists = true 1231 } 1232 } 1233 1234 if !exists { 1235 operations = append(operations, &apigateway.PatchOperation{ 1236 Op: aws.String("remove"), 1237 Path: aws.String("/stages"), 1238 Value: aws.String(fmt.Sprintf("%s/%s", p["rest_api_id"].(string), p["stage_name"].(string))), 1239 }) 1240 } 1241 } 1242 1243 for i := range currList { 1244 c := currList[i].(map[string]interface{}) 1245 exists := false 1246 1247 for j := range prevList { 1248 p := prevList[j].(map[string]interface{}) 1249 if c["rest_api_id"].(string) == p["rest_api_id"].(string) && c["stage_name"].(string) == p["stage_name"].(string) { 1250 exists = true 1251 } 1252 } 1253 1254 if !exists { 1255 operations = append(operations, &apigateway.PatchOperation{ 1256 Op: aws.String("add"), 1257 Path: aws.String("/stages"), 1258 Value: aws.String(fmt.Sprintf("%s/%s", c["rest_api_id"].(string), c["stage_name"].(string))), 1259 }) 1260 } 1261 } 1262 1263 return operations 1264 } 1265 1266 func expandCloudWachLogMetricTransformations(m map[string]interface{}) []*cloudwatchlogs.MetricTransformation { 1267 transformation := cloudwatchlogs.MetricTransformation{ 1268 MetricName: aws.String(m["name"].(string)), 1269 MetricNamespace: aws.String(m["namespace"].(string)), 1270 MetricValue: aws.String(m["value"].(string)), 1271 } 1272 1273 return []*cloudwatchlogs.MetricTransformation{&transformation} 1274 } 1275 1276 func flattenCloudWachLogMetricTransformations(ts []*cloudwatchlogs.MetricTransformation) map[string]string { 1277 m := make(map[string]string, 0) 1278 1279 m["name"] = *ts[0].MetricName 1280 m["namespace"] = *ts[0].MetricNamespace 1281 m["value"] = *ts[0].MetricValue 1282 1283 return m 1284 } 1285 1286 func flattenBeanstalkAsg(list []*elasticbeanstalk.AutoScalingGroup) []string { 1287 strs := make([]string, 0, len(list)) 1288 for _, r := range list { 1289 if r.Name != nil { 1290 strs = append(strs, *r.Name) 1291 } 1292 } 1293 return strs 1294 } 1295 1296 func flattenBeanstalkInstances(list []*elasticbeanstalk.Instance) []string { 1297 strs := make([]string, 0, len(list)) 1298 for _, r := range list { 1299 if r.Id != nil { 1300 strs = append(strs, *r.Id) 1301 } 1302 } 1303 return strs 1304 } 1305 1306 func flattenBeanstalkLc(list []*elasticbeanstalk.LaunchConfiguration) []string { 1307 strs := make([]string, 0, len(list)) 1308 for _, r := range list { 1309 if r.Name != nil { 1310 strs = append(strs, *r.Name) 1311 } 1312 } 1313 return strs 1314 } 1315 1316 func flattenBeanstalkElb(list []*elasticbeanstalk.LoadBalancer) []string { 1317 strs := make([]string, 0, len(list)) 1318 for _, r := range list { 1319 if r.Name != nil { 1320 strs = append(strs, *r.Name) 1321 } 1322 } 1323 return strs 1324 } 1325 1326 func flattenBeanstalkSqs(list []*elasticbeanstalk.Queue) []string { 1327 strs := make([]string, 0, len(list)) 1328 for _, r := range list { 1329 if r.URL != nil { 1330 strs = append(strs, *r.URL) 1331 } 1332 } 1333 return strs 1334 } 1335 1336 func flattenBeanstalkTrigger(list []*elasticbeanstalk.Trigger) []string { 1337 strs := make([]string, 0, len(list)) 1338 for _, r := range list { 1339 if r.Name != nil { 1340 strs = append(strs, *r.Name) 1341 } 1342 } 1343 return strs 1344 } 1345 1346 // There are several parts of the AWS API that will sort lists of strings, 1347 // causing diffs inbetweeen resources that use lists. This avoids a bit of 1348 // code duplication for pre-sorts that can be used for things like hash 1349 // functions, etc. 1350 func sortInterfaceSlice(in []interface{}) []interface{} { 1351 a := []string{} 1352 b := []interface{}{} 1353 for _, v := range in { 1354 a = append(a, v.(string)) 1355 } 1356 1357 sort.Strings(a) 1358 1359 for _, v := range a { 1360 b = append(b, v) 1361 } 1362 1363 return b 1364 } 1365 1366 func flattenApiGatewayThrottleSettings(settings *apigateway.ThrottleSettings) []map[string]interface{} { 1367 result := make([]map[string]interface{}, 0, 1) 1368 1369 if settings != nil { 1370 r := make(map[string]interface{}) 1371 if settings.BurstLimit != nil { 1372 r["burst_limit"] = *settings.BurstLimit 1373 } 1374 1375 if settings.RateLimit != nil { 1376 r["rate_limit"] = *settings.RateLimit 1377 } 1378 1379 result = append(result, r) 1380 } 1381 1382 return result 1383 } 1384 1385 // TODO: refactor some of these helper functions and types in the terraform/helper packages 1386 1387 // getStringPtr returns a *string version of the value taken from m, where m 1388 // can be a map[string]interface{} or a *schema.ResourceData. If the key isn't 1389 // present or is empty, getNilString returns nil. 1390 func getStringPtr(m interface{}, key string) *string { 1391 switch m := m.(type) { 1392 case map[string]interface{}: 1393 v := m[key] 1394 1395 if v == nil { 1396 return nil 1397 } 1398 1399 s := v.(string) 1400 if s == "" { 1401 return nil 1402 } 1403 1404 return &s 1405 1406 case *schema.ResourceData: 1407 if v, ok := m.GetOk(key); ok { 1408 if v == nil || v.(string) == "" { 1409 return nil 1410 } 1411 s := v.(string) 1412 return &s 1413 } 1414 1415 default: 1416 panic("unknown type in getStringPtr") 1417 } 1418 1419 return nil 1420 } 1421 1422 // getStringPtrList returns a []*string version of the map value. If the key 1423 // isn't present, getNilStringList returns nil. 1424 func getStringPtrList(m map[string]interface{}, key string) []*string { 1425 if v, ok := m[key]; ok { 1426 var stringList []*string 1427 for _, i := range v.([]interface{}) { 1428 s := i.(string) 1429 stringList = append(stringList, &s) 1430 } 1431 1432 return stringList 1433 } 1434 1435 return nil 1436 } 1437 1438 // a convenience wrapper type for the schema.Set map[string]interface{} 1439 // Set operations only alter the underlying map if the value is not nil 1440 type setMap map[string]interface{} 1441 1442 // SetString sets m[key] = *value only if `value != nil` 1443 func (s setMap) SetString(key string, value *string) { 1444 if value == nil { 1445 return 1446 } 1447 1448 s[key] = *value 1449 } 1450 1451 // SetStringMap sets key to value as a map[string]interface{}, stripping any nil 1452 // values. The value parameter can be a map[string]interface{}, a 1453 // map[string]*string, or a map[string]string. 1454 func (s setMap) SetStringMap(key string, value interface{}) { 1455 // because these methods are meant to be chained without intermediate 1456 // checks for nil, we are likely to get interfaces with dynamic types but 1457 // a nil value. 1458 if reflect.ValueOf(value).IsNil() { 1459 return 1460 } 1461 1462 m := make(map[string]interface{}) 1463 1464 switch value := value.(type) { 1465 case map[string]string: 1466 for k, v := range value { 1467 m[k] = v 1468 } 1469 case map[string]*string: 1470 for k, v := range value { 1471 if v == nil { 1472 continue 1473 } 1474 m[k] = *v 1475 } 1476 case map[string]interface{}: 1477 for k, v := range value { 1478 if v == nil { 1479 continue 1480 } 1481 1482 switch v := v.(type) { 1483 case string: 1484 m[k] = v 1485 case *string: 1486 if v != nil { 1487 m[k] = *v 1488 } 1489 default: 1490 panic(fmt.Sprintf("unknown type for SetString: %T", v)) 1491 } 1492 } 1493 } 1494 1495 // catch the case where the interface wasn't nil, but we had no non-nil values 1496 if len(m) > 0 { 1497 s[key] = m 1498 } 1499 } 1500 1501 // Set assigns value to s[key] if value isn't nil 1502 func (s setMap) Set(key string, value interface{}) { 1503 if reflect.ValueOf(value).IsNil() { 1504 return 1505 } 1506 1507 s[key] = value 1508 } 1509 1510 // Map returns the raw map type for a shorter type conversion 1511 func (s setMap) Map() map[string]interface{} { 1512 return map[string]interface{}(s) 1513 } 1514 1515 // MapList returns the map[string]interface{} as a single element in a slice to 1516 // match the schema.Set data type used for structs. 1517 func (s setMap) MapList() []map[string]interface{} { 1518 return []map[string]interface{}{s.Map()} 1519 } 1520 1521 // Takes the result of flatmap.Expand for an array of policy attributes and 1522 // returns ELB API compatible objects 1523 func expandPolicyAttributes(configured []interface{}) ([]*elb.PolicyAttribute, error) { 1524 attributes := make([]*elb.PolicyAttribute, 0, len(configured)) 1525 1526 // Loop over our configured attributes and create 1527 // an array of aws-sdk-go compatible objects 1528 for _, lRaw := range configured { 1529 data := lRaw.(map[string]interface{}) 1530 1531 a := &elb.PolicyAttribute{ 1532 AttributeName: aws.String(data["name"].(string)), 1533 AttributeValue: aws.String(data["value"].(string)), 1534 } 1535 1536 attributes = append(attributes, a) 1537 1538 } 1539 1540 return attributes, nil 1541 } 1542 1543 // Flattens an array of PolicyAttributes into a []interface{} 1544 func flattenPolicyAttributes(list []*elb.PolicyAttributeDescription) []interface{} { 1545 attributes := []interface{}{} 1546 for _, attrdef := range list { 1547 attribute := map[string]string{ 1548 "name": *attrdef.AttributeName, 1549 "value": *attrdef.AttributeValue, 1550 } 1551 1552 attributes = append(attributes, attribute) 1553 1554 } 1555 1556 return attributes 1557 }