github.com/tkak/terraform@v0.5.4-0.20150712180941-7f738dc27225/builtin/providers/aws/structure.go (about)

     1  package aws
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"sort"
     8  	"strings"
     9  
    10  	"github.com/aws/aws-sdk-go/aws"
    11  	"github.com/aws/aws-sdk-go/service/ec2"
    12  	"github.com/aws/aws-sdk-go/service/ecs"
    13  	"github.com/aws/aws-sdk-go/service/elasticache"
    14  	"github.com/aws/aws-sdk-go/service/elb"
    15  	"github.com/aws/aws-sdk-go/service/rds"
    16  	"github.com/aws/aws-sdk-go/service/route53"
    17  	"github.com/hashicorp/terraform/helper/schema"
    18  )
    19  
    20  // Takes the result of flatmap.Expand for an array of listeners and
    21  // returns ELB API compatible objects
    22  func expandListeners(configured []interface{}) ([]*elb.Listener, error) {
    23  	listeners := make([]*elb.Listener, 0, len(configured))
    24  
    25  	// Loop over our configured listeners and create
    26  	// an array of aws-sdk-go compatabile objects
    27  	for _, lRaw := range configured {
    28  		data := lRaw.(map[string]interface{})
    29  
    30  		ip := int64(data["instance_port"].(int))
    31  		lp := int64(data["lb_port"].(int))
    32  		l := &elb.Listener{
    33  			InstancePort:     &ip,
    34  			InstanceProtocol: aws.String(data["instance_protocol"].(string)),
    35  			LoadBalancerPort: &lp,
    36  			Protocol:         aws.String(data["lb_protocol"].(string)),
    37  		}
    38  
    39  		if v, ok := data["ssl_certificate_id"]; ok {
    40  			l.SSLCertificateID = aws.String(v.(string))
    41  		}
    42  
    43  		listeners = append(listeners, l)
    44  	}
    45  
    46  	return listeners, nil
    47  }
    48  
    49  // Takes the result of flatmap. Expand for an array of listeners and
    50  // returns ECS Volume compatible objects
    51  func expandEcsVolumes(configured []interface{}) ([]*ecs.Volume, error) {
    52  	volumes := make([]*ecs.Volume, 0, len(configured))
    53  
    54  	// Loop over our configured volumes and create
    55  	// an array of aws-sdk-go compatible objects
    56  	for _, lRaw := range configured {
    57  		data := lRaw.(map[string]interface{})
    58  
    59  		l := &ecs.Volume{
    60  			Name: aws.String(data["name"].(string)),
    61  			Host: &ecs.HostVolumeProperties{
    62  				SourcePath: aws.String(data["host_path"].(string)),
    63  			},
    64  		}
    65  
    66  		volumes = append(volumes, l)
    67  	}
    68  
    69  	return volumes, nil
    70  }
    71  
    72  // Takes JSON in a string. Decodes JSON into
    73  // an array of ecs.ContainerDefinition compatible objects
    74  func expandEcsContainerDefinitions(rawDefinitions string) ([]*ecs.ContainerDefinition, error) {
    75  	var definitions []*ecs.ContainerDefinition
    76  
    77  	err := json.Unmarshal([]byte(rawDefinitions), &definitions)
    78  	if err != nil {
    79  		return nil, fmt.Errorf("Error decoding JSON: %s", err)
    80  	}
    81  
    82  	return definitions, nil
    83  }
    84  
    85  // Takes the result of flatmap. Expand for an array of load balancers and
    86  // returns ecs.LoadBalancer compatible objects
    87  func expandEcsLoadBalancers(configured []interface{}) []*ecs.LoadBalancer {
    88  	loadBalancers := make([]*ecs.LoadBalancer, 0, len(configured))
    89  
    90  	// Loop over our configured load balancers and create
    91  	// an array of aws-sdk-go compatible objects
    92  	for _, lRaw := range configured {
    93  		data := lRaw.(map[string]interface{})
    94  
    95  		l := &ecs.LoadBalancer{
    96  			ContainerName:    aws.String(data["container_name"].(string)),
    97  			ContainerPort:    aws.Long(int64(data["container_port"].(int))),
    98  			LoadBalancerName: aws.String(data["elb_name"].(string)),
    99  		}
   100  
   101  		loadBalancers = append(loadBalancers, l)
   102  	}
   103  
   104  	return loadBalancers
   105  }
   106  
   107  // Takes the result of flatmap.Expand for an array of ingress/egress security
   108  // group rules and returns EC2 API compatible objects. This function will error
   109  // if it finds invalid permissions input, namely a protocol of "-1" with either
   110  // to_port or from_port set to a non-zero value.
   111  func expandIPPerms(
   112  	group *ec2.SecurityGroup, configured []interface{}) ([]*ec2.IPPermission, error) {
   113  	vpc := group.VPCID != nil
   114  
   115  	perms := make([]*ec2.IPPermission, len(configured))
   116  	for i, mRaw := range configured {
   117  		var perm ec2.IPPermission
   118  		m := mRaw.(map[string]interface{})
   119  
   120  		perm.FromPort = aws.Long(int64(m["from_port"].(int)))
   121  		perm.ToPort = aws.Long(int64(m["to_port"].(int)))
   122  		perm.IPProtocol = aws.String(m["protocol"].(string))
   123  
   124  		// When protocol is "-1", AWS won't store any ports for the
   125  		// rule, but also won't error if the user specifies ports other
   126  		// than '0'. Force the user to make a deliberate '0' port
   127  		// choice when specifying a "-1" protocol, and tell them about
   128  		// AWS's behavior in the error message.
   129  		if *perm.IPProtocol == "-1" && (*perm.FromPort != 0 || *perm.ToPort != 0) {
   130  			return nil, fmt.Errorf(
   131  				"from_port (%d) and to_port (%d) must both be 0 to use the the 'ALL' \"-1\" protocol!",
   132  				*perm.FromPort, *perm.ToPort)
   133  		}
   134  
   135  		var groups []string
   136  		if raw, ok := m["security_groups"]; ok {
   137  			list := raw.(*schema.Set).List()
   138  			for _, v := range list {
   139  				groups = append(groups, v.(string))
   140  			}
   141  		}
   142  		if v, ok := m["self"]; ok && v.(bool) {
   143  			if vpc {
   144  				groups = append(groups, *group.GroupID)
   145  			} else {
   146  				groups = append(groups, *group.GroupName)
   147  			}
   148  		}
   149  
   150  		if len(groups) > 0 {
   151  			perm.UserIDGroupPairs = make([]*ec2.UserIDGroupPair, len(groups))
   152  			for i, name := range groups {
   153  				ownerId, id := "", name
   154  				if items := strings.Split(id, "/"); len(items) > 1 {
   155  					ownerId, id = items[0], items[1]
   156  				}
   157  
   158  				perm.UserIDGroupPairs[i] = &ec2.UserIDGroupPair{
   159  					GroupID: aws.String(id),
   160  				}
   161  
   162  				if ownerId != "" {
   163  					perm.UserIDGroupPairs[i].UserID = aws.String(ownerId)
   164  				}
   165  
   166  				if !vpc {
   167  					perm.UserIDGroupPairs[i].GroupID = nil
   168  					perm.UserIDGroupPairs[i].GroupName = aws.String(id)
   169  				}
   170  			}
   171  		}
   172  
   173  		if raw, ok := m["cidr_blocks"]; ok {
   174  			list := raw.([]interface{})
   175  			for _, v := range list {
   176  				perm.IPRanges = append(perm.IPRanges, &ec2.IPRange{CIDRIP: aws.String(v.(string))})
   177  			}
   178  		}
   179  
   180  		perms[i] = &perm
   181  	}
   182  
   183  	return perms, nil
   184  }
   185  
   186  // Takes the result of flatmap.Expand for an array of parameters and
   187  // returns Parameter API compatible objects
   188  func expandParameters(configured []interface{}) ([]*rds.Parameter, error) {
   189  	parameters := make([]*rds.Parameter, 0, len(configured))
   190  
   191  	// Loop over our configured parameters and create
   192  	// an array of aws-sdk-go compatabile objects
   193  	for _, pRaw := range configured {
   194  		data := pRaw.(map[string]interface{})
   195  
   196  		p := &rds.Parameter{
   197  			ApplyMethod:    aws.String(data["apply_method"].(string)),
   198  			ParameterName:  aws.String(data["name"].(string)),
   199  			ParameterValue: aws.String(data["value"].(string)),
   200  		}
   201  
   202  		parameters = append(parameters, p)
   203  	}
   204  
   205  	return parameters, nil
   206  }
   207  
   208  // Takes the result of flatmap.Expand for an array of parameters and
   209  // returns Parameter API compatible objects
   210  func expandElastiCacheParameters(configured []interface{}) ([]*elasticache.ParameterNameValue, error) {
   211  	parameters := make([]*elasticache.ParameterNameValue, 0, len(configured))
   212  
   213  	// Loop over our configured parameters and create
   214  	// an array of aws-sdk-go compatabile objects
   215  	for _, pRaw := range configured {
   216  		data := pRaw.(map[string]interface{})
   217  
   218  		p := &elasticache.ParameterNameValue{
   219  			ParameterName:  aws.String(data["name"].(string)),
   220  			ParameterValue: aws.String(data["value"].(string)),
   221  		}
   222  
   223  		parameters = append(parameters, p)
   224  	}
   225  
   226  	return parameters, nil
   227  }
   228  
   229  // Flattens a health check into something that flatmap.Flatten()
   230  // can handle
   231  func flattenHealthCheck(check *elb.HealthCheck) []map[string]interface{} {
   232  	result := make([]map[string]interface{}, 0, 1)
   233  
   234  	chk := make(map[string]interface{})
   235  	chk["unhealthy_threshold"] = *check.UnhealthyThreshold
   236  	chk["healthy_threshold"] = *check.HealthyThreshold
   237  	chk["target"] = *check.Target
   238  	chk["timeout"] = *check.Timeout
   239  	chk["interval"] = *check.Interval
   240  
   241  	result = append(result, chk)
   242  
   243  	return result
   244  }
   245  
   246  // Flattens an array of UserSecurityGroups into a []string
   247  func flattenSecurityGroups(list []*ec2.UserIDGroupPair) []string {
   248  	result := make([]string, 0, len(list))
   249  	for _, g := range list {
   250  		result = append(result, *g.GroupID)
   251  	}
   252  	return result
   253  }
   254  
   255  // Flattens an array of Instances into a []string
   256  func flattenInstances(list []*elb.Instance) []string {
   257  	result := make([]string, 0, len(list))
   258  	for _, i := range list {
   259  		result = append(result, *i.InstanceID)
   260  	}
   261  	return result
   262  }
   263  
   264  // Expands an array of String Instance IDs into a []Instances
   265  func expandInstanceString(list []interface{}) []*elb.Instance {
   266  	result := make([]*elb.Instance, 0, len(list))
   267  	for _, i := range list {
   268  		result = append(result, &elb.Instance{InstanceID: aws.String(i.(string))})
   269  	}
   270  	return result
   271  }
   272  
   273  // Flattens an array of Backend Descriptions into a a map of instance_port to policy names.
   274  func flattenBackendPolicies(backends []*elb.BackendServerDescription) map[int64][]string {
   275  	policies := make(map[int64][]string)
   276  	for _, i := range backends {
   277  		for _, p := range i.PolicyNames {
   278  			policies[*i.InstancePort] = append(policies[*i.InstancePort], *p)
   279  		}
   280  		sort.Strings(policies[*i.InstancePort])
   281  	}
   282  	return policies
   283  }
   284  
   285  // Flattens an array of Listeners into a []map[string]interface{}
   286  func flattenListeners(list []*elb.ListenerDescription) []map[string]interface{} {
   287  	result := make([]map[string]interface{}, 0, len(list))
   288  	for _, i := range list {
   289  		l := map[string]interface{}{
   290  			"instance_port":     *i.Listener.InstancePort,
   291  			"instance_protocol": strings.ToLower(*i.Listener.InstanceProtocol),
   292  			"lb_port":           *i.Listener.LoadBalancerPort,
   293  			"lb_protocol":       strings.ToLower(*i.Listener.Protocol),
   294  		}
   295  		// SSLCertificateID is optional, and may be nil
   296  		if i.Listener.SSLCertificateID != nil {
   297  			l["ssl_certificate_id"] = *i.Listener.SSLCertificateID
   298  		}
   299  		result = append(result, l)
   300  	}
   301  	return result
   302  }
   303  
   304  // Flattens an array of Volumes into a []map[string]interface{}
   305  func flattenEcsVolumes(list []*ecs.Volume) []map[string]interface{} {
   306  	result := make([]map[string]interface{}, 0, len(list))
   307  	for _, volume := range list {
   308  		l := map[string]interface{}{
   309  			"name":      *volume.Name,
   310  			"host_path": *volume.Host.SourcePath,
   311  		}
   312  		result = append(result, l)
   313  	}
   314  	return result
   315  }
   316  
   317  // Flattens an array of ECS LoadBalancers into a []map[string]interface{}
   318  func flattenEcsLoadBalancers(list []*ecs.LoadBalancer) []map[string]interface{} {
   319  	result := make([]map[string]interface{}, 0, len(list))
   320  	for _, loadBalancer := range list {
   321  		l := map[string]interface{}{
   322  			"elb_name":       *loadBalancer.LoadBalancerName,
   323  			"container_name": *loadBalancer.ContainerName,
   324  			"container_port": *loadBalancer.ContainerPort,
   325  		}
   326  		result = append(result, l)
   327  	}
   328  	return result
   329  }
   330  
   331  // Encodes an array of ecs.ContainerDefinitions into a JSON string
   332  func flattenEcsContainerDefinitions(definitions []*ecs.ContainerDefinition) (string, error) {
   333  	byteArray, err := json.Marshal(definitions)
   334  	if err != nil {
   335  		return "", fmt.Errorf("Error encoding to JSON: %s", err)
   336  	}
   337  
   338  	n := bytes.Index(byteArray, []byte{0})
   339  	return string(byteArray[:n]), nil
   340  }
   341  
   342  // Flattens an array of Parameters into a []map[string]interface{}
   343  func flattenParameters(list []*rds.Parameter) []map[string]interface{} {
   344  	result := make([]map[string]interface{}, 0, len(list))
   345  	for _, i := range list {
   346  		result = append(result, map[string]interface{}{
   347  			"name":  strings.ToLower(*i.ParameterName),
   348  			"value": strings.ToLower(*i.ParameterValue),
   349  		})
   350  	}
   351  	return result
   352  }
   353  
   354  // Flattens an array of Parameters into a []map[string]interface{}
   355  func flattenElastiCacheParameters(list []*elasticache.Parameter) []map[string]interface{} {
   356  	result := make([]map[string]interface{}, 0, len(list))
   357  	for _, i := range list {
   358  		result = append(result, map[string]interface{}{
   359  			"name":  strings.ToLower(*i.ParameterName),
   360  			"value": strings.ToLower(*i.ParameterValue),
   361  		})
   362  	}
   363  	return result
   364  }
   365  
   366  // Takes the result of flatmap.Expand for an array of strings
   367  // and returns a []string
   368  func expandStringList(configured []interface{}) []*string {
   369  	vs := make([]*string, 0, len(configured))
   370  	for _, v := range configured {
   371  		vs = append(vs, aws.String(v.(string)))
   372  	}
   373  	return vs
   374  }
   375  
   376  //Flattens an array of private ip addresses into a []string, where the elements returned are the IP strings e.g. "192.168.0.0"
   377  func flattenNetworkInterfacesPrivateIPAddesses(dtos []*ec2.NetworkInterfacePrivateIPAddress) []string {
   378  	ips := make([]string, 0, len(dtos))
   379  	for _, v := range dtos {
   380  		ip := *v.PrivateIPAddress
   381  		ips = append(ips, ip)
   382  	}
   383  	return ips
   384  }
   385  
   386  //Flattens security group identifiers into a []string, where the elements returned are the GroupIDs
   387  func flattenGroupIdentifiers(dtos []*ec2.GroupIdentifier) []string {
   388  	ids := make([]string, 0, len(dtos))
   389  	for _, v := range dtos {
   390  		group_id := *v.GroupID
   391  		ids = append(ids, group_id)
   392  	}
   393  	return ids
   394  }
   395  
   396  //Expands an array of IPs into a ec2 Private IP Address Spec
   397  func expandPrivateIPAddesses(ips []interface{}) []*ec2.PrivateIPAddressSpecification {
   398  	dtos := make([]*ec2.PrivateIPAddressSpecification, 0, len(ips))
   399  	for i, v := range ips {
   400  		new_private_ip := &ec2.PrivateIPAddressSpecification{
   401  			PrivateIPAddress: aws.String(v.(string)),
   402  		}
   403  
   404  		new_private_ip.Primary = aws.Boolean(i == 0)
   405  
   406  		dtos = append(dtos, new_private_ip)
   407  	}
   408  	return dtos
   409  }
   410  
   411  //Flattens network interface attachment into a map[string]interface
   412  func flattenAttachment(a *ec2.NetworkInterfaceAttachment) map[string]interface{} {
   413  	att := make(map[string]interface{})
   414  	att["instance"] = *a.InstanceID
   415  	att["device_index"] = *a.DeviceIndex
   416  	att["attachment_id"] = *a.AttachmentID
   417  	return att
   418  }
   419  
   420  func flattenResourceRecords(recs []*route53.ResourceRecord) []string {
   421  	strs := make([]string, 0, len(recs))
   422  	for _, r := range recs {
   423  		if r.Value != nil {
   424  			s := strings.Replace(*r.Value, "\"", "", 2)
   425  			strs = append(strs, s)
   426  		}
   427  	}
   428  	return strs
   429  }
   430  
   431  func expandResourceRecords(recs []interface{}, typeStr string) []*route53.ResourceRecord {
   432  	records := make([]*route53.ResourceRecord, 0, len(recs))
   433  	for _, r := range recs {
   434  		s := r.(string)
   435  		switch typeStr {
   436  		case "TXT":
   437  			str := fmt.Sprintf("\"%s\"", s)
   438  			records = append(records, &route53.ResourceRecord{Value: aws.String(str)})
   439  		default:
   440  			records = append(records, &route53.ResourceRecord{Value: aws.String(s)})
   441  		}
   442  	}
   443  	return records
   444  }