示例#1
0
func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers) {
	// Merge in user provided configuration
	cfg.MergeIn(userCfg)

	// Region if not already set by user
	if len(aws.StringValue(cfg.Region)) == 0 {
		if len(envCfg.Region) > 0 {
			cfg.WithRegion(envCfg.Region)
		} else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 {
			cfg.WithRegion(sharedCfg.Region)
		}
	}

	// Configure credentials if not already set
	if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil {
		if len(envCfg.Creds.AccessKeyID) > 0 {
			cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
				envCfg.Creds,
			)
		} else if envCfg.EnableSharedConfig && len(sharedCfg.AssumeRole.RoleARN) > 0 && sharedCfg.AssumeRoleSource != nil {
			cfgCp := *cfg
			cfgCp.Credentials = credentials.NewStaticCredentialsFromCreds(
				sharedCfg.AssumeRoleSource.Creds,
			)
			cfg.Credentials = stscreds.NewCredentials(
				&Session{
					Config:   &cfgCp,
					Handlers: handlers.Copy(),
				},
				sharedCfg.AssumeRole.RoleARN,
				func(opt *stscreds.AssumeRoleProvider) {
					opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName

					if len(sharedCfg.AssumeRole.ExternalID) > 0 {
						opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID)
					}

					// MFA not supported
				},
			)
		} else if len(sharedCfg.Creds.AccessKeyID) > 0 {
			cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
				sharedCfg.Creds,
			)
		} else {
			// Fallback to default credentials provider, include mock errors
			// for the credential chain so user can identify why credentials
			// failed to be retrieved.
			cfg.Credentials = credentials.NewCredentials(&credentials.ChainProvider{
				VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors),
				Providers: []credentials.Provider{
					&credProviderError{Err: awserr.New("EnvAccessKeyNotFound", "failed to find credentials in the environment.", nil)},
					&credProviderError{Err: awserr.New("SharedCredsLoad", fmt.Sprintf("failed to load profile, %s.", envCfg.Profile), nil)},
					defaults.RemoteCredProvider(*cfg, handlers),
				},
			})
		}
	}
}
示例#2
0
func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers) {
	// Merge in user provided configuration
	cfg.MergeIn(userCfg)

	// Region if not already set by user
	if len(aws.StringValue(cfg.Region)) == 0 {
		if len(envCfg.Region) > 0 {
			cfg.WithRegion(envCfg.Region)
		} else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 {
			cfg.WithRegion(sharedCfg.Region)
		}
	}

	// Configure credentials if not already set
	if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil {
		if len(envCfg.Creds.AccessKeyID) > 0 {
			cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
				envCfg.Creds,
			)
		} else if envCfg.EnableSharedConfig && len(sharedCfg.AssumeRole.RoleARN) > 0 && sharedCfg.AssumeRoleSource != nil {
			cfgCp := *cfg
			cfgCp.Credentials = credentials.NewStaticCredentialsFromCreds(
				sharedCfg.AssumeRoleSource.Creds,
			)
			cfg.Credentials = stscreds.NewCredentials(
				&Session{
					Config:   &cfgCp,
					Handlers: handlers.Copy(),
				},
				sharedCfg.AssumeRole.RoleARN,
				func(opt *stscreds.AssumeRoleProvider) {
					opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName

					if len(sharedCfg.AssumeRole.ExternalID) > 0 {
						opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID)
					}

					// MFA not supported
				},
			)
		} else if len(sharedCfg.Creds.AccessKeyID) > 0 {
			cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
				sharedCfg.Creds,
			)
		} else {
			// Fallback to default credentials provider
			cfg.Credentials = credentials.NewCredentials(
				defaults.RemoteCredProvider(*cfg, handlers),
			)
		}
	}
}
示例#3
0
文件: goad.go 项目: goadapp/goad
func (t *Test) invokeLambdas(awsConfig *aws.Config, sqsURL string) {
	lambdas := numberOfLambdas(t.config.Concurrency, len(t.config.Regions))

	for i := 0; i < lambdas; i++ {
		region := t.config.Regions[i%len(t.config.Regions)]
		requests, requestsRemainder := divide(t.config.TotalRequests, lambdas)
		concurrency, _ := divide(t.config.Concurrency, lambdas)

		if requestsRemainder > 0 && i == lambdas-1 {
			requests += requestsRemainder
		}

		c := t.config
		args := []string{
			"-u",
			fmt.Sprintf("%s", c.URL),
			"-c",
			fmt.Sprintf("%s", strconv.Itoa(int(concurrency))),
			"-n",
			fmt.Sprintf("%s", strconv.Itoa(int(requests))),
			"-s",
			fmt.Sprintf("%s", sqsURL),
			"-q",
			fmt.Sprintf("%s", c.Regions[0]),
			"-t",
			fmt.Sprintf("%s", c.RequestTimeout.String()),
			"-f",
			fmt.Sprintf("%s", reportingFrequency(lambdas).String()),
			"-r",
			fmt.Sprintf("%s", region),
			"-m",
			fmt.Sprintf("%s", c.Method),
			"-b",
			fmt.Sprintf("%s", c.Body),
		}

		for _, v := range t.config.Headers {
			args = append(args, "-H", fmt.Sprintf("%s", v))
		}

		invokeargs := invokeArgs{
			File: "./goad-lambda",
			Args: args,
		}

		config := awsConfig.WithRegion(region)
		go t.invokeLambda(config, invokeargs)
	}
}
示例#4
0
// getSessionWithConfig grabs the region and appends to the current config
func getSessionWithConfig(config *aws.Config) (*session.Session, error) {
	region, err := getAWSRegion()

	if profileName != "" {
		fmt.Println("Profile: ", *profile)
	} else {
		fmt.Println("Profile: default")
	}

	if region != "" {
		fmt.Println("Region: ", region)
		config = config.WithRegion(region)
	}

	fmt.Println()
	return session.New(config), err
}
示例#5
0
func instances(args instancesArgs, config *aws.Config) {
	zone := lookupZone(args.name)
	fmt.Println("Getting DNS records")

	describeInstancesInput := ec2.DescribeInstancesInput{}
	if args.off == "" {
		filter := ec2.Filter{
			Name:   aws.String("instance-state-name"),
			Values: []*string{aws.String("running")},
		}
		describeInstancesInput.Filters = []*ec2.Filter{&filter}
	}

	var reMatch *regexp.Regexp
	if args.match != "" {
		var err error
		reMatch, err = regexp.Compile(args.match)
		if err != nil {
			fatalIfErr(err)
		}
	}

	insts := map[string]*ec2.Instance{}
	for _, region := range args.regions {
		ec2conn := ec2.New(session.New(), config.WithRegion(region))
		for {
			// paginated
			output, err := ec2conn.DescribeInstances(&describeInstancesInput)
			fatalIfErr(err)
			for _, r := range output.Reservations {
				for _, i := range r.Instances {
					for _, tag := range i.Tags {
						// limit to instances with a Name tag
						if *tag.Key == "Name" {
							if reMatch != nil && !reMatch.MatchString(*tag.Value) {
								continue
							}
							insts[*tag.Value] = i
							continue
						}
					}
				}
			}

			if output.NextToken == nil {
				break
			}
			describeInstancesInput.NextToken = output.NextToken
		}
	}

	if len(insts) == 0 {
		fmt.Println("No instances found")
	}

	var rtype string
	if args.aRecord {
		rtype = "A"
	} else {
		rtype = "CNAME"
	}

	suffix := "." + *zone.Name
	suffix = strings.TrimSuffix(suffix, ".")

	upserts := []*route53.Change{}
	for name, instance := range insts {
		var value *string
		if *instance.State.Name != "running" {
			value = &args.off
		} else if args.aRecord {
			if args.internal {
				value = instance.PrivateIpAddress
			} else {
				value = instance.PublicIpAddress
			}
		} else {
			if args.internal {
				value = aws.String(*instance.PrivateDnsName + ".")
			} else {
				value = aws.String(*instance.PublicDnsName + ".")
			}
		}

		// add domain suffix if missing
		dnsname := name
		if !strings.HasSuffix(dnsname, suffix) {
			dnsname += suffix
		}
		rr := route53.ResourceRecord{
			Value: value,
		}
		rrset := route53.ResourceRecordSet{
			Name:            &dnsname,
			TTL:             aws.Int64(int64(args.ttl)),
			Type:            &rtype,
			ResourceRecords: []*route53.ResourceRecord{&rr},
		}
		change := route53.Change{
			Action:            aws.String("UPSERT"),
			ResourceRecordSet: &rrset,
		}
		upserts = append(upserts, &change)
	}

	if args.dryRun {
		fmt.Println("Dry-run, upserts that would be made:")
		for _, upsert := range upserts {
			rr := upsert.ResourceRecordSet
			fmt.Printf("+ %s %s %v\n", *rr.Name, *rr.Type, *rr.ResourceRecords[0].Value)
		}
	} else {
		resp := batchChanges(upserts, []*route53.Change{}, zone)
		fmt.Printf("%d records upserted\n", len(upserts))

		if args.wait && resp != nil {
			waitForChange(resp.ChangeInfo)
		}
	}
}