github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/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 compatible 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 compatible 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 compatible 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 compatible 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 setting := map[string]interface{}{ 628 "name": *j.Name, 629 } 630 if j.Value != nil { 631 setting["value"] = *j.Value 632 } 633 634 settings = append(settings, setting) 635 } 636 637 r["option_settings"] = settings 638 } 639 result = append(result, r) 640 } 641 } 642 return result 643 } 644 645 // Flattens an array of Parameters into a []map[string]interface{} 646 func flattenParameters(list []*rds.Parameter) []map[string]interface{} { 647 result := make([]map[string]interface{}, 0, len(list)) 648 for _, i := range list { 649 if i.ParameterName != nil { 650 r := make(map[string]interface{}) 651 r["name"] = strings.ToLower(*i.ParameterName) 652 // Default empty string, guard against nil parameter values 653 r["value"] = "" 654 if i.ParameterValue != nil { 655 r["value"] = strings.ToLower(*i.ParameterValue) 656 } 657 if i.ApplyMethod != nil { 658 r["apply_method"] = strings.ToLower(*i.ApplyMethod) 659 } 660 661 result = append(result, r) 662 } 663 } 664 return result 665 } 666 667 // Flattens an array of Redshift Parameters into a []map[string]interface{} 668 func flattenRedshiftParameters(list []*redshift.Parameter) []map[string]interface{} { 669 result := make([]map[string]interface{}, 0, len(list)) 670 for _, i := range list { 671 result = append(result, map[string]interface{}{ 672 "name": strings.ToLower(*i.ParameterName), 673 "value": strings.ToLower(*i.ParameterValue), 674 }) 675 } 676 return result 677 } 678 679 // Flattens an array of Parameters into a []map[string]interface{} 680 func flattenElastiCacheParameters(list []*elasticache.Parameter) []map[string]interface{} { 681 result := make([]map[string]interface{}, 0, len(list)) 682 for _, i := range list { 683 if i.ParameterValue != nil { 684 result = append(result, map[string]interface{}{ 685 "name": strings.ToLower(*i.ParameterName), 686 "value": strings.ToLower(*i.ParameterValue), 687 }) 688 } 689 } 690 return result 691 } 692 693 // Takes the result of flatmap.Expand for an array of strings 694 // and returns a []*string 695 func expandStringList(configured []interface{}) []*string { 696 vs := make([]*string, 0, len(configured)) 697 for _, v := range configured { 698 vs = append(vs, aws.String(v.(string))) 699 } 700 return vs 701 } 702 703 // Takes the result of schema.Set of strings and returns a []*string 704 func expandStringSet(configured *schema.Set) []*string { 705 return expandStringList(configured.List()) 706 } 707 708 // Takes list of pointers to strings. Expand to an array 709 // of raw strings and returns a []interface{} 710 // to keep compatibility w/ schema.NewSetschema.NewSet 711 func flattenStringList(list []*string) []interface{} { 712 vs := make([]interface{}, 0, len(list)) 713 for _, v := range list { 714 vs = append(vs, *v) 715 } 716 return vs 717 } 718 719 //Flattens an array of private ip addresses into a []string, where the elements returned are the IP strings e.g. "192.168.0.0" 720 func flattenNetworkInterfacesPrivateIPAddresses(dtos []*ec2.NetworkInterfacePrivateIpAddress) []string { 721 ips := make([]string, 0, len(dtos)) 722 for _, v := range dtos { 723 ip := *v.PrivateIpAddress 724 ips = append(ips, ip) 725 } 726 return ips 727 } 728 729 //Flattens security group identifiers into a []string, where the elements returned are the GroupIDs 730 func flattenGroupIdentifiers(dtos []*ec2.GroupIdentifier) []string { 731 ids := make([]string, 0, len(dtos)) 732 for _, v := range dtos { 733 group_id := *v.GroupId 734 ids = append(ids, group_id) 735 } 736 return ids 737 } 738 739 //Expands an array of IPs into a ec2 Private IP Address Spec 740 func expandPrivateIPAddresses(ips []interface{}) []*ec2.PrivateIpAddressSpecification { 741 dtos := make([]*ec2.PrivateIpAddressSpecification, 0, len(ips)) 742 for i, v := range ips { 743 new_private_ip := &ec2.PrivateIpAddressSpecification{ 744 PrivateIpAddress: aws.String(v.(string)), 745 } 746 747 new_private_ip.Primary = aws.Bool(i == 0) 748 749 dtos = append(dtos, new_private_ip) 750 } 751 return dtos 752 } 753 754 //Flattens network interface attachment into a map[string]interface 755 func flattenAttachment(a *ec2.NetworkInterfaceAttachment) map[string]interface{} { 756 att := make(map[string]interface{}) 757 if a.InstanceId != nil { 758 att["instance"] = *a.InstanceId 759 } 760 att["device_index"] = *a.DeviceIndex 761 att["attachment_id"] = *a.AttachmentId 762 return att 763 } 764 765 func flattenElastiCacheSecurityGroupNames(securityGroups []*elasticache.CacheSecurityGroupMembership) []string { 766 result := make([]string, 0, len(securityGroups)) 767 for _, sg := range securityGroups { 768 if sg.CacheSecurityGroupName != nil { 769 result = append(result, *sg.CacheSecurityGroupName) 770 } 771 } 772 return result 773 } 774 775 func flattenElastiCacheSecurityGroupIds(securityGroups []*elasticache.SecurityGroupMembership) []string { 776 result := make([]string, 0, len(securityGroups)) 777 for _, sg := range securityGroups { 778 if sg.SecurityGroupId != nil { 779 result = append(result, *sg.SecurityGroupId) 780 } 781 } 782 return result 783 } 784 785 // Flattens step adjustments into a list of map[string]interface. 786 func flattenStepAdjustments(adjustments []*autoscaling.StepAdjustment) []map[string]interface{} { 787 result := make([]map[string]interface{}, 0, len(adjustments)) 788 for _, raw := range adjustments { 789 a := map[string]interface{}{ 790 "scaling_adjustment": *raw.ScalingAdjustment, 791 } 792 if raw.MetricIntervalUpperBound != nil { 793 a["metric_interval_upper_bound"] = *raw.MetricIntervalUpperBound 794 } 795 if raw.MetricIntervalLowerBound != nil { 796 a["metric_interval_lower_bound"] = *raw.MetricIntervalLowerBound 797 } 798 result = append(result, a) 799 } 800 return result 801 } 802 803 func flattenResourceRecords(recs []*route53.ResourceRecord) []string { 804 strs := make([]string, 0, len(recs)) 805 for _, r := range recs { 806 if r.Value != nil { 807 s := strings.Replace(*r.Value, "\"", "", 2) 808 strs = append(strs, s) 809 } 810 } 811 return strs 812 } 813 814 func expandResourceRecords(recs []interface{}, typeStr string) []*route53.ResourceRecord { 815 records := make([]*route53.ResourceRecord, 0, len(recs)) 816 for _, r := range recs { 817 s := r.(string) 818 switch typeStr { 819 case "TXT", "SPF": 820 str := fmt.Sprintf("\"%s\"", s) 821 records = append(records, &route53.ResourceRecord{Value: aws.String(str)}) 822 default: 823 records = append(records, &route53.ResourceRecord{Value: aws.String(s)}) 824 } 825 } 826 return records 827 } 828 829 func expandESClusterConfig(m map[string]interface{}) *elasticsearch.ElasticsearchClusterConfig { 830 config := elasticsearch.ElasticsearchClusterConfig{} 831 832 if v, ok := m["dedicated_master_enabled"]; ok { 833 isEnabled := v.(bool) 834 config.DedicatedMasterEnabled = aws.Bool(isEnabled) 835 836 if isEnabled { 837 if v, ok := m["dedicated_master_count"]; ok && v.(int) > 0 { 838 config.DedicatedMasterCount = aws.Int64(int64(v.(int))) 839 } 840 if v, ok := m["dedicated_master_type"]; ok && v.(string) != "" { 841 config.DedicatedMasterType = aws.String(v.(string)) 842 } 843 } 844 } 845 846 if v, ok := m["instance_count"]; ok { 847 config.InstanceCount = aws.Int64(int64(v.(int))) 848 } 849 if v, ok := m["instance_type"]; ok { 850 config.InstanceType = aws.String(v.(string)) 851 } 852 853 if v, ok := m["zone_awareness_enabled"]; ok { 854 config.ZoneAwarenessEnabled = aws.Bool(v.(bool)) 855 } 856 857 return &config 858 } 859 860 func flattenESClusterConfig(c *elasticsearch.ElasticsearchClusterConfig) []map[string]interface{} { 861 m := map[string]interface{}{} 862 863 if c.DedicatedMasterCount != nil { 864 m["dedicated_master_count"] = *c.DedicatedMasterCount 865 } 866 if c.DedicatedMasterEnabled != nil { 867 m["dedicated_master_enabled"] = *c.DedicatedMasterEnabled 868 } 869 if c.DedicatedMasterType != nil { 870 m["dedicated_master_type"] = *c.DedicatedMasterType 871 } 872 if c.InstanceCount != nil { 873 m["instance_count"] = *c.InstanceCount 874 } 875 if c.InstanceType != nil { 876 m["instance_type"] = *c.InstanceType 877 } 878 if c.ZoneAwarenessEnabled != nil { 879 m["zone_awareness_enabled"] = *c.ZoneAwarenessEnabled 880 } 881 882 return []map[string]interface{}{m} 883 } 884 885 func flattenESEBSOptions(o *elasticsearch.EBSOptions) []map[string]interface{} { 886 m := map[string]interface{}{} 887 888 if o.EBSEnabled != nil { 889 m["ebs_enabled"] = *o.EBSEnabled 890 } 891 if o.Iops != nil { 892 m["iops"] = *o.Iops 893 } 894 if o.VolumeSize != nil { 895 m["volume_size"] = *o.VolumeSize 896 } 897 if o.VolumeType != nil { 898 m["volume_type"] = *o.VolumeType 899 } 900 901 return []map[string]interface{}{m} 902 } 903 904 func expandESEBSOptions(m map[string]interface{}) *elasticsearch.EBSOptions { 905 options := elasticsearch.EBSOptions{} 906 907 if v, ok := m["ebs_enabled"]; ok { 908 options.EBSEnabled = aws.Bool(v.(bool)) 909 } 910 if v, ok := m["iops"]; ok && v.(int) > 0 { 911 options.Iops = aws.Int64(int64(v.(int))) 912 } 913 if v, ok := m["volume_size"]; ok && v.(int) > 0 { 914 options.VolumeSize = aws.Int64(int64(v.(int))) 915 } 916 if v, ok := m["volume_type"]; ok && v.(string) != "" { 917 options.VolumeType = aws.String(v.(string)) 918 } 919 920 return &options 921 } 922 923 func pointersMapToStringList(pointers map[string]*string) map[string]interface{} { 924 list := make(map[string]interface{}, len(pointers)) 925 for i, v := range pointers { 926 list[i] = *v 927 } 928 return list 929 } 930 931 func stringMapToPointers(m map[string]interface{}) map[string]*string { 932 list := make(map[string]*string, len(m)) 933 for i, v := range m { 934 list[i] = aws.String(v.(string)) 935 } 936 return list 937 } 938 939 func flattenDSVpcSettings( 940 s *directoryservice.DirectoryVpcSettingsDescription) []map[string]interface{} { 941 settings := make(map[string]interface{}, 0) 942 943 if s == nil { 944 return nil 945 } 946 947 settings["subnet_ids"] = schema.NewSet(schema.HashString, flattenStringList(s.SubnetIds)) 948 settings["vpc_id"] = *s.VpcId 949 950 return []map[string]interface{}{settings} 951 } 952 953 func flattenLambdaVpcConfigResponse(s *lambda.VpcConfigResponse) []map[string]interface{} { 954 settings := make(map[string]interface{}, 0) 955 956 if s == nil { 957 return nil 958 } 959 960 if len(s.SubnetIds) == 0 && len(s.SecurityGroupIds) == 0 && s.VpcId == nil { 961 return nil 962 } 963 964 settings["subnet_ids"] = schema.NewSet(schema.HashString, flattenStringList(s.SubnetIds)) 965 settings["security_group_ids"] = schema.NewSet(schema.HashString, flattenStringList(s.SecurityGroupIds)) 966 if s.VpcId != nil { 967 settings["vpc_id"] = *s.VpcId 968 } 969 970 return []map[string]interface{}{settings} 971 } 972 973 func flattenDSConnectSettings( 974 customerDnsIps []*string, 975 s *directoryservice.DirectoryConnectSettingsDescription) []map[string]interface{} { 976 if s == nil { 977 return nil 978 } 979 980 settings := make(map[string]interface{}, 0) 981 982 settings["customer_dns_ips"] = schema.NewSet(schema.HashString, flattenStringList(customerDnsIps)) 983 settings["connect_ips"] = schema.NewSet(schema.HashString, flattenStringList(s.ConnectIps)) 984 settings["customer_username"] = *s.CustomerUserName 985 settings["subnet_ids"] = schema.NewSet(schema.HashString, flattenStringList(s.SubnetIds)) 986 settings["vpc_id"] = *s.VpcId 987 988 return []map[string]interface{}{settings} 989 } 990 991 func expandCloudFormationParameters(params map[string]interface{}) []*cloudformation.Parameter { 992 var cfParams []*cloudformation.Parameter 993 for k, v := range params { 994 cfParams = append(cfParams, &cloudformation.Parameter{ 995 ParameterKey: aws.String(k), 996 ParameterValue: aws.String(v.(string)), 997 }) 998 } 999 1000 return cfParams 1001 } 1002 1003 // flattenCloudFormationParameters is flattening list of 1004 // *cloudformation.Parameters and only returning existing 1005 // parameters to avoid clash with default values 1006 func flattenCloudFormationParameters(cfParams []*cloudformation.Parameter, 1007 originalParams map[string]interface{}) map[string]interface{} { 1008 params := make(map[string]interface{}, len(cfParams)) 1009 for _, p := range cfParams { 1010 _, isConfigured := originalParams[*p.ParameterKey] 1011 if isConfigured { 1012 params[*p.ParameterKey] = *p.ParameterValue 1013 } 1014 } 1015 return params 1016 } 1017 1018 func flattenAllCloudFormationParameters(cfParams []*cloudformation.Parameter) map[string]interface{} { 1019 params := make(map[string]interface{}, len(cfParams)) 1020 for _, p := range cfParams { 1021 params[*p.ParameterKey] = *p.ParameterValue 1022 } 1023 return params 1024 } 1025 1026 func expandCloudFormationTags(tags map[string]interface{}) []*cloudformation.Tag { 1027 var cfTags []*cloudformation.Tag 1028 for k, v := range tags { 1029 cfTags = append(cfTags, &cloudformation.Tag{ 1030 Key: aws.String(k), 1031 Value: aws.String(v.(string)), 1032 }) 1033 } 1034 return cfTags 1035 } 1036 1037 func flattenCloudFormationTags(cfTags []*cloudformation.Tag) map[string]string { 1038 tags := make(map[string]string, len(cfTags)) 1039 for _, t := range cfTags { 1040 tags[*t.Key] = *t.Value 1041 } 1042 return tags 1043 } 1044 1045 func flattenCloudFormationOutputs(cfOutputs []*cloudformation.Output) map[string]string { 1046 outputs := make(map[string]string, len(cfOutputs)) 1047 for _, o := range cfOutputs { 1048 outputs[*o.OutputKey] = *o.OutputValue 1049 } 1050 return outputs 1051 } 1052 1053 func flattenAsgEnabledMetrics(list []*autoscaling.EnabledMetric) []string { 1054 strs := make([]string, 0, len(list)) 1055 for _, r := range list { 1056 if r.Metric != nil { 1057 strs = append(strs, *r.Metric) 1058 } 1059 } 1060 return strs 1061 } 1062 1063 func flattenKinesisShardLevelMetrics(list []*kinesis.EnhancedMetrics) []string { 1064 if len(list) == 0 { 1065 return []string{} 1066 } 1067 strs := make([]string, 0, len(list[0].ShardLevelMetrics)) 1068 for _, s := range list[0].ShardLevelMetrics { 1069 strs = append(strs, *s) 1070 } 1071 return strs 1072 } 1073 1074 func flattenApiGatewayStageKeys(keys []*string) []map[string]interface{} { 1075 stageKeys := make([]map[string]interface{}, 0, len(keys)) 1076 for _, o := range keys { 1077 key := make(map[string]interface{}) 1078 parts := strings.Split(*o, "/") 1079 key["stage_name"] = parts[1] 1080 key["rest_api_id"] = parts[0] 1081 1082 stageKeys = append(stageKeys, key) 1083 } 1084 return stageKeys 1085 } 1086 1087 func expandApiGatewayStageKeys(d *schema.ResourceData) []*apigateway.StageKey { 1088 var stageKeys []*apigateway.StageKey 1089 1090 if stageKeyData, ok := d.GetOk("stage_key"); ok { 1091 params := stageKeyData.(*schema.Set).List() 1092 for k := range params { 1093 data := params[k].(map[string]interface{}) 1094 stageKeys = append(stageKeys, &apigateway.StageKey{ 1095 RestApiId: aws.String(data["rest_api_id"].(string)), 1096 StageName: aws.String(data["stage_name"].(string)), 1097 }) 1098 } 1099 } 1100 1101 return stageKeys 1102 } 1103 1104 func expandApiGatewayRequestResponseModelOperations(d *schema.ResourceData, key string, prefix string) []*apigateway.PatchOperation { 1105 operations := make([]*apigateway.PatchOperation, 0) 1106 1107 oldModels, newModels := d.GetChange(key) 1108 oldModelMap := oldModels.(map[string]interface{}) 1109 newModelMap := newModels.(map[string]interface{}) 1110 1111 for k, _ := range oldModelMap { 1112 operation := apigateway.PatchOperation{ 1113 Op: aws.String("remove"), 1114 Path: aws.String(fmt.Sprintf("/%s/%s", prefix, strings.Replace(k, "/", "~1", -1))), 1115 } 1116 1117 for nK, nV := range newModelMap { 1118 if nK == k { 1119 operation.Op = aws.String("replace") 1120 operation.Value = aws.String(nV.(string)) 1121 } 1122 } 1123 1124 operations = append(operations, &operation) 1125 } 1126 1127 for nK, nV := range newModelMap { 1128 exists := false 1129 for k, _ := range oldModelMap { 1130 if k == nK { 1131 exists = true 1132 } 1133 } 1134 if !exists { 1135 operation := apigateway.PatchOperation{ 1136 Op: aws.String("add"), 1137 Path: aws.String(fmt.Sprintf("/%s/%s", prefix, strings.Replace(nK, "/", "~1", -1))), 1138 Value: aws.String(nV.(string)), 1139 } 1140 operations = append(operations, &operation) 1141 } 1142 } 1143 1144 return operations 1145 } 1146 1147 func deprecatedExpandApiGatewayMethodParametersJSONOperations(d *schema.ResourceData, key string, prefix string) ([]*apigateway.PatchOperation, error) { 1148 operations := make([]*apigateway.PatchOperation, 0) 1149 oldParameters, newParameters := d.GetChange(key) 1150 oldParametersMap := make(map[string]interface{}) 1151 newParametersMap := make(map[string]interface{}) 1152 1153 if err := json.Unmarshal([]byte(oldParameters.(string)), &oldParametersMap); err != nil { 1154 err := fmt.Errorf("Error unmarshaling old %s: %s", key, err) 1155 return operations, err 1156 } 1157 1158 if err := json.Unmarshal([]byte(newParameters.(string)), &newParametersMap); err != nil { 1159 err := fmt.Errorf("Error unmarshaling new %s: %s", key, err) 1160 return operations, err 1161 } 1162 1163 for k, _ := range oldParametersMap { 1164 operation := apigateway.PatchOperation{ 1165 Op: aws.String("remove"), 1166 Path: aws.String(fmt.Sprintf("/%s/%s", prefix, k)), 1167 } 1168 1169 for nK, nV := range newParametersMap { 1170 if nK == k { 1171 operation.Op = aws.String("replace") 1172 operation.Value = aws.String(strconv.FormatBool(nV.(bool))) 1173 } 1174 } 1175 1176 operations = append(operations, &operation) 1177 } 1178 1179 for nK, nV := range newParametersMap { 1180 exists := false 1181 for k, _ := range oldParametersMap { 1182 if k == nK { 1183 exists = true 1184 } 1185 } 1186 if !exists { 1187 operation := apigateway.PatchOperation{ 1188 Op: aws.String("add"), 1189 Path: aws.String(fmt.Sprintf("/%s/%s", prefix, nK)), 1190 Value: aws.String(strconv.FormatBool(nV.(bool))), 1191 } 1192 operations = append(operations, &operation) 1193 } 1194 } 1195 1196 return operations, nil 1197 } 1198 1199 func expandApiGatewayMethodParametersOperations(d *schema.ResourceData, key string, prefix string) ([]*apigateway.PatchOperation, error) { 1200 operations := make([]*apigateway.PatchOperation, 0) 1201 1202 oldParameters, newParameters := d.GetChange(key) 1203 oldParametersMap := oldParameters.(map[string]interface{}) 1204 newParametersMap := newParameters.(map[string]interface{}) 1205 1206 for k, _ := range oldParametersMap { 1207 operation := apigateway.PatchOperation{ 1208 Op: aws.String("remove"), 1209 Path: aws.String(fmt.Sprintf("/%s/%s", prefix, k)), 1210 } 1211 1212 for nK, nV := range newParametersMap { 1213 b, ok := nV.(bool) 1214 if !ok { 1215 value, _ := strconv.ParseBool(nV.(string)) 1216 b = value 1217 } 1218 if nK == k { 1219 operation.Op = aws.String("replace") 1220 operation.Value = aws.String(strconv.FormatBool(b)) 1221 } 1222 } 1223 1224 operations = append(operations, &operation) 1225 } 1226 1227 for nK, nV := range newParametersMap { 1228 exists := false 1229 for k, _ := range oldParametersMap { 1230 if k == nK { 1231 exists = true 1232 } 1233 } 1234 if !exists { 1235 b, ok := nV.(bool) 1236 if !ok { 1237 value, _ := strconv.ParseBool(nV.(string)) 1238 b = value 1239 } 1240 operation := apigateway.PatchOperation{ 1241 Op: aws.String("add"), 1242 Path: aws.String(fmt.Sprintf("/%s/%s", prefix, nK)), 1243 Value: aws.String(strconv.FormatBool(b)), 1244 } 1245 operations = append(operations, &operation) 1246 } 1247 } 1248 1249 return operations, nil 1250 } 1251 1252 func expandApiGatewayStageKeyOperations(d *schema.ResourceData) []*apigateway.PatchOperation { 1253 operations := make([]*apigateway.PatchOperation, 0) 1254 1255 prev, curr := d.GetChange("stage_key") 1256 prevList := prev.(*schema.Set).List() 1257 currList := curr.(*schema.Set).List() 1258 1259 for i := range prevList { 1260 p := prevList[i].(map[string]interface{}) 1261 exists := false 1262 1263 for j := range currList { 1264 c := currList[j].(map[string]interface{}) 1265 if c["rest_api_id"].(string) == p["rest_api_id"].(string) && c["stage_name"].(string) == p["stage_name"].(string) { 1266 exists = true 1267 } 1268 } 1269 1270 if !exists { 1271 operations = append(operations, &apigateway.PatchOperation{ 1272 Op: aws.String("remove"), 1273 Path: aws.String("/stages"), 1274 Value: aws.String(fmt.Sprintf("%s/%s", p["rest_api_id"].(string), p["stage_name"].(string))), 1275 }) 1276 } 1277 } 1278 1279 for i := range currList { 1280 c := currList[i].(map[string]interface{}) 1281 exists := false 1282 1283 for j := range prevList { 1284 p := prevList[j].(map[string]interface{}) 1285 if c["rest_api_id"].(string) == p["rest_api_id"].(string) && c["stage_name"].(string) == p["stage_name"].(string) { 1286 exists = true 1287 } 1288 } 1289 1290 if !exists { 1291 operations = append(operations, &apigateway.PatchOperation{ 1292 Op: aws.String("add"), 1293 Path: aws.String("/stages"), 1294 Value: aws.String(fmt.Sprintf("%s/%s", c["rest_api_id"].(string), c["stage_name"].(string))), 1295 }) 1296 } 1297 } 1298 1299 return operations 1300 } 1301 1302 func expandCloudWachLogMetricTransformations(m map[string]interface{}) []*cloudwatchlogs.MetricTransformation { 1303 transformation := cloudwatchlogs.MetricTransformation{ 1304 MetricName: aws.String(m["name"].(string)), 1305 MetricNamespace: aws.String(m["namespace"].(string)), 1306 MetricValue: aws.String(m["value"].(string)), 1307 } 1308 1309 return []*cloudwatchlogs.MetricTransformation{&transformation} 1310 } 1311 1312 func flattenCloudWachLogMetricTransformations(ts []*cloudwatchlogs.MetricTransformation) map[string]string { 1313 m := make(map[string]string, 0) 1314 1315 m["name"] = *ts[0].MetricName 1316 m["namespace"] = *ts[0].MetricNamespace 1317 m["value"] = *ts[0].MetricValue 1318 1319 return m 1320 } 1321 1322 func flattenBeanstalkAsg(list []*elasticbeanstalk.AutoScalingGroup) []string { 1323 strs := make([]string, 0, len(list)) 1324 for _, r := range list { 1325 if r.Name != nil { 1326 strs = append(strs, *r.Name) 1327 } 1328 } 1329 return strs 1330 } 1331 1332 func flattenBeanstalkInstances(list []*elasticbeanstalk.Instance) []string { 1333 strs := make([]string, 0, len(list)) 1334 for _, r := range list { 1335 if r.Id != nil { 1336 strs = append(strs, *r.Id) 1337 } 1338 } 1339 return strs 1340 } 1341 1342 func flattenBeanstalkLc(list []*elasticbeanstalk.LaunchConfiguration) []string { 1343 strs := make([]string, 0, len(list)) 1344 for _, r := range list { 1345 if r.Name != nil { 1346 strs = append(strs, *r.Name) 1347 } 1348 } 1349 return strs 1350 } 1351 1352 func flattenBeanstalkElb(list []*elasticbeanstalk.LoadBalancer) []string { 1353 strs := make([]string, 0, len(list)) 1354 for _, r := range list { 1355 if r.Name != nil { 1356 strs = append(strs, *r.Name) 1357 } 1358 } 1359 return strs 1360 } 1361 1362 func flattenBeanstalkSqs(list []*elasticbeanstalk.Queue) []string { 1363 strs := make([]string, 0, len(list)) 1364 for _, r := range list { 1365 if r.URL != nil { 1366 strs = append(strs, *r.URL) 1367 } 1368 } 1369 return strs 1370 } 1371 1372 func flattenBeanstalkTrigger(list []*elasticbeanstalk.Trigger) []string { 1373 strs := make([]string, 0, len(list)) 1374 for _, r := range list { 1375 if r.Name != nil { 1376 strs = append(strs, *r.Name) 1377 } 1378 } 1379 return strs 1380 } 1381 1382 // There are several parts of the AWS API that will sort lists of strings, 1383 // causing diffs inbetween resources that use lists. This avoids a bit of 1384 // code duplication for pre-sorts that can be used for things like hash 1385 // functions, etc. 1386 func sortInterfaceSlice(in []interface{}) []interface{} { 1387 a := []string{} 1388 b := []interface{}{} 1389 for _, v := range in { 1390 a = append(a, v.(string)) 1391 } 1392 1393 sort.Strings(a) 1394 1395 for _, v := range a { 1396 b = append(b, v) 1397 } 1398 1399 return b 1400 } 1401 1402 func flattenApiGatewayThrottleSettings(settings *apigateway.ThrottleSettings) []map[string]interface{} { 1403 result := make([]map[string]interface{}, 0, 1) 1404 1405 if settings != nil { 1406 r := make(map[string]interface{}) 1407 if settings.BurstLimit != nil { 1408 r["burst_limit"] = *settings.BurstLimit 1409 } 1410 1411 if settings.RateLimit != nil { 1412 r["rate_limit"] = *settings.RateLimit 1413 } 1414 1415 result = append(result, r) 1416 } 1417 1418 return result 1419 } 1420 1421 // TODO: refactor some of these helper functions and types in the terraform/helper packages 1422 1423 // getStringPtr returns a *string version of the value taken from m, where m 1424 // can be a map[string]interface{} or a *schema.ResourceData. If the key isn't 1425 // present or is empty, getNilString returns nil. 1426 func getStringPtr(m interface{}, key string) *string { 1427 switch m := m.(type) { 1428 case map[string]interface{}: 1429 v := m[key] 1430 1431 if v == nil { 1432 return nil 1433 } 1434 1435 s := v.(string) 1436 if s == "" { 1437 return nil 1438 } 1439 1440 return &s 1441 1442 case *schema.ResourceData: 1443 if v, ok := m.GetOk(key); ok { 1444 if v == nil || v.(string) == "" { 1445 return nil 1446 } 1447 s := v.(string) 1448 return &s 1449 } 1450 1451 default: 1452 panic("unknown type in getStringPtr") 1453 } 1454 1455 return nil 1456 } 1457 1458 // getStringPtrList returns a []*string version of the map value. If the key 1459 // isn't present, getNilStringList returns nil. 1460 func getStringPtrList(m map[string]interface{}, key string) []*string { 1461 if v, ok := m[key]; ok { 1462 var stringList []*string 1463 for _, i := range v.([]interface{}) { 1464 s := i.(string) 1465 stringList = append(stringList, &s) 1466 } 1467 1468 return stringList 1469 } 1470 1471 return nil 1472 } 1473 1474 // a convenience wrapper type for the schema.Set map[string]interface{} 1475 // Set operations only alter the underlying map if the value is not nil 1476 type setMap map[string]interface{} 1477 1478 // SetString sets m[key] = *value only if `value != nil` 1479 func (s setMap) SetString(key string, value *string) { 1480 if value == nil { 1481 return 1482 } 1483 1484 s[key] = *value 1485 } 1486 1487 // SetStringMap sets key to value as a map[string]interface{}, stripping any nil 1488 // values. The value parameter can be a map[string]interface{}, a 1489 // map[string]*string, or a map[string]string. 1490 func (s setMap) SetStringMap(key string, value interface{}) { 1491 // because these methods are meant to be chained without intermediate 1492 // checks for nil, we are likely to get interfaces with dynamic types but 1493 // a nil value. 1494 if reflect.ValueOf(value).IsNil() { 1495 return 1496 } 1497 1498 m := make(map[string]interface{}) 1499 1500 switch value := value.(type) { 1501 case map[string]string: 1502 for k, v := range value { 1503 m[k] = v 1504 } 1505 case map[string]*string: 1506 for k, v := range value { 1507 if v == nil { 1508 continue 1509 } 1510 m[k] = *v 1511 } 1512 case map[string]interface{}: 1513 for k, v := range value { 1514 if v == nil { 1515 continue 1516 } 1517 1518 switch v := v.(type) { 1519 case string: 1520 m[k] = v 1521 case *string: 1522 if v != nil { 1523 m[k] = *v 1524 } 1525 default: 1526 panic(fmt.Sprintf("unknown type for SetString: %T", v)) 1527 } 1528 } 1529 } 1530 1531 // catch the case where the interface wasn't nil, but we had no non-nil values 1532 if len(m) > 0 { 1533 s[key] = m 1534 } 1535 } 1536 1537 // Set assigns value to s[key] if value isn't nil 1538 func (s setMap) Set(key string, value interface{}) { 1539 if reflect.ValueOf(value).IsNil() { 1540 return 1541 } 1542 1543 s[key] = value 1544 } 1545 1546 // Map returns the raw map type for a shorter type conversion 1547 func (s setMap) Map() map[string]interface{} { 1548 return map[string]interface{}(s) 1549 } 1550 1551 // MapList returns the map[string]interface{} as a single element in a slice to 1552 // match the schema.Set data type used for structs. 1553 func (s setMap) MapList() []map[string]interface{} { 1554 return []map[string]interface{}{s.Map()} 1555 } 1556 1557 // Takes the result of flatmap.Expand for an array of policy attributes and 1558 // returns ELB API compatible objects 1559 func expandPolicyAttributes(configured []interface{}) ([]*elb.PolicyAttribute, error) { 1560 attributes := make([]*elb.PolicyAttribute, 0, len(configured)) 1561 1562 // Loop over our configured attributes and create 1563 // an array of aws-sdk-go compatible objects 1564 for _, lRaw := range configured { 1565 data := lRaw.(map[string]interface{}) 1566 1567 a := &elb.PolicyAttribute{ 1568 AttributeName: aws.String(data["name"].(string)), 1569 AttributeValue: aws.String(data["value"].(string)), 1570 } 1571 1572 attributes = append(attributes, a) 1573 1574 } 1575 1576 return attributes, nil 1577 } 1578 1579 // Flattens an array of PolicyAttributes into a []interface{} 1580 func flattenPolicyAttributes(list []*elb.PolicyAttributeDescription) []interface{} { 1581 attributes := []interface{}{} 1582 for _, attrdef := range list { 1583 attribute := map[string]string{ 1584 "name": *attrdef.AttributeName, 1585 "value": *attrdef.AttributeValue, 1586 } 1587 1588 attributes = append(attributes, attribute) 1589 1590 } 1591 1592 return attributes 1593 } 1594 1595 // Takes a value containing JSON string and passes it through 1596 // the JSON parser to normalize it, returns either a parsing 1597 // error or normalized JSON string. 1598 func normalizeJsonString(jsonString interface{}) (string, error) { 1599 var j interface{} 1600 1601 if jsonString == nil || jsonString.(string) == "" { 1602 return "", nil 1603 } 1604 1605 s := jsonString.(string) 1606 1607 err := json.Unmarshal([]byte(s), &j) 1608 if err != nil { 1609 return s, err 1610 } 1611 1612 bytes, _ := json.Marshal(j) 1613 return string(bytes[:]), nil 1614 }