func testAccCheckAWSSecurityGroupRuleAttributes(group *ec2.SecurityGroup, ruleType string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		p := &ec2.IPPermission{
			FromPort:   aws.Long(80),
			ToPort:     aws.Long(8000),
			IPProtocol: aws.String("tcp"),
			IPRanges:   []*ec2.IPRange{&ec2.IPRange{CIDRIP: aws.String("10.0.0.0/8")}},
		}
		var rules []*ec2.IPPermission
		if ruleType == "ingress" {
			rules = group.IPPermissions
		} else {
			rules = group.IPPermissionsEgress
		}

		if len(rules) == 0 {
			return fmt.Errorf("No IPPerms")
		}

		// Compare our ingress
		if !reflect.DeepEqual(rules[0], p) {
			return fmt.Errorf(
				"Got:\n\n%#v\n\nExpected:\n\n%#v\n",
				rules[0],
				p)
		}

		return nil
	}
}
예제 #2
0
func ExampleDirectConnect_AllocatePrivateVirtualInterface() {
	svc := directconnect.New(nil)

	params := &directconnect.AllocatePrivateVirtualInterfaceInput{
		ConnectionID: aws.String("ConnectionId"), // Required
		NewPrivateVirtualInterfaceAllocation: &directconnect.NewPrivateVirtualInterfaceAllocation{ // Required
			ASN:                  aws.Long(1),                        // Required
			VLAN:                 aws.Long(1),                        // Required
			VirtualInterfaceName: aws.String("VirtualInterfaceName"), // Required
			AmazonAddress:        aws.String("AmazonAddress"),
			AuthKey:              aws.String("BGPAuthKey"),
			CustomerAddress:      aws.String("CustomerAddress"),
		},
		OwnerAccount: aws.String("OwnerAccount"), // Required
	}
	resp, err := svc.AllocatePrivateVirtualInterface(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
func resourceAwsAutoscalingGroupDrain(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).autoscalingconn

	// First, set the capacity to zero so the group will drain
	log.Printf("[DEBUG] Reducing autoscaling group capacity to zero")
	opts := autoscaling.UpdateAutoScalingGroupInput{
		AutoScalingGroupName: aws.String(d.Id()),
		DesiredCapacity:      aws.Long(0),
		MinSize:              aws.Long(0),
		MaxSize:              aws.Long(0),
	}
	if _, err := conn.UpdateAutoScalingGroup(&opts); err != nil {
		return fmt.Errorf("Error setting capacity to zero to drain: %s", err)
	}

	// Next, wait for the autoscale group to drain
	log.Printf("[DEBUG] Waiting for group to have zero instances")
	return resource.Retry(10*time.Minute, func() error {
		g, err := getAwsAutoscalingGroup(d, meta)
		if err != nil {
			return resource.RetryError{Err: err}
		}
		if g == nil {
			return nil
		}

		if len(g.Instances) == 0 {
			return nil
		}

		return fmt.Errorf("group still has %d instances", len(g.Instances))
	})
}
예제 #4
0
func ExampleCloudWatchLogs_GetLogEvents() {
	svc := cloudwatchlogs.New(nil)

	params := &cloudwatchlogs.GetLogEventsInput{
		LogGroupName:  aws.String("LogGroupName"),  // Required
		LogStreamName: aws.String("LogStreamName"), // Required
		EndTime:       aws.Long(1),
		Limit:         aws.Long(1),
		NextToken:     aws.String("NextToken"),
		StartFromHead: aws.Boolean(true),
		StartTime:     aws.Long(1),
	}
	resp, err := svc.GetLogEvents(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
예제 #5
0
파일: sqs.go 프로젝트: toomore/simpleaws
// Receive to receive a queue message.
func (s SQS) Receive(Visibility int64) (*sqs.ReceiveMessageOutput, error) {
	return s.sqs.ReceiveMessage(&sqs.ReceiveMessageInput{
		MaxNumberOfMessages: aws.Long(10),
		QueueURL:            s.url,
		VisibilityTimeout:   aws.Long(Visibility),
	})
}
예제 #6
0
func ExampleStorageGateway_CreateTapes() {
	svc := storagegateway.New(nil)

	params := &storagegateway.CreateTapesInput{
		ClientToken:       aws.String("ClientToken"),       // Required
		GatewayARN:        aws.String("GatewayARN"),        // Required
		NumTapesToCreate:  aws.Long(1),                     // Required
		TapeBarcodePrefix: aws.String("TapeBarcodePrefix"), // Required
		TapeSizeInBytes:   aws.Long(1),                     // Required
	}
	resp, err := svc.CreateTapes(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
예제 #7
0
func ExampleStorageGateway_UpdateSnapshotSchedule() {
	svc := storagegateway.New(nil)

	params := &storagegateway.UpdateSnapshotScheduleInput{
		RecurrenceInHours: aws.Long(1),             // Required
		StartAt:           aws.Long(1),             // Required
		VolumeARN:         aws.String("VolumeARN"), // Required
		Description:       aws.String("Description"),
	}
	resp, err := svc.UpdateSnapshotSchedule(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
func resourceAwsElasticacheClusterCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).elasticacheconn

	clusterId := d.Get("cluster_id").(string)
	nodeType := d.Get("node_type").(string)           // e.g) cache.m1.small
	numNodes := int64(d.Get("num_cache_nodes").(int)) // 2
	engine := d.Get("engine").(string)                // memcached
	engineVersion := d.Get("engine_version").(string) // 1.4.14
	port := int64(d.Get("port").(int))                // e.g) 11211
	subnetGroupName := d.Get("subnet_group_name").(string)
	securityNameSet := d.Get("security_group_names").(*schema.Set)
	securityIdSet := d.Get("security_group_ids").(*schema.Set)

	securityNames := expandStringList(securityNameSet.List())
	securityIds := expandStringList(securityIdSet.List())

	tags := tagsFromMapEC(d.Get("tags").(map[string]interface{}))
	req := &elasticache.CreateCacheClusterInput{
		CacheClusterID:          aws.String(clusterId),
		CacheNodeType:           aws.String(nodeType),
		NumCacheNodes:           aws.Long(numNodes),
		Engine:                  aws.String(engine),
		EngineVersion:           aws.String(engineVersion),
		Port:                    aws.Long(port),
		CacheSubnetGroupName:    aws.String(subnetGroupName),
		CacheSecurityGroupNames: securityNames,
		SecurityGroupIDs:        securityIds,
		Tags:                    tags,
	}

	// parameter groups are optional and can be defaulted by AWS
	if v, ok := d.GetOk("parameter_group_name"); ok {
		req.CacheParameterGroupName = aws.String(v.(string))
	}

	_, err := conn.CreateCacheCluster(req)
	if err != nil {
		return fmt.Errorf("Error creating Elasticache: %s", err)
	}

	pending := []string{"creating"}
	stateConf := &resource.StateChangeConf{
		Pending:    pending,
		Target:     "available",
		Refresh:    CacheClusterStateRefreshFunc(conn, d.Id(), "available", pending),
		Timeout:    10 * time.Minute,
		Delay:      10 * time.Second,
		MinTimeout: 3 * time.Second,
	}

	log.Printf("[DEBUG] Waiting for state to become available: %v", d.Id())
	_, sterr := stateConf.WaitForState()
	if sterr != nil {
		return fmt.Errorf("Error waiting for elasticache (%s) to be created: %s", d.Id(), sterr)
	}

	d.SetId(clusterId)

	return resourceAwsElasticacheClusterRead(d, meta)
}
예제 #9
0
func ExampleStorageGateway_UpdateMaintenanceStartTime() {
	svc := storagegateway.New(nil)

	params := &storagegateway.UpdateMaintenanceStartTimeInput{
		DayOfWeek:    aws.Long(1),              // Required
		GatewayARN:   aws.String("GatewayARN"), // Required
		HourOfDay:    aws.Long(1),              // Required
		MinuteOfHour: aws.Long(1),              // Required
	}
	resp, err := svc.UpdateMaintenanceStartTime(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
func testAccCheckAWSSecurityGroupAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		p := &ec2.IPPermission{
			FromPort:   aws.Long(80),
			ToPort:     aws.Long(8000),
			IPProtocol: aws.String("tcp"),
			IPRanges:   []*ec2.IPRange{&ec2.IPRange{CIDRIP: aws.String("10.0.0.0/8")}},
		}

		if *group.GroupName != "terraform_acceptance_test_example" {
			return fmt.Errorf("Bad name: %s", *group.GroupName)
		}

		if *group.Description != "Used in the terraform acceptance tests" {
			return fmt.Errorf("Bad description: %s", *group.Description)
		}

		if len(group.IPPermissions) == 0 {
			return fmt.Errorf("No IPPerms")
		}

		// Compare our ingress
		if !reflect.DeepEqual(group.IPPermissions[0], p) {
			return fmt.Errorf(
				"Got:\n\n%#v\n\nExpected:\n\n%#v\n",
				group.IPPermissions[0],
				p)
		}

		return nil
	}
}
예제 #11
0
func TestexpandListeners(t *testing.T) {
	expanded := []interface{}{
		map[string]interface{}{
			"instance_port":     8000,
			"lb_port":           80,
			"instance_protocol": "http",
			"lb_protocol":       "http",
		},
	}
	listeners, err := expandListeners(expanded)
	if err != nil {
		t.Fatalf("bad: %#v", err)
	}

	expected := &elb.Listener{
		InstancePort:     aws.Long(int64(8000)),
		LoadBalancerPort: aws.Long(int64(80)),
		InstanceProtocol: aws.String("http"),
		Protocol:         aws.String("http"),
	}

	if !reflect.DeepEqual(listeners[0], expected) {
		t.Fatalf(
			"Got:\n\n%#v\n\nExpected:\n\n%#v\n",
			listeners[0],
			expected)
	}

}
예제 #12
0
func ExampleELB_ConfigureHealthCheck() {
	svc := elb.New(nil)

	params := &elb.ConfigureHealthCheckInput{
		HealthCheck: &elb.HealthCheck{ // Required
			HealthyThreshold:   aws.Long(1),                     // Required
			Interval:           aws.Long(1),                     // Required
			Target:             aws.String("HealthCheckTarget"), // Required
			Timeout:            aws.Long(1),                     // Required
			UnhealthyThreshold: aws.Long(1),                     // Required
		},
		LoadBalancerName: aws.String("AccessPointName"), // Required
	}
	resp, err := svc.ConfigureHealthCheck(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
예제 #13
0
func ExampleElastiCache_DescribeEvents() {
	svc := elasticache.New(nil)

	params := &elasticache.DescribeEventsInput{
		Duration:         aws.Long(1),
		EndTime:          aws.Time(time.Now()),
		Marker:           aws.String("String"),
		MaxRecords:       aws.Long(1),
		SourceIdentifier: aws.String("String"),
		SourceType:       aws.String("SourceType"),
		StartTime:        aws.Time(time.Now()),
	}
	resp, err := svc.DescribeEvents(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
func resourceAwsLBCookieStickinessPolicyCreate(d *schema.ResourceData, meta interface{}) error {
	elbconn := meta.(*AWSClient).elbconn

	// Provision the LBStickinessPolicy
	lbspOpts := &elb.CreateLBCookieStickinessPolicyInput{
		CookieExpirationPeriod: aws.Long(int64(d.Get("cookie_expiration_period").(int))),
		LoadBalancerName:       aws.String(d.Get("load_balancer").(string)),
		PolicyName:             aws.String(d.Get("name").(string)),
	}

	if _, err := elbconn.CreateLBCookieStickinessPolicy(lbspOpts); err != nil {
		return fmt.Errorf("Error creating LBCookieStickinessPolicy: %s", err)
	}

	setLoadBalancerOpts := &elb.SetLoadBalancerPoliciesOfListenerInput{
		LoadBalancerName: aws.String(d.Get("load_balancer").(string)),
		LoadBalancerPort: aws.Long(int64(d.Get("lb_port").(int))),
		PolicyNames:      []*string{aws.String(d.Get("name").(string))},
	}

	if _, err := elbconn.SetLoadBalancerPoliciesOfListener(setLoadBalancerOpts); err != nil {
		return fmt.Errorf("Error setting LBCookieStickinessPolicy: %s", err)
	}

	d.SetId(fmt.Sprintf("%s:%d:%s",
		*lbspOpts.LoadBalancerName,
		*setLoadBalancerOpts.LoadBalancerPort,
		*lbspOpts.PolicyName))
	return nil
}
예제 #15
0
func ExampleRoute53_UpdateHealthCheck() {
	svc := route53.New(nil)

	params := &route53.UpdateHealthCheckInput{
		HealthCheckID:            aws.String("HealthCheckId"), // Required
		FailureThreshold:         aws.Long(1),
		FullyQualifiedDomainName: aws.String("FullyQualifiedDomainName"),
		HealthCheckVersion:       aws.Long(1),
		IPAddress:                aws.String("IPAddress"),
		Port:                     aws.Long(1),
		ResourcePath:             aws.String("ResourcePath"),
		SearchString:             aws.String("SearchString"),
	}
	resp, err := svc.UpdateHealthCheck(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, The SDK should alwsy return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
예제 #16
0
func ExampleCognitoSync_ListRecords() {
	svc := cognitosync.New(nil)

	params := &cognitosync.ListRecordsInput{
		DatasetName:      aws.String("DatasetName"),    // Required
		IdentityID:       aws.String("IdentityId"),     // Required
		IdentityPoolID:   aws.String("IdentityPoolId"), // Required
		LastSyncCount:    aws.Long(1),
		MaxResults:       aws.Long(1),
		NextToken:        aws.String("String"),
		SyncSessionToken: aws.String("SyncSessionToken"),
	}
	resp, err := svc.ListRecords(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
예제 #17
0
func ExampleCloudSearch_UpdateScalingParameters() {
	svc := cloudsearch.New(nil)

	params := &cloudsearch.UpdateScalingParametersInput{
		DomainName: aws.String("DomainName"), // Required
		ScalingParameters: &cloudsearch.ScalingParameters{ // Required
			DesiredInstanceType:     aws.String("PartitionInstanceType"),
			DesiredPartitionCount:   aws.Long(1),
			DesiredReplicationCount: aws.Long(1),
		},
	}
	resp, err := svc.UpdateScalingParameters(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
예제 #18
0
func ExampleStorageGateway_UpdateBandwidthRateLimit() {
	svc := storagegateway.New(nil)

	params := &storagegateway.UpdateBandwidthRateLimitInput{
		GatewayARN:                           aws.String("GatewayARN"), // Required
		AverageDownloadRateLimitInBitsPerSec: aws.Long(1),
		AverageUploadRateLimitInBitsPerSec:   aws.Long(1),
	}
	resp, err := svc.UpdateBandwidthRateLimit(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
예제 #19
0
func ExampleLambda_UpdateFunctionConfiguration() {
	svc := lambda.New(nil)

	params := &lambda.UpdateFunctionConfigurationInput{
		FunctionName: aws.String("FunctionName"), // Required
		Description:  aws.String("Description"),
		Handler:      aws.String("Handler"),
		MemorySize:   aws.Long(1),
		Role:         aws.String("RoleArn"),
		Timeout:      aws.Long(1),
	}
	resp, err := svc.UpdateFunctionConfiguration(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
예제 #20
0
func TestflattenHealthCheck(t *testing.T) {
	cases := []struct {
		Input  *elb.HealthCheck
		Output []map[string]interface{}
	}{
		{
			Input: &elb.HealthCheck{
				UnhealthyThreshold: aws.Long(int64(10)),
				HealthyThreshold:   aws.Long(int64(10)),
				Target:             aws.String("HTTP:80/"),
				Timeout:            aws.Long(int64(30)),
				Interval:           aws.Long(int64(30)),
			},
			Output: []map[string]interface{}{
				map[string]interface{}{
					"unhealthy_threshold": int64(10),
					"healthy_threshold":   int64(10),
					"target":              "HTTP:80/",
					"timeout":             int64(30),
					"interval":            int64(30),
				},
			},
		},
	}

	for _, tc := range cases {
		output := flattenHealthCheck(tc.Input)
		if !reflect.DeepEqual(output, tc.Output) {
			t.Fatalf("Got:\n\n%#v\n\nExpected:\n\n%#v", output, tc.Output)
		}
	}
}
예제 #21
0
func ExampleAutoScaling_PutScheduledUpdateGroupAction() {
	svc := autoscaling.New(nil)

	params := &autoscaling.PutScheduledUpdateGroupActionInput{
		AutoScalingGroupName: aws.String("ResourceName"),       // Required
		ScheduledActionName:  aws.String("XmlStringMaxLen255"), // Required
		DesiredCapacity:      aws.Long(1),
		EndTime:              aws.Time(time.Now()),
		MaxSize:              aws.Long(1),
		MinSize:              aws.Long(1),
		Recurrence:           aws.String("XmlStringMaxLen255"),
		StartTime:            aws.Time(time.Now()),
		Time:                 aws.Time(time.Now()),
	}
	resp, err := svc.PutScheduledUpdateGroupAction(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
예제 #22
0
func ExampleAutoScaling_PutScalingPolicy() {
	svc := autoscaling.New(nil)

	params := &autoscaling.PutScalingPolicyInput{
		AdjustmentType:       aws.String("XmlStringMaxLen255"), // Required
		AutoScalingGroupName: aws.String("ResourceName"),       // Required
		PolicyName:           aws.String("XmlStringMaxLen255"), // Required
		Cooldown:             aws.Long(1),
		MinAdjustmentStep:    aws.Long(1),
		ScalingAdjustment:    aws.Long(1),
	}
	resp, err := svc.PutScalingPolicy(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
예제 #23
0
func ExampleAutoScaling_CreateAutoScalingGroup() {
	svc := autoscaling.New(nil)

	params := &autoscaling.CreateAutoScalingGroupInput{
		AutoScalingGroupName: aws.String("XmlStringMaxLen255"), // Required
		MaxSize:              aws.Long(1),                      // Required
		MinSize:              aws.Long(1),                      // Required
		AvailabilityZones: []*string{
			aws.String("XmlStringMaxLen255"), // Required
			// More values...
		},
		DefaultCooldown:         aws.Long(1),
		DesiredCapacity:         aws.Long(1),
		HealthCheckGracePeriod:  aws.Long(1),
		HealthCheckType:         aws.String("XmlStringMaxLen32"),
		InstanceID:              aws.String("XmlStringMaxLen16"),
		LaunchConfigurationName: aws.String("ResourceName"),
		LoadBalancerNames: []*string{
			aws.String("XmlStringMaxLen255"), // Required
			// More values...
		},
		PlacementGroup: aws.String("XmlStringMaxLen255"),
		Tags: []*autoscaling.Tag{
			{ // Required
				Key:               aws.String("TagKey"), // Required
				PropagateAtLaunch: aws.Boolean(true),
				ResourceID:        aws.String("XmlString"),
				ResourceType:      aws.String("XmlString"),
				Value:             aws.String("TagValue"),
			},
			// More values...
		},
		TerminationPolicies: []*string{
			aws.String("XmlStringMaxLen1600"), // Required
			// More values...
		},
		VPCZoneIdentifier: aws.String("XmlStringMaxLen255"),
	}
	resp, err := svc.CreateAutoScalingGroup(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
예제 #24
0
func resourceAwsEbsVolumeCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn

	request := &ec2.CreateVolumeInput{
		AvailabilityZone: aws.String(d.Get("availability_zone").(string)),
	}
	if value, ok := d.GetOk("encrypted"); ok {
		request.Encrypted = aws.Boolean(value.(bool))
	}
	if value, ok := d.GetOk("iops"); ok {
		request.IOPS = aws.Long(int64(value.(int)))
	}
	if value, ok := d.GetOk("kms_key_id"); ok {
		request.KMSKeyID = aws.String(value.(string))
	}
	if value, ok := d.GetOk("size"); ok {
		request.Size = aws.Long(int64(value.(int)))
	}
	if value, ok := d.GetOk("snapshot_id"); ok {
		request.SnapshotID = aws.String(value.(string))
	}
	if value, ok := d.GetOk("type"); ok {
		request.VolumeType = aws.String(value.(string))
	}

	result, err := conn.CreateVolume(request)
	if err != nil {
		return fmt.Errorf("Error creating EC2 volume: %s", err)
	}

	log.Printf(
		"[DEBUG] Waiting for Volume (%s) to become available",
		d.Id())

	stateConf := &resource.StateChangeConf{
		Pending:    []string{"creating"},
		Target:     "available",
		Refresh:    volumeStateRefreshFunc(conn, *result.VolumeID),
		Timeout:    5 * time.Minute,
		Delay:      10 * time.Second,
		MinTimeout: 3 * time.Second,
	}

	_, err = stateConf.WaitForState()
	if err != nil {
		return fmt.Errorf(
			"Error waiting for Volume (%s) to become available: %s",
			*result.VolumeID, err)
	}

	d.SetId(*result.VolumeID)

	if _, ok := d.GetOk("tags"); ok {
		setTags(conn, d)
	}

	return readVolume(d, result)
}
func expandIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup) *ec2.IPPermission {
	var perm ec2.IPPermission

	perm.FromPort = aws.Long(int64(d.Get("from_port").(int)))
	perm.ToPort = aws.Long(int64(d.Get("to_port").(int)))
	perm.IPProtocol = aws.String(d.Get("protocol").(string))

	// build a group map that behaves like a set
	groups := make(map[string]bool)
	if raw, ok := d.GetOk("source_security_group_id"); ok {
		groups[raw.(string)] = true
	}

	if v, ok := d.GetOk("self"); ok && v.(bool) {
		if sg.VPCID != nil && *sg.VPCID != "" {
			groups[*sg.GroupID] = true
		} else {
			groups[*sg.GroupName] = true
		}
	}

	if len(groups) > 0 {
		perm.UserIDGroupPairs = make([]*ec2.UserIDGroupPair, len(groups))
		// build string list of group name/ids
		var gl []string
		for k, _ := range groups {
			gl = append(gl, k)
		}

		for i, name := range gl {
			ownerId, id := "", name
			if items := strings.Split(id, "/"); len(items) > 1 {
				ownerId, id = items[0], items[1]
			}

			perm.UserIDGroupPairs[i] = &ec2.UserIDGroupPair{
				GroupID: aws.String(id),
				UserID:  aws.String(ownerId),
			}

			if sg.VPCID == nil || *sg.VPCID == "" {
				perm.UserIDGroupPairs[i].GroupID = nil
				perm.UserIDGroupPairs[i].GroupName = aws.String(id)
				perm.UserIDGroupPairs[i].UserID = nil
			}
		}
	}

	if raw, ok := d.GetOk("cidr_blocks"); ok {
		list := raw.([]interface{})
		perm.IPRanges = make([]*ec2.IPRange, len(list))
		for i, v := range list {
			perm.IPRanges[i] = &ec2.IPRange{CIDRIP: aws.String(v.(string))}
		}
	}

	return &perm
}
예제 #26
0
func ExampleCloudFront_UpdateStreamingDistribution() {
	svc := cloudfront.New(nil)

	params := &cloudfront.UpdateStreamingDistributionInput{
		ID: aws.String("string"), // Required
		StreamingDistributionConfig: &cloudfront.StreamingDistributionConfig{ // Required
			CallerReference: aws.String("string"), // Required
			Comment:         aws.String("string"), // Required
			Enabled:         aws.Boolean(true),    // Required
			S3Origin: &cloudfront.S3Origin{ // Required
				DomainName:           aws.String("string"), // Required
				OriginAccessIdentity: aws.String("string"), // Required
			},
			TrustedSigners: &cloudfront.TrustedSigners{ // Required
				Enabled:  aws.Boolean(true), // Required
				Quantity: aws.Long(1),       // Required
				Items: []*string{
					aws.String("string"), // Required
					// More values...
				},
			},
			Aliases: &cloudfront.Aliases{
				Quantity: aws.Long(1), // Required
				Items: []*string{
					aws.String("string"), // Required
					// More values...
				},
			},
			Logging: &cloudfront.StreamingLoggingConfig{
				Bucket:  aws.String("string"), // Required
				Enabled: aws.Boolean(true),    // Required
				Prefix:  aws.String("string"), // Required
			},
			PriceClass: aws.String("PriceClass"),
		},
		IfMatch: aws.String("string"),
	}
	resp, err := svc.UpdateStreamingDistribution(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
예제 #27
0
func ExampleELB_CreateLoadBalancer() {
	svc := elb.New(nil)

	params := &elb.CreateLoadBalancerInput{
		Listeners: []*elb.Listener{ // Required
			{ // Required
				InstancePort:     aws.Long(1),            // Required
				LoadBalancerPort: aws.Long(1),            // Required
				Protocol:         aws.String("Protocol"), // Required
				InstanceProtocol: aws.String("Protocol"),
				SSLCertificateID: aws.String("SSLCertificateId"),
			},
			// More values...
		},
		LoadBalancerName: aws.String("AccessPointName"), // Required
		AvailabilityZones: []*string{
			aws.String("AvailabilityZone"), // Required
			// More values...
		},
		Scheme: aws.String("LoadBalancerScheme"),
		SecurityGroups: []*string{
			aws.String("SecurityGroupId"), // Required
			// More values...
		},
		Subnets: []*string{
			aws.String("SubnetId"), // Required
			// More values...
		},
		Tags: []*elb.Tag{
			{ // Required
				Key:   aws.String("TagKey"), // Required
				Value: aws.String("TagValue"),
			},
			// More values...
		},
	}
	resp, err := svc.CreateLoadBalancer(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
예제 #28
0
// resourceAwsLambdaFunction maps to:
// CreateFunction in the API / SDK
func resourceAwsLambdaFunctionCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).lambdaconn

	functionName := d.Get("function_name").(string)
	iamRole := d.Get("role").(string)

	log.Printf("[DEBUG] Creating Lambda Function %s with role %s", functionName, iamRole)

	filename, err := homedir.Expand(d.Get("filename").(string))
	if err != nil {
		return err
	}
	zipfile, err := ioutil.ReadFile(filename)
	if err != nil {
		return err
	}
	d.Set("source_code_hash", sha256.Sum256(zipfile))

	log.Printf("[DEBUG] ")

	params := &lambda.CreateFunctionInput{
		Code: &lambda.FunctionCode{
			ZipFile: zipfile,
		},
		Description:  aws.String(d.Get("description").(string)),
		FunctionName: aws.String(functionName),
		Handler:      aws.String(d.Get("handler").(string)),
		MemorySize:   aws.Long(int64(d.Get("memory_size").(int))),
		Role:         aws.String(iamRole),
		Runtime:      aws.String(d.Get("runtime").(string)),
		Timeout:      aws.Long(int64(d.Get("timeout").(int))),
	}

	for i := 0; i < 5; i++ {
		_, err = conn.CreateFunction(params)
		if awsErr, ok := err.(awserr.Error); ok {

			// IAM profiles can take ~10 seconds to propagate in AWS:
			//  http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#launch-instance-with-role-console
			// Error creating Lambda function: InvalidParameterValueException: The role defined for the task cannot be assumed by Lambda.
			if awsErr.Code() == "InvalidParameterValueException" && strings.Contains(awsErr.Message(), "The role defined for the task cannot be assumed by Lambda.") {
				log.Printf("[DEBUG] Invalid IAM Instance Profile referenced, retrying...")
				time.Sleep(2 * time.Second)
				continue
			}
		}
		break
	}
	if err != nil {
		return fmt.Errorf("Error creating Lambda function: %s", err)
	}

	d.SetId(d.Get("function_name").(string))

	return resourceAwsLambdaFunctionRead(d, meta)
}
예제 #29
0
func (self *ECSManager) RegisterTaskDefinition(taskName string, containers []*schema.ContainerDefinition) (*ecs.RegisterTaskDefinitionOutput, error) {

	svc := ecs.New(&aws.Config{
		Region:      self.Region,
		Credentials: self.Credentials,
	})

	conDefs := []*ecs.ContainerDefinition{}

	for _, con := range containers {

		var commands []*string
		if len(con.Command) > 0 {
			for _, token := range strings.Split(con.Command, " ") {
				commands = append(commands, aws.String(token))
			}
		} else {
			commands = nil
		}

		var entryPoints []*string
		if len(con.EntryPoint) > 0 {
			for _, token := range strings.Split(con.EntryPoint, " ") {
				entryPoints = append(entryPoints, aws.String(token))
			}
		} else {
			entryPoints = nil
		}

		conDef := &ecs.ContainerDefinition{
			CPU:         aws.Long(con.CpuUnits),
			Command:     commands,
			EntryPoint:  entryPoints,
			Environment: toKeyValuePairs(con.Environment),
			Essential:   aws.Boolean(con.Essential),
			Image:       aws.String(con.Image),
			Links:       util.ConvertPointerString(con.Links),
			Memory:      aws.Long(con.Memory),
			// MountPoints
			Name:         aws.String(con.Name),
			PortMappings: toPortMappings(con.Ports),
			// VolumesFrom
		}

		conDefs = append(conDefs, conDef)
	}

	params := &ecs.RegisterTaskDefinitionInput{
		ContainerDefinitions: conDefs,
		Family:               aws.String(taskName),
		Volumes:              []*ecs.Volume{},
	}

	return svc.RegisterTaskDefinition(params)
}
예제 #30
0
func ExampleCloudWatch_PutMetricAlarm() {
	svc := cloudwatch.New(nil)

	params := &cloudwatch.PutMetricAlarmInput{
		AlarmName:          aws.String("AlarmName"),          // Required
		ComparisonOperator: aws.String("ComparisonOperator"), // Required
		EvaluationPeriods:  aws.Long(1),                      // Required
		MetricName:         aws.String("MetricName"),         // Required
		Namespace:          aws.String("Namespace"),          // Required
		Period:             aws.Long(1),                      // Required
		Statistic:          aws.String("Statistic"),          // Required
		Threshold:          aws.Double(1.0),                  // Required
		ActionsEnabled:     aws.Boolean(true),
		AlarmActions: []*string{
			aws.String("ResourceName"), // Required
			// More values...
		},
		AlarmDescription: aws.String("AlarmDescription"),
		Dimensions: []*cloudwatch.Dimension{
			{ // Required
				Name:  aws.String("DimensionName"),  // Required
				Value: aws.String("DimensionValue"), // Required
			},
			// More values...
		},
		InsufficientDataActions: []*string{
			aws.String("ResourceName"), // Required
			// More values...
		},
		OKActions: []*string{
			aws.String("ResourceName"), // Required
			// More values...
		},
		Unit: aws.String("StandardUnit"),
	}
	resp, err := svc.PutMetricAlarm(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}