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