func (s *CloudFormationStack) buildStackDetails(stack *cloudformation.Stack) StackDetails {
	stackDetails := StackDetails{
		StackName:        aws.StringValue(stack.StackName),
		Capabilities:     aws.StringValueSlice(stack.Capabilities),
		DisableRollback:  aws.BoolValue(stack.DisableRollback),
		Description:      aws.StringValue(stack.Description),
		NotificationARNs: aws.StringValueSlice(stack.NotificationARNs),
		StackID:          aws.StringValue(stack.StackId),
		StackStatus:      s.stackStatus(aws.StringValue(stack.StackStatus)),
		TimeoutInMinutes: aws.Int64Value(stack.TimeoutInMinutes),
	}

	if stack.Parameters != nil && len(stack.Parameters) > 0 {
		stackDetails.Parameters = make(map[string]string)
		for _, parameter := range stack.Parameters {
			stackDetails.Parameters[aws.StringValue(parameter.ParameterKey)] = aws.StringValue(parameter.ParameterValue)
		}
	}

	if stack.Outputs != nil && len(stack.Outputs) > 0 {
		stackDetails.Outputs = make(map[string]string)
		for _, output := range stack.Outputs {
			stackDetails.Outputs[aws.StringValue(output.OutputKey)] = aws.StringValue(output.OutputValue)
		}
	}

	return stackDetails
}
Exemple #2
0
// Marshal parses the response from the aws sdk into an awsm LoadBalancer
func (l *LoadBalancer) Marshal(balancer *elb.LoadBalancerDescription, region string, secGrpList *SecurityGroups, vpcList *Vpcs, subList *Subnets) {

	// security groups
	secGroupNames := secGrpList.GetSecurityGroupNames(aws.StringValueSlice(balancer.SecurityGroups))
	secGroupNamesSorted := sort.StringSlice(secGroupNames[0:])
	secGroupNamesSorted.Sort()

	// subnets
	subnetNames := subList.GetSubnetNames(aws.StringValueSlice(balancer.Subnets))
	subnetNamesSorted := sort.StringSlice(subnetNames[0:])
	subnetNamesSorted.Sort()

	l.Name = aws.StringValue(balancer.LoadBalancerName)
	l.DNSName = aws.StringValue(balancer.DNSName)
	l.CreatedTime = aws.TimeValue(balancer.CreatedTime) // robots
	l.CreatedHuman = humanize.Time(l.CreatedTime)       // humans
	l.VpcID = aws.StringValue(balancer.VPCId)
	l.Vpc = vpcList.GetVpcName(l.VpcID)
	l.SubnetIDs = aws.StringValueSlice(balancer.Subnets)
	l.Subnets = strings.Join(subnetNamesSorted, ", ")
	l.HealthCheckTarget = aws.StringValue(balancer.HealthCheck.Target)
	l.HealthCheckInterval = fmt.Sprintf("%d seconds", *balancer.HealthCheck.Interval)
	l.Scheme = aws.StringValue(balancer.Scheme)
	l.SecurityGroups = strings.Join(secGroupNamesSorted, ", ")
	l.AvailabilityZones = strings.Join(aws.StringValueSlice(balancer.AvailabilityZones), ", ") // TODO
	l.Region = region
}
func flattenEc2Attributes(ia *emr.Ec2InstanceAttributes) []map[string]interface{} {
	attrs := map[string]interface{}{}
	result := make([]map[string]interface{}, 0)

	if ia.Ec2KeyName != nil {
		attrs["key_name"] = *ia.Ec2KeyName
	}
	if ia.Ec2SubnetId != nil {
		attrs["subnet_id"] = *ia.Ec2SubnetId
	}
	if ia.IamInstanceProfile != nil {
		attrs["instance_profile"] = *ia.IamInstanceProfile
	}
	if ia.EmrManagedMasterSecurityGroup != nil {
		attrs["emr_managed_master_security_group"] = *ia.EmrManagedMasterSecurityGroup
	}
	if ia.EmrManagedSlaveSecurityGroup != nil {
		attrs["emr_managed_slave_security_group"] = *ia.EmrManagedSlaveSecurityGroup
	}

	if len(ia.AdditionalMasterSecurityGroups) > 0 {
		strs := aws.StringValueSlice(ia.AdditionalMasterSecurityGroups)
		attrs["additional_master_security_groups"] = strings.Join(strs, ",")
	}
	if len(ia.AdditionalSlaveSecurityGroups) > 0 {
		strs := aws.StringValueSlice(ia.AdditionalSlaveSecurityGroups)
		attrs["additional_slave_security_groups"] = strings.Join(strs, ",")
	}

	result = append(result, attrs)

	return result
}
func TestConvertToTaskDefinitionWithDnsServers(t *testing.T) {
	dnsServer := "1.2.3.4"

	serviceConfig := &libcompose.ServiceConfig{DNS: libcompose.NewStringorslice(dnsServer)}

	taskDefinition := convertToTaskDefinitionInTest(t, "name", serviceConfig)
	containerDef := *taskDefinition.ContainerDefinitions[0]
	if !reflect.DeepEqual([]string{dnsServer}, aws.StringValueSlice(containerDef.DnsServers)) {
		t.Errorf("Expected dnsServer [%s] But was [%v]", dnsServer, aws.StringValueSlice(containerDef.DnsServers))
	}
}
func TestConvertToTaskDefinitionWithDnsSearch(t *testing.T) {
	dnsSearchDomains := []string{"search.example.com"}

	serviceConfig := &libcompose.ServiceConfig{DNSSearch: libcompose.NewStringorslice(dnsSearchDomains...)}

	taskDefinition := convertToTaskDefinitionInTest(t, "name", serviceConfig)
	containerDef := *taskDefinition.ContainerDefinitions[0]
	if !reflect.DeepEqual(dnsSearchDomains, aws.StringValueSlice(containerDef.DnsSearchDomains)) {
		t.Errorf("Expected dnsSearchDomains [%v] But was [%v]", dnsSearchDomains,
			aws.StringValueSlice(containerDef.DnsSearchDomains))
	}
}
Exemple #6
0
// configChanged checks if function configuration differs from configuration stored in AWS Lambda
func (f *Function) configChanged(config *lambda.GetFunctionOutput) bool {
	type diffConfig struct {
		Description string
		Memory      int64
		Timeout     int64
		Role        string
		Runtime     string
		Handler     string
		VPC         vpc.VPC
	}

	localConfig := &diffConfig{
		Description: f.Description,
		Memory:      f.Memory,
		Timeout:     f.Timeout,
		Role:        f.Role,
		Runtime:     f.Runtime,
		Handler:     f.Handler,
		VPC: vpc.VPC{
			Subnets:        f.VPC.Subnets,
			SecurityGroups: f.VPC.SecurityGroups,
		},
	}

	remoteConfig := &diffConfig{
		Description: *config.Configuration.Description,
		Memory:      *config.Configuration.MemorySize,
		Timeout:     *config.Configuration.Timeout,
		Role:        *config.Configuration.Role,
		Runtime:     *config.Configuration.Runtime,
		Handler:     *config.Configuration.Handler,
	}

	// SDK is inconsistent here. VpcConfig can be nil or empty struct.
	remoteConfig.VPC = vpc.VPC{Subnets: []string{}, SecurityGroups: []string{}}
	if config.Configuration.VpcConfig != nil {
		remoteConfig.VPC = vpc.VPC{
			Subnets:        aws.StringValueSlice(config.Configuration.VpcConfig.SubnetIds),
			SecurityGroups: aws.StringValueSlice(config.Configuration.VpcConfig.SecurityGroupIds),
		}
	}

	// don't make any assumptions about the order AWS stores the subnets or security groups
	sort.StringSlice(remoteConfig.VPC.Subnets).Sort()
	sort.StringSlice(localConfig.VPC.Subnets).Sort()
	sort.StringSlice(remoteConfig.VPC.SecurityGroups).Sort()
	sort.StringSlice(localConfig.VPC.SecurityGroups).Sort()

	localConfigJSON, _ := json.Marshal(localConfig)
	remoteConfigJSON, _ := json.Marshal(remoteConfig)
	return string(localConfigJSON) != string(remoteConfigJSON)
}
func resourceAwsRDSClusterRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).rdsconn

	resp, err := conn.DescribeDBClusters(&rds.DescribeDBClustersInput{
		DBClusterIdentifier: aws.String(d.Id()),
	})

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			if "DBClusterNotFoundFault" == awsErr.Code() {
				d.SetId("")
				log.Printf("[DEBUG] RDS Cluster (%s) not found", d.Id())
				return nil
			}
		}
		log.Printf("[DEBUG] Error describing RDS Cluster (%s)", d.Id())
		return err
	}

	var dbc *rds.DBCluster
	for _, c := range resp.DBClusters {
		if *c.DBClusterIdentifier == d.Id() {
			dbc = c
		}
	}

	if dbc == nil {
		log.Printf("[WARN] RDS Cluster (%s) not found", d.Id())
		d.SetId("")
		return nil
	}

	if err := d.Set("availability_zones", aws.StringValueSlice(dbc.AvailabilityZones)); err != nil {
		return fmt.Errorf("[DEBUG] Error saving AvailabilityZones to state for RDS Cluster (%s): %s", d.Id(), err)
	}
	d.Set("database_name", dbc.DatabaseName)
	d.Set("db_subnet_group_name", dbc.DBSubnetGroup)
	d.Set("endpoint", dbc.Endpoint)
	d.Set("engine", dbc.Engine)
	d.Set("master_username", dbc.MasterUsername)
	d.Set("port", dbc.Port)

	var vpcg []string
	for _, g := range dbc.VpcSecurityGroups {
		vpcg = append(vpcg, *g.VpcSecurityGroupId)
	}
	if err := d.Set("vpc_security_group_ids", vpcg); err != nil {
		return fmt.Errorf("[DEBUG] Error saving VPC Security Group IDs to state for RDS Cluster (%s): %s", d.Id(), err)
	}

	var cm []string
	for _, m := range dbc.DBClusterMembers {
		cm = append(cm, *m.DBInstanceIdentifier)
	}
	if err := d.Set("cluster_members", cm); err != nil {
		return fmt.Errorf("[DEBUG] Error saving RDS Cluster Members to state for RDS Cluster (%s): %s", d.Id(), err)
	}

	return nil
}
Exemple #8
0
func TestStringValueSlice(t *testing.T) {
	for idx, in := range testCasesStringValueSlice {
		if in == nil {
			continue
		}
		out := aws.StringValueSlice(in)
		assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
		for i := range out {
			if in[i] == nil {
				assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
			} else {
				assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
			}
		}

		out2 := aws.StringSlice(out)
		assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
		for i := range out2 {
			if in[i] == nil {
				assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
			} else {
				assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
			}
		}
	}
}
func dataSourceAwsVpcEndpointServiceRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn

	service := d.Get("service").(string)

	log.Printf("[DEBUG] Reading VPC Endpoint Services.")

	request := &ec2.DescribeVpcEndpointServicesInput{}

	resp, err := conn.DescribeVpcEndpointServices(request)
	if err != nil {
		return fmt.Errorf("Error fetching VPC Endpoint Services: %s", err)
	}

	names := aws.StringValueSlice(resp.ServiceNames)
	for _, name := range names {
		if strings.HasSuffix(name, "."+service) {
			d.SetId(strconv.Itoa(hashcode.String(name)))
			d.Set("service_name", name)
			return nil
		}
	}

	return fmt.Errorf("VPC Endpoint Service (%s) not found", service)
}
func testAccCheckAWSOpsworksCreateLayerAttributes(
	opslayer *opsworks.Layer, stackName string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		if *opslayer.Name != stackName {
			return fmt.Errorf("Unexpected name: %s", *opslayer.Name)
		}

		if *opslayer.AutoAssignElasticIps {
			return fmt.Errorf(
				"Unexpected AutoAssignElasticIps: %t", *opslayer.AutoAssignElasticIps)
		}

		if !*opslayer.EnableAutoHealing {
			return fmt.Errorf(
				"Unexpected EnableAutoHealing: %t", *opslayer.EnableAutoHealing)
		}

		if !*opslayer.LifecycleEventConfiguration.Shutdown.DelayUntilElbConnectionsDrained {
			return fmt.Errorf(
				"Unexpected DelayUntilElbConnectionsDrained: %t",
				*opslayer.LifecycleEventConfiguration.Shutdown.DelayUntilElbConnectionsDrained)
		}

		if *opslayer.LifecycleEventConfiguration.Shutdown.ExecutionTimeout != 300 {
			return fmt.Errorf(
				"Unexpected ExecutionTimeout: %d",
				*opslayer.LifecycleEventConfiguration.Shutdown.ExecutionTimeout)
		}

		if v := len(opslayer.CustomSecurityGroupIds); v != 2 {
			return fmt.Errorf("Expected 2 customSecurityGroupIds, got %d", v)
		}

		expectedPackages := []*string{
			aws.String("git"),
			aws.String("golang"),
		}

		if !reflect.DeepEqual(expectedPackages, opslayer.Packages) {
			return fmt.Errorf("Unexpected Packages: %v", aws.StringValueSlice(opslayer.Packages))
		}

		expectedEbsVolumes := []*opsworks.VolumeConfiguration{
			&opsworks.VolumeConfiguration{
				VolumeType:    aws.String("gp2"),
				NumberOfDisks: aws.Int64(2),
				MountPoint:    aws.String("/home"),
				Size:          aws.Int64(100),
				RaidLevel:     aws.Int64(0),
			},
		}

		if !reflect.DeepEqual(expectedEbsVolumes, opslayer.VolumeConfigurations) {
			return fmt.Errorf("Unnexpected VolumeConfiguration: %s", opslayer.VolumeConfigurations)
		}

		return nil
	}
}
func testAccCheckAWSS3BucketLambdaFunctionConfiguration(n, i, t string, events []string, filters *s3.KeyFilter) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, _ := s.RootModule().Resources[n]
		funcArn := s.RootModule().Resources[t].Primary.Attributes["arn"]
		conn := testAccProvider.Meta().(*AWSClient).s3conn

		err := resource.Retry(1*time.Minute, func() *resource.RetryError {
			out, err := conn.GetBucketNotificationConfiguration(&s3.GetBucketNotificationConfigurationRequest{
				Bucket: aws.String(rs.Primary.ID),
			})

			if err != nil {
				return resource.NonRetryableError(fmt.Errorf("GetBucketNotification error: %v", err))
			}

			eventSlice := sort.StringSlice(events)
			eventSlice.Sort()

			outputFunctions := out.LambdaFunctionConfigurations
			matched := false
			for _, outputFunc := range outputFunctions {
				if *outputFunc.Id == i {
					matched = true

					if *outputFunc.LambdaFunctionArn != funcArn {
						return resource.RetryableError(fmt.Errorf("bad lambda function arn, expected: %s, got %#v", funcArn, *outputFunc.LambdaFunctionArn))
					}

					if filters != nil {
						if !reflect.DeepEqual(filters, outputFunc.Filter.Key) {
							return resource.RetryableError(fmt.Errorf("bad notification filters, expected: %#v, got %#v", filters, outputFunc.Filter.Key))
						}
					} else {
						if outputFunc.Filter != nil {
							return resource.RetryableError(fmt.Errorf("bad notification filters, expected: nil, got %#v", outputFunc.Filter))
						}
					}

					outputEventSlice := sort.StringSlice(aws.StringValueSlice(outputFunc.Events))
					outputEventSlice.Sort()
					if !reflect.DeepEqual(eventSlice, outputEventSlice) {
						return resource.RetryableError(fmt.Errorf("bad notification events, expected: %#v, got %#v", events, outputEventSlice))
					}
				}
			}

			if !matched {
				return resource.RetryableError(fmt.Errorf("No match lambda function configurations: %#v", out))
			}

			return nil
		})

		return err
	}
}
Exemple #12
0
func (kin *Kinesumer) GetStreams() (streams []string, err error) {
	streams = make([]string, 0)
	err = kin.Kinesis.ListStreamsPages(&kinesis.ListStreamsInput{
		Limit: &kin.Options.ListStreamsLimit,
	}, func(sts *kinesis.ListStreamsOutput, _ bool) bool {
		streams = append(streams, aws.StringValueSlice(sts.StreamNames)...)
		return true
	})
	return
}
Exemple #13
0
// Marshal parses the response from the aws sdk into an awsm AutoScale Group
func (a *AutoScaleGroup) Marshal(autoscalegroup *autoscaling.Group, region string, subList *Subnets) {
	a.Name = aws.StringValue(autoscalegroup.AutoScalingGroupName)
	a.Class = GetTagValue("Class", autoscalegroup.Tags)
	a.HealthCheckType = aws.StringValue(autoscalegroup.HealthCheckType)
	a.HealthCheckGracePeriod = int(aws.Int64Value(autoscalegroup.HealthCheckGracePeriod))
	a.LaunchConfig = aws.StringValue(autoscalegroup.LaunchConfigurationName)
	a.LoadBalancers = aws.StringValueSlice(autoscalegroup.LoadBalancerNames)
	a.InstanceCount = len(autoscalegroup.Instances)
	a.DesiredCapacity = int(aws.Int64Value(autoscalegroup.DesiredCapacity))
	a.MinSize = int(aws.Int64Value(autoscalegroup.MinSize))
	a.MaxSize = int(aws.Int64Value(autoscalegroup.MaxSize))
	a.DefaultCooldown = int(aws.Int64Value(autoscalegroup.DefaultCooldown))
	a.AvailabilityZones = aws.StringValueSlice(autoscalegroup.AvailabilityZones)
	a.SubnetID = aws.StringValue(autoscalegroup.VPCZoneIdentifier)
	a.SubnetName = subList.GetSubnetName(a.SubnetID)
	a.VpcID = subList.GetVpcIDBySubnetID(a.SubnetID)
	a.VpcName = subList.GetVpcNameBySubnetID(a.SubnetID)
	a.Region = region
}
// Convert *cloudfront.ActiveTrustedSigners to a flatmap.Map type, which ensures
// it can probably be inserted into the schema.TypeMap type used by the
// active_trusted_signers attribute.
func flattenActiveTrustedSigners(ats *cloudfront.ActiveTrustedSigners) flatmap.Map {
	m := make(map[string]interface{})
	s := []interface{}{}
	m["enabled"] = *ats.Enabled

	for _, v := range ats.Items {
		signer := make(map[string]interface{})
		signer["aws_account_number"] = *v.AwsAccountNumber
		signer["key_pair_ids"] = aws.StringValueSlice(v.KeyPairIds.Items)
		s = append(s, signer)
	}
	m["items"] = s
	return flatmap.Flatten(m)
}
Exemple #15
0
func (r *RecordManager) ProcessFunc(instances []*ec2.Instance) error {
	if len(instances) == 0 {
		return errors.New("no instance to process")
	}

	publicIps := make([]*string, 0, len(instances))
	for _, instance := range instances {
		publicIps = append(publicIps, instance.PublicIpAddress)
	}

	r.log.Debug("Autoscaling operating IPs %s", aws.StringValueSlice(publicIps))

	return r.UpsertRecordSet(publicIps)
}
Exemple #16
0
// configChanged checks if function configuration differs from configuration stored in AWS Lambda
func (f *Function) configChanged(config *lambda.GetFunctionOutput) bool {
	type diffConfig struct {
		Description string
		Memory      int64
		Timeout     int64
		Role        string
		Handler     string
		VPC         vpc.VPC
	}

	localConfig, _ := json.Marshal(diffConfig{
		Description: f.Description,
		Memory:      f.Memory,
		Timeout:     f.Timeout,
		Role:        f.Role,
		Handler:     f.Handler,
		VPC: vpc.VPC{
			Subnets:        f.VPC.Subnets,
			SecurityGroups: f.VPC.SecurityGroups,
		},
	})

	remoteConfig, _ := json.Marshal(diffConfig{
		Description: *config.Configuration.Description,
		Memory:      *config.Configuration.MemorySize,
		Timeout:     *config.Configuration.Timeout,
		Role:        *config.Configuration.Role,
		Handler:     *config.Configuration.Handler,
		VPC: vpc.VPC{
			Subnets:        aws.StringValueSlice(config.Configuration.VpcConfig.SubnetIds),
			SecurityGroups: aws.StringValueSlice(config.Configuration.VpcConfig.SecurityGroupIds),
		},
	})

	return string(localConfig) != string(remoteConfig)
}
Exemple #17
0
// Marshal parses the response from the aws sdk into an awsm LaunchConfig
func (l *LaunchConfig) Marshal(config *autoscaling.LaunchConfiguration, region string, secGrpList *SecurityGroups, imgList *Images) {
	secGroupNames := secGrpList.GetSecurityGroupNames(aws.StringValueSlice(config.SecurityGroups))
	secGroupNamesSorted := sort.StringSlice(secGroupNames[0:])
	secGroupNamesSorted.Sort()

	l.Name = aws.StringValue(config.LaunchConfigurationName)
	l.ImageID = aws.StringValue(config.ImageId)
	l.ImageName = imgList.GetImageName(l.ImageID)
	l.InstanceType = aws.StringValue(config.InstanceType)
	l.KeyName = aws.StringValue(config.KeyName)
	l.CreationTime = aws.TimeValue(config.CreatedTime) // robots
	l.CreatedHuman = humanize.Time(l.CreationTime)     // humans
	l.EbsOptimized = aws.BoolValue(config.EbsOptimized)
	l.SecurityGroups = strings.Join(secGroupNamesSorted, ", ")
	l.Region = region

	for _, snapshot := range config.BlockDeviceMappings {
		l.SnapshotIDs = append(l.SnapshotIDs, *snapshot.Ebs.SnapshotId)
	}
}
Exemple #18
0
// Marshal parses the response from the aws sdk into an awsm LoadBalancerV2
func (l *LoadBalancerV2) Marshal(balancer *elbv2.LoadBalancer, region string, secGrpList *SecurityGroups) {

	secGroupNames := secGrpList.GetSecurityGroupNames(aws.StringValueSlice(balancer.SecurityGroups))
	secGroupNamesSorted := sort.StringSlice(secGroupNames[0:])
	secGroupNamesSorted.Sort()

	l.Name = aws.StringValue(balancer.LoadBalancerName)
	l.DNSName = aws.StringValue(balancer.DNSName)
	l.CreatedTime = aws.TimeValue(balancer.CreatedTime) // robots
	l.CreatedHuman = humanize.Time(l.CreatedTime)       // humans
	l.VpcID = aws.StringValue(balancer.VpcId)
	l.Type = aws.StringValue(balancer.Type)
	l.State = balancer.State.String()
	l.Scheme = aws.StringValue(balancer.Scheme)
	l.CanonicalHostedZoneID = aws.StringValue(balancer.CanonicalHostedZoneId)
	l.LoadBalancerArn = aws.StringValue(balancer.LoadBalancerArn)
	l.SecurityGroups = strings.Join(secGroupNamesSorted, ", ")
	//	l.AvailabilityZones = strings.Join(aws.StringValueSlice(balancer.AvailabilityZones), ", ") // TODO
	l.Region = region

}
func resourceAwsVPCEndpointRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn
	input := &ec2.DescribeVpcEndpointsInput{
		VpcEndpointIds: []*string{aws.String(d.Id())},
	}

	log.Printf("[DEBUG] Reading VPC Endpoint: %q", d.Id())
	output, err := conn.DescribeVpcEndpoints(input)

	if err != nil {
		ec2err, ok := err.(awserr.Error)
		if !ok {
			return fmt.Errorf("Error reading VPC Endpoint: %s", err.Error())
		}

		if ec2err.Code() == "InvalidVpcEndpointId.NotFound" {
			return nil
		}

		return fmt.Errorf("Error reading VPC Endpoint: %s", err.Error())
	}

	if len(output.VpcEndpoints) != 1 {
		return fmt.Errorf("There's no unique VPC Endpoint, but %d endpoints: %#v",
			len(output.VpcEndpoints), output.VpcEndpoints)
	}

	vpce := output.VpcEndpoints[0]

	d.Set("vpc_id", vpce.VpcId)
	d.Set("policy", normalizeJson(*vpce.PolicyDocument))
	d.Set("service_name", vpce.ServiceName)
	if err := d.Set("route_table_ids", aws.StringValueSlice(vpce.RouteTableIds)); err != nil {
		return err
	}

	return nil
}
func resourceAwsVPCEndpointRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn
	input := &ec2.DescribeVpcEndpointsInput{
		VpcEndpointIds: []*string{aws.String(d.Id())},
	}

	log.Printf("[DEBUG] Reading VPC Endpoint: %q", d.Id())
	output, err := conn.DescribeVpcEndpoints(input)

	if err != nil {
		ec2err, ok := err.(awserr.Error)
		if !ok {
			return fmt.Errorf("Error reading VPC Endpoint: %s", err.Error())
		}

		if ec2err.Code() == "InvalidVpcEndpointId.NotFound" {
			log.Printf("[WARN] VPC Endpoint (%s) not found, removing from state", d.Id())
			d.SetId("")
			return nil
		}

		return fmt.Errorf("Error reading VPC Endpoint: %s", err.Error())
	}

	if len(output.VpcEndpoints) != 1 {
		return fmt.Errorf("There's no unique VPC Endpoint, but %d endpoints: %#v",
			len(output.VpcEndpoints), output.VpcEndpoints)
	}

	vpce := output.VpcEndpoints[0]

	// A VPC Endpoint is associated with exactly one prefix list name (also called Service Name).
	// The prefix list ID can be used in security groups, so retrieve it to support that capability.
	prefixListServiceName := *vpce.ServiceName
	prefixListInput := &ec2.DescribePrefixListsInput{
		Filters: []*ec2.Filter{
			{Name: aws.String("prefix-list-name"), Values: []*string{aws.String(prefixListServiceName)}},
		},
	}

	log.Printf("[DEBUG] Reading VPC Endpoint prefix list: %s", prefixListServiceName)
	prefixListsOutput, err := conn.DescribePrefixLists(prefixListInput)

	if err != nil {
		_, ok := err.(awserr.Error)
		if !ok {
			return fmt.Errorf("Error reading VPC Endpoint prefix list: %s", err.Error())
		}
	}

	if len(prefixListsOutput.PrefixLists) != 1 {
		return fmt.Errorf("There are multiple prefix lists associated with the service name '%s'. Unexpected", prefixListServiceName)
	}

	policy, err := normalizeJsonString(*vpce.PolicyDocument)
	if err != nil {
		return errwrap.Wrapf("policy contains an invalid JSON: {{err}}", err)
	}

	d.Set("vpc_id", vpce.VpcId)
	d.Set("policy", policy)
	d.Set("service_name", vpce.ServiceName)
	if err := d.Set("route_table_ids", aws.StringValueSlice(vpce.RouteTableIds)); err != nil {
		return err
	}
	pl := prefixListsOutput.PrefixLists[0]
	d.Set("prefix_list_id", pl.PrefixListId)
	d.Set("cidr_blocks", aws.StringValueSlice(pl.Cidrs))

	return nil
}
func resourceAwsRDSClusterRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).rdsconn

	resp, err := conn.DescribeDBClusters(&rds.DescribeDBClustersInput{
		DBClusterIdentifier: aws.String(d.Id()),
	})

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			if "DBClusterNotFoundFault" == awsErr.Code() {
				d.SetId("")
				log.Printf("[DEBUG] RDS Cluster (%s) not found", d.Id())
				return nil
			}
		}
		log.Printf("[DEBUG] Error describing RDS Cluster (%s)", d.Id())
		return err
	}

	var dbc *rds.DBCluster
	for _, c := range resp.DBClusters {
		if *c.DBClusterIdentifier == d.Id() {
			dbc = c
		}
	}

	if dbc == nil {
		log.Printf("[WARN] RDS Cluster (%s) not found", d.Id())
		d.SetId("")
		return nil
	}

	if err := d.Set("availability_zones", aws.StringValueSlice(dbc.AvailabilityZones)); err != nil {
		return fmt.Errorf("[DEBUG] Error saving AvailabilityZones to state for RDS Cluster (%s): %s", d.Id(), err)
	}

	// Only set the DatabaseName if it is not nil. There is a known API bug where
	// RDS accepts a DatabaseName but does not return it, causing a perpetual
	// diff.
	//	See https://github.com/hashicorp/terraform/issues/4671 for backstory
	if dbc.DatabaseName != nil {
		d.Set("database_name", dbc.DatabaseName)
	}

	d.Set("db_subnet_group_name", dbc.DBSubnetGroup)
	d.Set("parameter_group_name", dbc.DBClusterParameterGroup)
	d.Set("db_cluster_parameter_group_name", dbc.DBClusterParameterGroup)
	d.Set("endpoint", dbc.Endpoint)
	d.Set("engine", dbc.Engine)
	d.Set("master_username", dbc.MasterUsername)
	d.Set("port", dbc.Port)
	d.Set("storage_encrypted", dbc.StorageEncrypted)
	d.Set("backup_retention_period", dbc.BackupRetentionPeriod)
	d.Set("preferred_backup_window", dbc.PreferredBackupWindow)
	d.Set("preferred_maintenance_window", dbc.PreferredMaintenanceWindow)

	var vpcg []string
	for _, g := range dbc.VpcSecurityGroups {
		vpcg = append(vpcg, *g.VpcSecurityGroupId)
	}
	if err := d.Set("vpc_security_group_ids", vpcg); err != nil {
		return fmt.Errorf("[DEBUG] Error saving VPC Security Group IDs to state for RDS Cluster (%s): %s", d.Id(), err)
	}

	var cm []string
	for _, m := range dbc.DBClusterMembers {
		cm = append(cm, *m.DBInstanceIdentifier)
	}
	if err := d.Set("cluster_members", cm); err != nil {
		return fmt.Errorf("[DEBUG] Error saving RDS Cluster Members to state for RDS Cluster (%s): %s", d.Id(), err)
	}

	return nil
}
Exemple #22
0
func GetContainerInstanceArnsForService(ecs_obj *ecs.ECS, cluster string, service string, local_container_instance_arn string, debug bool) ([]string, error) {
	// Fetch a task list based on the service name.
	list_tasks_params := &ecs.ListTasksInput{
		Cluster:     &cluster,
		ServiceName: &service,
	}
	list_tasks_resp, list_tasks_err := ecs_obj.ListTasks(list_tasks_params)

	if list_tasks_err != nil {
		return []string{}, fmt.Errorf("Cannot retrieve ECS task list: %s", FormatAwsError(list_tasks_err))
	}

	if len(list_tasks_resp.TaskArns) <= 0 {
		return []string{}, fmt.Errorf("No ECS tasks found with specified filter - cluster: ", cluster, ", service:", service)
	}

	// Describe the tasks retrieved above.
	describe_tasks_params := &ecs.DescribeTasksInput{
		Cluster: &cluster,
		Tasks:   list_tasks_resp.TaskArns,
	}
	describe_tasks_resp, describe_tasks_err := ecs_obj.DescribeTasks(describe_tasks_params)

	if describe_tasks_err != nil {
		return []string{}, fmt.Errorf("Cannot retrieve ECS task details:", FormatAwsError(describe_tasks_err))
	}

	if len(describe_tasks_resp.Tasks) <= 0 {
		return []string{}, fmt.Errorf("No ECS task details found with specified filter - tasks:", strings.Join(aws.StringValueSlice(list_tasks_resp.TaskArns), ", "))
	}

	var result []string
	for _, value := range describe_tasks_resp.Tasks {
		if *value.LastStatus == "RUNNING" && *value.ContainerInstanceArn != local_container_instance_arn {
			result = append(result, *value.ContainerInstanceArn)
		} else {
			if debug == true {
				fmt.Println(*value.ContainerInstanceArn, "is not in a RUNNING state, or is this instance (we dont return ourself). Excluded from results.")
			}
		}
	}

	if len(result) == 0 {
		return []string{}, fmt.Errorf("No ECS task results found in RUNNING state, no ECS container instances to return.")
	}
	return result, nil
}
func testAccCheckAWSOpsworksUpdateAppAttributes(
	opsapp *opsworks.App) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		if *opsapp.Type != "rails" {
			return fmt.Errorf("Unnexpected type: %s", *opsapp.Type)
		}

		if !*opsapp.EnableSsl {
			return fmt.Errorf("Unexpected enable ssl: %t", *opsapp.EnableSsl)
		}

		if *opsapp.SslConfiguration.Certificate != "-----BEGIN CERTIFICATE-----\nMIIBkDCB+gIJALoScFD0sJq3MA0GCSqGSIb3DQEBBQUAMA0xCzAJBgNVBAYTAkRF\nMB4XDTE1MTIxOTIwMzU1MVoXDTE2MDExODIwMzU1MVowDTELMAkGA1UEBhMCREUw\ngZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKKQKbTTH/Julz16xY7ArYlzJYCP\nedTCx1bopuryCx/+d1gC94MtRdlPSpQl8mfc9iBdtXbJppp73Qh/DzLzO9Ns25xZ\n+kUQMhbIyLsaCBzuEGLgAaVdGpNvRBw++UoYtd0U7QczFAreTGLH8n8+FIzuI5Mc\n+MJ1TKbbt5gFfRSzAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEALARo96wCDmaHKCaX\nS0IGLGnZCfiIUfCmBxOXBSJxDBwter95QHR0dMGxYIujee5n4vvavpVsqZnfMC3I\nOZWPlwiUJbNIpK+04Bg2vd5m/NMMrvi75RfmyeMtSfq/NrIX2Q3+nyWI7DLq7yZI\nV/YEvOqdAiy5NEWBztHx8HvB9G4=\n-----END CERTIFICATE-----" {
			return fmt.Errorf("Unexpected ssl configuration certificate: %s", *opsapp.SslConfiguration.Certificate)
		}

		if *opsapp.SslConfiguration.PrivateKey != "-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQCikCm00x/ybpc9esWOwK2JcyWAj3nUwsdW6Kbq8gsf/ndYAveD\nLUXZT0qUJfJn3PYgXbV2yaaae90Ifw8y8zvTbNucWfpFEDIWyMi7Gggc7hBi4AGl\nXRqTb0QcPvlKGLXdFO0HMxQK3kxix/J/PhSM7iOTHPjCdUym27eYBX0UswIDAQAB\nAoGBAIYcrvuqDboguI8U4TUjCkfSAgds1pLLWk79wu8jXkA329d1IyNKT0y3WIye\nPbyoEzmidZmZROQ/+ZsPz8c12Y0DrX73WSVzKNyJeP7XMk9HSzA1D9RX0U0S+5Kh\nFAMc2NEVVFIfQtVtoVmHdKDpnRYtOCHLW9rRpvqOOjd4mYk5AkEAzeiFr1mtlnsa\n67shMxzDaOTAFMchRz6G7aSovvCztxcB63ulFI/w9OTUMdTQ7ff7pet+lVihLc2W\nefIL0HvsjQJBAMocNTKaR/TnsV5GSk2kPAdR+zFP5sQy8sfMy0lEXTylc7zN4ajX\nMeHVoxp+GZgpfDcZ3ya808H1umyXh+xA1j8CQE9x9ZKQYT98RAjL7KVR5btk9w+N\nPTPF1j1+mHUDXfO4ds8qp6jlWKzEVXLcj7ghRADiebaZuaZ4eiSW1SQdjEkCQQC4\nwDhQ3X9RfEpCp3ZcqvjEqEg6t5N3XitYQPjDLN8eBRBbUsgpEy3iBuxl10eGNMX7\niIbYXlwkPYAArDPv3wT5AkAwp4vym+YKmDqh6gseKfRDuJqRiW9yD5A8VGr/w88k\n5rkuduVGP7tK3uIp00Its3aEyKF8mLGWYszVGeeLxAMH\n-----END RSA PRIVATE KEY-----" {
			return fmt.Errorf("Unexpected ssl configuration private key: %s", *opsapp.SslConfiguration.PrivateKey)
		}

		expectedAttrs := map[string]*string{
			"DocumentRoot":        aws.String("root"),
			"RailsEnv":            aws.String("staging"),
			"AutoBundleOnDeploy":  aws.String("true"),
			"AwsFlowRubySettings": nil,
		}

		if !reflect.DeepEqual(expectedAttrs, opsapp.Attributes) {
			return fmt.Errorf("Unnexpected Attributes: %v", aws.StringValueMap(opsapp.Attributes))
		}

		expectedAppSource := &opsworks.Source{
			Type:     aws.String("git"),
			Revision: aws.String("master"),
			Url:      aws.String("https://github.com/aws/example.git"),
		}

		if !reflect.DeepEqual(expectedAppSource, opsapp.AppSource) {
			return fmt.Errorf("Unnexpected appsource: %s", opsapp.AppSource)
		}

		expectedEnv := []*opsworks.EnvironmentVariable{
			&opsworks.EnvironmentVariable{
				Key:    aws.String("key2"),
				Value:  aws.String("*****FILTERED*****"),
				Secure: aws.Bool(true),
			},
			&opsworks.EnvironmentVariable{
				Key:    aws.String("key1"),
				Value:  aws.String("value1"),
				Secure: aws.Bool(false),
			},
		}

		if !reflect.DeepEqual(expectedEnv, opsapp.Environment) {
			return fmt.Errorf("Unnexpected environment: %s", opsapp.Environment)
		}

		expectedDomains := []*string{
			aws.String("example.com"),
			aws.String("sub.example.com"),
		}

		if !reflect.DeepEqual(expectedDomains, opsapp.Domains) {
			return fmt.Errorf("Unnexpected Daomins : %v", aws.StringValueSlice(opsapp.Domains))
		}

		return nil
	}
}
func TestConvertToTaskDefinition(t *testing.T) {
	name := "mysql"
	cpu := int64(10)
	command := "cmd"
	essential := false
	hostname := "foobarbaz"
	image := "testimage"
	links := []string{"container1"}
	memory := int64(100) // 1 MiB = 1048576B
	privileged := true
	readOnly := true
	restart := "no"
	securityOpts := []string{"label:type:test_virt"}
	user := "******"
	workingDir := "/var"

	serviceConfig := &libcompose.ServiceConfig{
		CpuShares:   cpu,
		Command:     libcompose.NewCommand(command),
		Hostname:    hostname,
		Image:       image,
		Links:       libcompose.NewMaporColonSlice(links),
		MemLimit:    int64(1048576) * memory,
		Privileged:  privileged,
		ReadOnly:    readOnly,
		Restart:     restart,
		SecurityOpt: securityOpts,
		User:        user,
		WorkingDir:  workingDir,
	}

	// convert
	taskDefinition := convertToTaskDefinitionInTest(t, name, serviceConfig)
	containerDef := *taskDefinition.ContainerDefinitions[0]

	// verify
	if name != aws.StringValue(containerDef.Name) {
		t.Errorf("Expected Name [%s] But was [%s]", name, aws.StringValue(containerDef.Name))
	}
	if cpu != aws.Int64Value(containerDef.Cpu) {
		t.Errorf("Expected cpu [%s] But was [%s]", cpu, aws.Int64Value(containerDef.Cpu))
	}
	if len(containerDef.Command) != 1 || command != aws.StringValue(containerDef.Command[0]) {
		t.Errorf("Expected command [%s] But was [%v]", command, containerDef.Command)
	}
	if essential != aws.BoolValue(containerDef.Essential) {
		t.Errorf("Expected essential [%s] But was [%s]", essential, aws.BoolValue(containerDef.Essential))
	}
	if !reflect.DeepEqual(securityOpts, aws.StringValueSlice(containerDef.DockerSecurityOptions)) {
		t.Errorf("Expected securityOpt [%v] But was [%v]", securityOpts, aws.StringValueSlice(containerDef.DockerSecurityOptions))
	}
	if hostname != aws.StringValue(containerDef.Hostname) {
		t.Errorf("Expected hostname [%s] But was [%s]", hostname, aws.StringValue(containerDef.Hostname))
	}
	if image != aws.StringValue(containerDef.Image) {
		t.Errorf("Expected Image [%s] But was [%s]", image, aws.StringValue(containerDef.Image))
	}
	if !reflect.DeepEqual(links, aws.StringValueSlice(containerDef.Links)) {
		t.Errorf("Expected links [%v] But was [%v]", links, aws.StringValueSlice(containerDef.Links))
	}
	if memory != aws.Int64Value(containerDef.Memory) {
		t.Errorf("Expected memory [%s] But was [%s]", memory, aws.Int64Value(containerDef.Memory))
	}
	if privileged != aws.BoolValue(containerDef.Privileged) {
		t.Errorf("Expected privileged [%s] But was [%s]", privileged, aws.BoolValue(containerDef.Privileged))
	}
	if readOnly != aws.BoolValue(containerDef.ReadonlyRootFilesystem) {
		t.Errorf("Expected ReadonlyRootFilesystem [%s] But was [%s]", readOnly, aws.BoolValue(containerDef.ReadonlyRootFilesystem))
	}
	if user != aws.StringValue(containerDef.User) {
		t.Errorf("Expected user [%s] But was [%s]", user, aws.StringValue(containerDef.User))
	}
	if workingDir != aws.StringValue(containerDef.WorkingDirectory) {
		t.Errorf("Expected WorkingDirectory [%s] But was [%s]", workingDir, aws.StringValue(containerDef.WorkingDirectory))
	}
}
func TestConvertToTaskDefinition(t *testing.T) {
	name := "mysql"
	cpu := int64(131072) // 128 * 1024
	command := "cmd"
	hostname := "foobarbaz"
	image := "testimage"
	links := []string{"container1"}
	memory := int64(131072) // 128 GiB = 131072 MiB
	privileged := true
	readOnly := true
	securityOpts := []string{"label:type:test_virt"}
	user := "******"
	workingDir := "/var"

	serviceConfig := &config.ServiceConfig{
		CPUShares:   yaml.StringorInt(cpu),
		Command:     []string{command},
		Hostname:    hostname,
		Image:       image,
		Links:       links,
		MemLimit:    yaml.StringorInt(int64(1048576) * memory), //1 MiB = 1048576B
		Privileged:  privileged,
		ReadOnly:    readOnly,
		SecurityOpt: securityOpts,
		User:        user,
		WorkingDir:  workingDir,
	}

	// convert
	taskDefinition := convertToTaskDefinitionInTest(t, name, serviceConfig)
	containerDef := *taskDefinition.ContainerDefinitions[0]

	// verify
	if name != aws.StringValue(containerDef.Name) {
		t.Errorf("Expected Name [%s] But was [%s]", name, aws.StringValue(containerDef.Name))
	}
	if cpu != aws.Int64Value(containerDef.Cpu) {
		t.Errorf("Expected cpu [%s] But was [%s]", cpu, aws.Int64Value(containerDef.Cpu))
	}
	if len(containerDef.Command) != 1 || command != aws.StringValue(containerDef.Command[0]) {
		t.Errorf("Expected command [%s] But was [%v]", command, containerDef.Command)
	}
	if !reflect.DeepEqual(securityOpts, aws.StringValueSlice(containerDef.DockerSecurityOptions)) {
		t.Errorf("Expected securityOpt [%v] But was [%v]", securityOpts, aws.StringValueSlice(containerDef.DockerSecurityOptions))
	}
	if hostname != aws.StringValue(containerDef.Hostname) {
		t.Errorf("Expected hostname [%s] But was [%s]", hostname, aws.StringValue(containerDef.Hostname))
	}
	if image != aws.StringValue(containerDef.Image) {
		t.Errorf("Expected Image [%s] But was [%s]", image, aws.StringValue(containerDef.Image))
	}
	if !reflect.DeepEqual(links, aws.StringValueSlice(containerDef.Links)) {
		t.Errorf("Expected links [%v] But was [%v]", links, aws.StringValueSlice(containerDef.Links))
	}
	if memory != aws.Int64Value(containerDef.Memory) {
		t.Errorf("Expected memory [%s] But was [%s]", memory, aws.Int64Value(containerDef.Memory))
	}
	if privileged != aws.BoolValue(containerDef.Privileged) {
		t.Errorf("Expected privileged [%s] But was [%s]", privileged, aws.BoolValue(containerDef.Privileged))
	}
	if readOnly != aws.BoolValue(containerDef.ReadonlyRootFilesystem) {
		t.Errorf("Expected ReadonlyRootFilesystem [%s] But was [%s]", readOnly, aws.BoolValue(containerDef.ReadonlyRootFilesystem))
	}
	if user != aws.StringValue(containerDef.User) {
		t.Errorf("Expected user [%s] But was [%s]", user, aws.StringValue(containerDef.User))
	}
	if workingDir != aws.StringValue(containerDef.WorkingDirectory) {
		t.Errorf("Expected WorkingDirectory [%s] But was [%s]", workingDir, aws.StringValue(containerDef.WorkingDirectory))
	}
}