Exemplo n.º 1
0
func ExampleSimpleDB_BatchPutAttributes() {
	svc := simpledb.New(nil)

	params := &simpledb.BatchPutAttributesInput{
		DomainName: aws.String("String"), // Required
		Items: []*simpledb.ReplaceableItem{ // Required
			{ // Required
				Attributes: []*simpledb.ReplaceableAttribute{ // Required
					{ // Required
						Name:    aws.String("String"), // Required
						Value:   aws.String("String"), // Required
						Replace: aws.Bool(true),
					},
					// More values...
				},
				Name: aws.String("String"), // Required
			},
			// More values...
		},
	}
	resp, err := svc.BatchPutAttributes(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Exemplo n.º 2
0
func ExampleSimpleDB_DeleteAttributes() {
	svc := simpledb.New(nil)

	params := &simpledb.DeleteAttributesInput{
		DomainName: aws.String("String"), // Required
		ItemName:   aws.String("String"), // Required
		Attributes: []*simpledb.DeletableAttribute{
			{ // Required
				Name:  aws.String("String"), // Required
				Value: aws.String("String"),
			},
			// More values...
		},
		Expected: &simpledb.UpdateCondition{
			Exists: aws.Bool(true),
			Name:   aws.String("String"),
			Value:  aws.String("String"),
		},
	}
	resp, err := svc.DeleteAttributes(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Exemplo n.º 3
0
// CreateAwsmDatabase creates an awsm SimpleDB Domain
func CreateAwsmDatabase() error {

	svc := simpledb.New(session.New(&aws.Config{Region: aws.String("us-east-1")})) // TODO handle default region preference

	params := &simpledb.CreateDomainInput{
		DomainName: aws.String("awsm"),
	}
	_, err := svc.CreateDomain(params)

	if err != nil {
		return err
	}

	// Insert our default configs
	Insert("securitygroups", DefaultSecurityGroupClasses())
	Insert("vpcs", DefaultVpcClasses())
	Insert("subnets", DefaultSubnetClasses())
	Insert("instances", DefaultInstanceClasses())
	Insert("alarms", DefaultAlarms())
	Insert("images", DefaultImageClasses())
	Insert("scalingpolicies", DefaultScalingPolicyClasses())
	Insert("launchconfigurations", DefaultLaunchConfigurationClasses())
	Insert("loadbalancers", DefaultLoadBalancerClasses())
	Insert("volumes", DefaultVolumeClasses())
	Insert("snapshots", DefaultSnapshotClasses())
	Insert("autoscalegroups", DefaultAutoscaleGroupClasses())
	Insert("keypairs", DefaultKeyPairClasses())
	Insert("widgets", DefaultWidgets())

	return nil
}
Exemplo n.º 4
0
func ExampleSimpleDB_Select() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := simpledb.New(sess)

	params := &simpledb.SelectInput{
		SelectExpression: aws.String("String"), // Required
		ConsistentRead:   aws.Bool(true),
		NextToken:        aws.String("String"),
	}
	resp, err := svc.Select(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Exemplo n.º 5
0
func TestResponseError(t *testing.T) {
	for _, test := range responseErrorTests {
		s := simpledb.New(nil)
		s.Handlers.Send.Clear()
		s.Handlers.Send.PushBack(func(r *request.Request) {
			xml := createXMLResponse(test.requestID, test.errors)
			body := ioutil.NopCloser(bytes.NewReader([]byte(xml)))
			r.HTTPResponse = &http.Response{
				ContentLength: int64(len(xml)),
				StatusCode:    test.scode,
				Status:        test.status,
				Body:          body,
			}
		})
		_, err := s.CreateDomain(&simpledb.CreateDomainInput{
			DomainName: aws.String("test-domain"),
		})

		assert.Error(t, err)
		assert.Equal(t, test.code, err.(awserr.Error).Code())
		assert.Equal(t, test.message, err.(awserr.Error).Message())
		if len(test.errors) > 0 {
			assert.Equal(t, test.requestID, err.(awserr.RequestFailure).RequestID())
			assert.Equal(t, test.scode, err.(awserr.RequestFailure).StatusCode())
		}
	}
}
Exemplo n.º 6
0
func ExampleSimpleDB_GetAttributes() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := simpledb.New(sess)

	params := &simpledb.GetAttributesInput{
		DomainName: aws.String("String"), // Required
		ItemName:   aws.String("String"), // Required
		AttributeNames: []*string{
			aws.String("String"), // Required
			// More values...
		},
		ConsistentRead: aws.Bool(true),
	}
	resp, err := svc.GetAttributes(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Exemplo n.º 7
0
func ExampleSimpleDB_ListDomains() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := simpledb.New(sess)

	params := &simpledb.ListDomainsInput{
		MaxNumberOfDomains: aws.Int64(1),
		NextToken:          aws.String("String"),
	}
	resp, err := svc.ListDomains(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Exemplo n.º 8
0
// DeleteItemsByType batch deletes classes from SimpleDB
func DeleteItemsByType(classType string) error {
	svc := simpledb.New(session.New(&aws.Config{Region: aws.String("us-east-1")})) // TODO handle default region preference

	existingItems, err := GetItemsByType(classType)
	if err != nil {
		return err
	}

	params := &simpledb.BatchDeleteAttributesInput{
		DomainName: aws.String("awsm"),
		//Items:      deleteList,
	}

	for _, item := range existingItems {
		itemName := aws.StringValue(item.Name)
		params.Items = append(params.Items, &simpledb.DeletableItem{
			Name: item.Name,
		})

		terminal.Information("Deleting [" + classType + "/" + itemName + "] Configuration...")
	}

	_, err = svc.BatchDeleteAttributes(params)
	if err != nil {
		return err
	}

	terminal.Information("Done!")

	return nil
}
Exemplo n.º 9
0
// GetItemByName gets a SimpleDB item by its type and name
func GetItemByName(classType, className string) (*simpledb.Item, error) {

	svc := simpledb.New(session.New(&aws.Config{Region: aws.String("us-east-1")})) // TODO handle default region preference

	params := &simpledb.GetAttributesInput{
		DomainName:     aws.String("awsm"),
		ItemName:       aws.String(classType + "/" + className),
		ConsistentRead: aws.Bool(true),
	}
	resp, err := svc.GetAttributes(params)

	if err != nil {
		return &simpledb.Item{}, err
	}

	if len(resp.Attributes) < 1 {
		return &simpledb.Item{}, errors.New("Unable to find the [" + className + "] class in the database!")
	}

	item := &simpledb.Item{
		Name:       aws.String(classType + "/" + className),
		Attributes: resp.Attributes,
	}

	return item, nil
}
Exemplo n.º 10
0
// DeleteSimpleDBDomains deletes one or more SimpleDB Domains
func DeleteSimpleDBDomains(search, region string) (err error) {

	domainList := new(SimpleDBDomains)

	// Check if we were given a region or not
	if region != "" {
		err = GetRegionSimpleDBDomains(aws.String(region), domainList, search)
	} else {
		domainList, _ = GetSimpleDBDomains(search)
	}

	if err != nil {
		terminal.ErrorLine("Error gathering SimpleDB domains list")
		return
	}

	if len(*domainList) > 0 {
		// Print the table
		domainList.PrintTable()
	} else {
		terminal.ErrorLine("No SimpleDB Domains found, Aborting!")
		return
	}

	// Confirm
	if !terminal.PromptBool("Are you sure you want to delete these SimpleDB Domains?") {
		terminal.ErrorLine("Aborting!")
		return
	}

	// Delete 'Em
	for _, domain := range *domainList {
		svc := simpledb.New(session.New(&aws.Config{Region: aws.String(domain.Region)}))

		params := &simpledb.DeleteDomainInput{
			DomainName: aws.String(domain.Name),
		}
		_, err = svc.DeleteDomain(params)
		if err != nil {
			terminal.ErrorLine("Error while deleting SimpleDB Domain [" + domain.Name + "] in [" + domain.Region + "], Aborting!")
			return
		}
		terminal.Information("Deleted SimpleDB Domain [" + domain.Name + "] in [" + domain.Region + "]!")
	}

	terminal.Information("Done!")

	return
}
Exemplo n.º 11
0
// CheckDB checks for an awsm database
func CheckDB() bool {

	svc := simpledb.New(session.New(&aws.Config{Region: aws.String("us-east-1")})) // TODO handle default region preference

	params := &simpledb.DomainMetadataInput{
		DomainName: aws.String("awsm"), // Required
	}
	_, err := svc.DomainMetadata(params)

	if err != nil {
		return false
	}

	// TODO handle the response stats?
	return true
}
Exemplo n.º 12
0
func ExampleSimpleDB_CreateDomain() {
	svc := simpledb.New(nil)

	params := &simpledb.CreateDomainInput{
		DomainName: aws.String("String"), // Required
	}
	resp, err := svc.CreateDomain(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Exemplo n.º 13
0
// DeleteWidget deletes a widget from SimpleDB
func DeleteWidget(widgetName string) error {
	svc := simpledb.New(session.New(&aws.Config{Region: aws.String("us-east-1")})) // TODO handle default region preference

	itemName := "widgets/" + widgetName

	params := &simpledb.DeleteAttributesInput{
		DomainName: aws.String("awsm"),
		ItemName:   aws.String(itemName),
	}

	terminal.Information("Deleting [" + itemName + "] Configuration...")
	_, err := svc.DeleteAttributes(params)
	if err != nil {
		return err
	}

	terminal.Information("Done!")

	return nil
}
Exemplo n.º 14
0
func TestStatusCodeError(t *testing.T) {
	for _, test := range statusCodeErrorTests {
		s := simpledb.New(nil)
		s.Handlers.Send.Clear()
		s.Handlers.Send.PushBack(func(r *request.Request) {
			body := ioutil.NopCloser(bytes.NewReader([]byte{}))
			r.HTTPResponse = &http.Response{
				ContentLength: 0,
				StatusCode:    test.scode,
				Status:        test.status,
				Body:          body,
			}
		})
		_, err := s.CreateDomain(&simpledb.CreateDomainInput{
			DomainName: aws.String("test-domain"),
		})

		assert.Error(t, err)
		assert.Equal(t, test.code, err.(awserr.Error).Code())
		assert.Equal(t, test.message, err.(awserr.Error).Message())
	}
}
Exemplo n.º 15
0
// GetItemsByType returns all SimpleDB items by class type
func GetItemsByType(classType string) ([]*simpledb.Item, error) {

	svc := simpledb.New(session.New(&aws.Config{Region: aws.String("us-east-1")})) // TODO handle default region preference

	params := &simpledb.SelectInput{
		SelectExpression: aws.String(fmt.Sprintf("select * from awsm where classType = '%s'", classType)),
		ConsistentRead:   aws.Bool(true),
		//NextToken:        aws.String("String"),
	}

	resp, err := svc.Select(params)

	if err != nil {
		return []*simpledb.Item{}, err
	}

	if len(resp.Items) < 1 {
		return []*simpledb.Item{}, errors.New("Unable to find the [" + classType + "] class in the database!")
	}

	return resp.Items, nil
}
Exemplo n.º 16
0
// CreateSimpleDBDomain creates a new SimpleDB Domain
func CreateSimpleDBDomain(domain, region string) error {

	// Validate the region
	if !regions.ValidRegion(region) {
		return errors.New("Region [" + region + "] is Invalid!")
	}

	svc := simpledb.New(session.New(&aws.Config{Region: aws.String(region)}))

	params := &simpledb.CreateDomainInput{
		DomainName: aws.String(domain),
	}

	terminal.Information("Creating SimpleDB Domain [" + domain + "] in [" + region + "]...")

	_, err := svc.CreateDomain(params)
	if err == nil {
		terminal.Information("Done!")
	}

	return err
}
Exemplo n.º 17
0
func ExampleSimpleDB_PutAttributes() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := simpledb.New(sess)

	params := &simpledb.PutAttributesInput{
		Attributes: []*simpledb.ReplaceableAttribute{ // Required
			{ // Required
				Name:    aws.String("String"), // Required
				Value:   aws.String("String"), // Required
				Replace: aws.Bool(true),
			},
			// More values...
		},
		DomainName: aws.String("String"), // Required
		ItemName:   aws.String("String"), // Required
		Expected: &simpledb.UpdateCondition{
			Exists: aws.Bool(true),
			Name:   aws.String("String"),
			Value:  aws.String("String"),
		},
	}
	resp, err := svc.PutAttributes(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Exemplo n.º 18
0
// GetRegionSimpleDBDomains returns a slice of a regions SimpleDB Domains into the provided SimpleDBDomains slice
func GetRegionSimpleDBDomains(region *string, domainList *SimpleDBDomains, search string) error {
	svc := simpledb.New(session.New(&aws.Config{Region: region}))
	result, err := svc.ListDomains(nil)
	if err != nil {
		//return err // TODO handle regions without services
	}

	domains := make(SimpleDBDomains, len(result.DomainNames))
	for i, domain := range result.DomainNames {

		domains[i] = SimpleDBDomain{
			Name:   aws.StringValue(domain),
			Region: aws.StringValue(region),
		}
	}

	if search != "" {
		term := regexp.MustCompile(search)
	Loop:
		for i, dn := range domains {
			rDomain := reflect.ValueOf(dn)

			for k := 0; k < rDomain.NumField(); k++ {
				sVal := rDomain.Field(k).String()

				if term.MatchString(sVal) {
					*domainList = append(*domainList, domains[i])
					continue Loop
				}
			}
		}
	} else {
		*domainList = append(*domainList, domains[:]...)
	}

	return nil
}
Exemplo n.º 19
0
func ExampleSimpleDB_BatchDeleteAttributes() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := simpledb.New(sess)

	params := &simpledb.BatchDeleteAttributesInput{
		DomainName: aws.String("String"), // Required
		Items: []*simpledb.DeletableItem{ // Required
			{ // Required
				Name: aws.String("String"), // Required
				Attributes: []*simpledb.DeletableAttribute{
					{ // Required
						Name:  aws.String("String"), // Required
						Value: aws.String("String"),
					},
					// More values...
				},
			},
			// More values...
		},
	}
	resp, err := svc.BatchDeleteAttributes(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Exemplo n.º 20
0
func ExampleSimpleDB_DomainMetadata() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := simpledb.New(sess)

	params := &simpledb.DomainMetadataInput{
		DomainName: aws.String("String"), // Required
	}
	resp, err := svc.DomainMetadata(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Exemplo n.º 21
0
func TestInterface(t *testing.T) {
	assert.Implements(t, (*simpledbiface.SimpleDBAPI)(nil), simpledb.New(nil))
}
Exemplo n.º 22
0
// Insert inserts Classes into SimpleDB
func Insert(classType string, classInterface interface{}) error {

	var itemName string
	itemsMap := make(map[string][]*simpledb.ReplaceableAttribute)
	svc := simpledb.New(session.New(&aws.Config{Region: aws.String("us-east-1")})) // TODO handle default region preference

	// Build Attributes
	switch classType {
	case "vpcs":
		for class, config := range classInterface.(VpcClasses) {
			itemName = classType + "/" + class
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)
		}

	case "subnets":
		for class, config := range classInterface.(SubnetClasses) {
			itemName = classType + "/" + class
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)
		}

	case "instances":
		for class, config := range classInterface.(InstanceClasses) {
			itemName = classType + "/" + class
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)
		}

	case "volumes":
		for class, config := range classInterface.(VolumeClasses) {
			itemName = classType + "/" + class
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)
		}

	case "snapshots":
		for class, config := range classInterface.(SnapshotClasses) {
			itemName = classType + "/" + class
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)
		}

	case "images":
		for class, config := range classInterface.(ImageClasses) {
			itemName = classType + "/" + class
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)
		}

	case "autoscalegroups":
		for class, config := range classInterface.(AutoscaleGroupClasses) {
			itemName = classType + "/" + class
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)
		}

	case "launchconfigurations":
		for class, config := range classInterface.(LaunchConfigurationClasses) {
			itemName = classType + "/" + class
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)
		}

	case "loadbalancers":
		for class, config := range classInterface.(LoadBalancerClasses) {
			itemName = classType + "/" + class
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)

			// Delete the existing listeners
			DeleteItemsByType(classType + "/" + class + "/listeners")

			// Load Balancer Listeners
			for _, listener := range config.Listeners {
				itemName = classType + "/" + class + "/listeners/" + uuid.NewV4().String()
				itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(listener, classType+"/"+class+"/listeners")...)
			}
		}

	case "scalingpolicies":
		for class, config := range classInterface.(ScalingPolicyClasses) {
			itemName = classType + "/" + class
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)
		}

	case "alarms":
		for class, config := range classInterface.(AlarmClasses) {
			itemName = classType + "/" + class
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)
		}

	case "securitygroups":
		for class, config := range classInterface.(SecurityGroupClasses) {
			itemName = classType + "/" + class
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)

			// Delete the existing grants
			DeleteItemsByType(classType + "/" + class + "/grants")

			// Security Group Grants
			for _, grant := range config.SecurityGroupGrants {
				itemName = classType + "/" + class + "/grants/" + uuid.NewV4().String()
				itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(grant, classType+"/"+class+"/grants")...)
			}
		}

	case "keypairs":
		for class, config := range classInterface.(KeyPairClasses) {
			itemName = classType + "/" + class
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)
		}

	case "widgets":
		for widget, config := range classInterface.(Widgets) {
			itemName = classType + "/" + widget
			itemsMap[itemName] = append(itemsMap[itemName], BuildAttributes(config, classType)...)
		}

	default:
		return errors.New("Insert does not have switch for [" + classType + "]! No configurations of this type are being installed!")

	}

	items := make([]*simpledb.ReplaceableItem, len(itemsMap))

	for item, attributes := range itemsMap {

		terminal.Information("Building Configuration for [" + item + "]...")

		i := &simpledb.ReplaceableItem{
			Attributes: attributes,
			Name:       aws.String(item),
		}
		items = append(items, i)

	}

	params := &simpledb.BatchPutAttributesInput{
		DomainName: aws.String("awsm"),
		Items:      items,
	}
	terminal.Information("Installing [" + classType + "] Configurations...")
	_, err := svc.BatchPutAttributes(params)

	if err != nil {
		return err
	}

	terminal.Information("Done!")

	return nil

}
Exemplo n.º 23
0
// SaveScalingPolicyClass reads and unmarshals a byte slice and inserts it into the db
func SaveFeed(feedName string, latest FeedItems, max int) (feed FeedItems, err error) {

	svc := simpledb.New(session.New(&aws.Config{Region: aws.String("us-east-1")})) // TODO handle default region preference
	existing, _ := LoadAllFeedItems(feedName)

	sort.Sort(existing)
	sort.Sort(latest)

	if len(latest) < 1 {
		return existing, nil
	}

	// Delete the existing items
	DeleteItemsByType("feeditems/" + feedName)

	itemsMap := make(map[string][]*simpledb.ReplaceableAttribute)
	for index, feedItem := range latest {
		if index > max {
			break
		}

		itemsMap[feedItem.ID] = append(itemsMap[feedItem.ID], BuildAttributes(feedItem, "feeditems/"+feedName)...)
	}

	count := len(itemsMap)

Loop:
	for _, feedItem := range existing {
		itemsMap[feedItem.ID] = append(itemsMap[feedItem.ID], BuildAttributes(feedItem, "feeditems/"+feedName)...)
		count++
		if count < max {
			continue Loop
		}
	}

	items := make([]*simpledb.ReplaceableItem, len(itemsMap))
	for item, attributes := range itemsMap {

		i := &simpledb.ReplaceableItem{
			Attributes: attributes,
			Name:       aws.String(item),
		}
		items = append(items, i)

	}

	params := &simpledb.BatchPutAttributesInput{
		DomainName: aws.String("awsm"),
		Items:      items,
	}

	_, err = svc.BatchPutAttributes(params)
	if err != nil {
		return latest, err
	}

	itms, err := LoadAllFeedItems(feedName)

	sort.Sort(itms)
	return itms, err

}
Exemplo n.º 24
0
// Client configures and returns a fully initialized AWSClient
func (c *Config) Client() (interface{}, error) {
	// Get the auth and region. This can fail if keys/regions were not
	// specified and we're attempting to use the environment.
	log.Println("[INFO] Building AWS region structure")
	err := c.ValidateRegion()
	if err != nil {
		return nil, err
	}

	var client AWSClient
	// store AWS region in client struct, for region specific operations such as
	// bucket storage in S3
	client.region = c.Region

	log.Println("[INFO] Building AWS auth structure")
	creds, err := GetCredentials(c)
	if err != nil {
		return nil, err
	}
	// Call Get to check for credential provider. If nothing found, we'll get an
	// error, and we can present it nicely to the user
	cp, err := creds.Get()
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoCredentialProviders" {
			return nil, errors.New(`No valid credential sources found for AWS Provider.
  Please see https://terraform.io/docs/providers/aws/index.html for more information on
  providing credentials for the AWS Provider`)
		}

		return nil, fmt.Errorf("Error loading credentials for AWS Provider: %s", err)
	}

	log.Printf("[INFO] AWS Auth provider used: %q", cp.ProviderName)

	awsConfig := &aws.Config{
		Credentials:      creds,
		Region:           aws.String(c.Region),
		MaxRetries:       aws.Int(c.MaxRetries),
		HTTPClient:       cleanhttp.DefaultClient(),
		S3ForcePathStyle: aws.Bool(c.S3ForcePathStyle),
	}

	if logging.IsDebugOrHigher() {
		awsConfig.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
		awsConfig.Logger = awsLogger{}
	}

	if c.Insecure {
		transport := awsConfig.HTTPClient.Transport.(*http.Transport)
		transport.TLSClientConfig = &tls.Config{
			InsecureSkipVerify: true,
		}
	}

	// Set up base session
	sess, err := session.NewSession(awsConfig)
	if err != nil {
		return nil, errwrap.Wrapf("Error creating AWS session: {{err}}", err)
	}

	// Removes the SDK Version handler, so we only have the provider User-Agent
	// Ex: "User-Agent: APN/1.0 HashiCorp/1.0 Terraform/0.7.9-dev"
	sess.Handlers.Build.Remove(request.NamedHandler{Name: "core.SDKVersionUserAgentHandler"})
	sess.Handlers.Build.PushFrontNamed(addTerraformVersionToUserAgent)

	if extraDebug := os.Getenv("TERRAFORM_AWS_AUTHFAILURE_DEBUG"); extraDebug != "" {
		sess.Handlers.UnmarshalError.PushFrontNamed(debugAuthFailure)
	}

	// Some services exist only in us-east-1, e.g. because they manage
	// resources that can span across multiple regions, or because
	// signature format v4 requires region to be us-east-1 for global
	// endpoints:
	// http://docs.aws.amazon.com/general/latest/gr/sigv4_changes.html
	usEast1Sess := sess.Copy(&aws.Config{Region: aws.String("us-east-1")})

	// Some services have user-configurable endpoints
	awsEc2Sess := sess.Copy(&aws.Config{Endpoint: aws.String(c.Ec2Endpoint)})
	awsElbSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.ElbEndpoint)})
	awsIamSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.IamEndpoint)})
	awsS3Sess := sess.Copy(&aws.Config{Endpoint: aws.String(c.S3Endpoint)})
	dynamoSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.DynamoDBEndpoint)})
	kinesisSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.KinesisEndpoint)})

	// These two services need to be set up early so we can check on AccountID
	client.iamconn = iam.New(awsIamSess)
	client.stsconn = sts.New(sess)

	if !c.SkipCredsValidation {
		err = c.ValidateCredentials(client.stsconn)
		if err != nil {
			return nil, err
		}
	}

	if !c.SkipRequestingAccountId {
		partition, accountId, err := GetAccountInfo(client.iamconn, client.stsconn, cp.ProviderName)
		if err == nil {
			client.partition = partition
			client.accountid = accountId
		}
	}

	authErr := c.ValidateAccountId(client.accountid)
	if authErr != nil {
		return nil, authErr
	}

	client.acmconn = acm.New(sess)
	client.apigateway = apigateway.New(sess)
	client.appautoscalingconn = applicationautoscaling.New(sess)
	client.autoscalingconn = autoscaling.New(sess)
	client.cfconn = cloudformation.New(sess)
	client.cloudfrontconn = cloudfront.New(sess)
	client.cloudtrailconn = cloudtrail.New(sess)
	client.cloudwatchconn = cloudwatch.New(sess)
	client.cloudwatcheventsconn = cloudwatchevents.New(sess)
	client.cloudwatchlogsconn = cloudwatchlogs.New(sess)
	client.codecommitconn = codecommit.New(usEast1Sess)
	client.codedeployconn = codedeploy.New(sess)
	client.dsconn = directoryservice.New(sess)
	client.dynamodbconn = dynamodb.New(dynamoSess)
	client.ec2conn = ec2.New(awsEc2Sess)
	client.ecrconn = ecr.New(sess)
	client.ecsconn = ecs.New(sess)
	client.efsconn = efs.New(sess)
	client.elasticacheconn = elasticache.New(sess)
	client.elasticbeanstalkconn = elasticbeanstalk.New(sess)
	client.elastictranscoderconn = elastictranscoder.New(sess)
	client.elbconn = elb.New(awsElbSess)
	client.elbv2conn = elbv2.New(awsElbSess)
	client.emrconn = emr.New(sess)
	client.esconn = elasticsearch.New(sess)
	client.firehoseconn = firehose.New(sess)
	client.glacierconn = glacier.New(sess)
	client.kinesisconn = kinesis.New(kinesisSess)
	client.kmsconn = kms.New(sess)
	client.lambdaconn = lambda.New(sess)
	client.lightsailconn = lightsail.New(usEast1Sess)
	client.opsworksconn = opsworks.New(usEast1Sess)
	client.r53conn = route53.New(usEast1Sess)
	client.rdsconn = rds.New(sess)
	client.redshiftconn = redshift.New(sess)
	client.simpledbconn = simpledb.New(sess)
	client.s3conn = s3.New(awsS3Sess)
	client.sesConn = ses.New(sess)
	client.snsconn = sns.New(sess)
	client.sqsconn = sqs.New(sess)
	client.ssmconn = ssm.New(sess)
	client.wafconn = waf.New(sess)

	return &client, nil
}
Exemplo n.º 25
0
func init() {
	Before("@simpledb", func() {
		World["client"] = simpledb.New(nil)
	})
}
Exemplo n.º 26
0
// Client configures and returns a fully initialized AWSClient
func (c *Config) Client() (interface{}, error) {
	// Get the auth and region. This can fail if keys/regions were not
	// specified and we're attempting to use the environment.
	var errs []error

	log.Println("[INFO] Building AWS region structure")
	err := c.ValidateRegion()
	if err != nil {
		errs = append(errs, err)
	}

	var client AWSClient
	if len(errs) == 0 {
		// store AWS region in client struct, for region specific operations such as
		// bucket storage in S3
		client.region = c.Region

		log.Println("[INFO] Building AWS auth structure")
		creds := GetCredentials(c.AccessKey, c.SecretKey, c.Token, c.Profile, c.CredsFilename)
		// Call Get to check for credential provider. If nothing found, we'll get an
		// error, and we can present it nicely to the user
		cp, err := creds.Get()
		if err != nil {
			if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoCredentialProviders" {
				errs = append(errs, fmt.Errorf(`No valid credential sources found for AWS Provider.
  Please see https://terraform.io/docs/providers/aws/index.html for more information on
  providing credentials for the AWS Provider`))
			} else {
				errs = append(errs, fmt.Errorf("Error loading credentials for AWS Provider: %s", err))
			}
			return nil, &multierror.Error{Errors: errs}
		}

		log.Printf("[INFO] AWS Auth provider used: %q", cp.ProviderName)

		awsConfig := &aws.Config{
			Credentials: creds,
			Region:      aws.String(c.Region),
			MaxRetries:  aws.Int(c.MaxRetries),
			HTTPClient:  cleanhttp.DefaultClient(),
		}

		if logging.IsDebugOrHigher() {
			awsConfig.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
			awsConfig.Logger = awsLogger{}
		}

		if c.Insecure {
			transport := awsConfig.HTTPClient.Transport.(*http.Transport)
			transport.TLSClientConfig = &tls.Config{
				InsecureSkipVerify: true,
			}
		}

		// Set up base session
		sess := session.New(awsConfig)
		sess.Handlers.Build.PushFrontNamed(addTerraformVersionToUserAgent)

		// Some services exist only in us-east-1, e.g. because they manage
		// resources that can span across multiple regions, or because
		// signature format v4 requires region to be us-east-1 for global
		// endpoints:
		// http://docs.aws.amazon.com/general/latest/gr/sigv4_changes.html
		usEast1Sess := sess.Copy(&aws.Config{Region: aws.String("us-east-1")})

		// Some services have user-configurable endpoints
		awsEc2Sess := sess.Copy(&aws.Config{Endpoint: aws.String(c.Ec2Endpoint)})
		awsElbSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.ElbEndpoint)})
		awsIamSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.IamEndpoint)})
		dynamoSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.DynamoDBEndpoint)})
		kinesisSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.KinesisEndpoint)})

		// These two services need to be set up early so we can check on AccountID
		client.iamconn = iam.New(awsIamSess)
		client.stsconn = sts.New(sess)

		err = c.ValidateCredentials(client.stsconn)
		if err != nil {
			errs = append(errs, err)
			return nil, &multierror.Error{Errors: errs}
		}
		accountId, err := GetAccountId(client.iamconn, client.stsconn, cp.ProviderName)
		if err == nil {
			client.accountid = accountId
		}

		authErr := c.ValidateAccountId(client.accountid)
		if authErr != nil {
			errs = append(errs, authErr)
		}

		client.apigateway = apigateway.New(sess)
		client.autoscalingconn = autoscaling.New(sess)
		client.cfconn = cloudformation.New(sess)
		client.cloudfrontconn = cloudfront.New(sess)
		client.cloudtrailconn = cloudtrail.New(sess)
		client.cloudwatchconn = cloudwatch.New(sess)
		client.cloudwatcheventsconn = cloudwatchevents.New(sess)
		client.cloudwatchlogsconn = cloudwatchlogs.New(sess)
		client.codecommitconn = codecommit.New(usEast1Sess)
		client.codedeployconn = codedeploy.New(sess)
		client.dsconn = directoryservice.New(sess)
		client.dynamodbconn = dynamodb.New(dynamoSess)
		client.ec2conn = ec2.New(awsEc2Sess)
		client.ecrconn = ecr.New(sess)
		client.ecsconn = ecs.New(sess)
		client.efsconn = efs.New(sess)
		client.elasticacheconn = elasticache.New(sess)
		client.elasticbeanstalkconn = elasticbeanstalk.New(sess)
		client.elastictranscoderconn = elastictranscoder.New(sess)
		client.elbconn = elb.New(awsElbSess)
		client.emrconn = emr.New(sess)
		client.esconn = elasticsearch.New(sess)
		client.firehoseconn = firehose.New(sess)
		client.glacierconn = glacier.New(sess)
		client.kinesisconn = kinesis.New(kinesisSess)
		client.kmsconn = kms.New(sess)
		client.lambdaconn = lambda.New(sess)
		client.opsworksconn = opsworks.New(usEast1Sess)
		client.r53conn = route53.New(usEast1Sess)
		client.rdsconn = rds.New(sess)
		client.redshiftconn = redshift.New(sess)
		client.simpledbconn = simpledb.New(sess)
		client.s3conn = s3.New(sess)
		client.sesConn = ses.New(sess)
		client.snsconn = sns.New(sess)
		client.sqsconn = sqs.New(sess)
	}

	if len(errs) > 0 {
		return nil, &multierror.Error{Errors: errs}
	}

	return &client, nil
}
Exemplo n.º 27
0
func init() {
	Before("@simpledb", func() {
		World["client"] = simpledb.New(smoke.Session)
	})
}