本文整理匯總了Golang中github.com/aws/aws-sdk-go/aws.NewConfig函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewConfig函數的具體用法?Golang NewConfig怎麽用?Golang NewConfig使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewConfig函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: GetSession
// GetSessions returns the current session from the SessionProvider.
func (dsp *ConfigurableSessionProvider) GetSession() *session.Session {
dsp.sessionMutex.Lock()
defer dsp.sessionMutex.Unlock()
if dsp._session != nil {
return dsp._session
}
cfgs := []*aws.Config{
aws.NewConfig().WithRegion(dsp.ConfigRegion),
}
if dsp.ConfigAccessKey != "" {
cfgs = append(cfgs, aws.NewConfig().WithCredentials(credentials.NewStaticCredentials(
dsp.ConfigAccessKey,
dsp.ConfigSecretKey,
dsp.ConfigSessionToken,
)))
} else if !dsp.ConfigDisableENVCredentials {
// NOTE: We may want to init all credential providers in one config, as they might overwrite each other
cfgs = append(cfgs, aws.NewConfig().WithCredentials(credentials.NewCredentials(&credentials.EnvProvider{})))
} else {
panic("no valid configuration parameters for aws credentials found.")
}
dsp._session = session.New(cfgs...)
return dsp._session
}
示例2: Run
func (u *User) Run(args []string) int {
cli := iam.New(session.New(aws.NewConfig().WithRegion(u.config.Region)))
u.ListUsers(cli)
return 0
}
示例3: Start
// Start a test
func (t *Test) Start() <-chan queue.RegionsAggData {
awsConfig := aws.NewConfig().WithRegion(t.config.Regions[0])
if t.config.AwsProfile != "" {
creds := credentials.NewSharedCredentials("", t.config.AwsProfile)
if _, err := creds.Get(); err != nil {
log.Fatal(err)
}
awsConfig.WithCredentials(creds)
}
infra, err := infrastructure.New(t.config.Regions, awsConfig)
if err != nil {
log.Fatal(err)
}
t.invokeLambdas(awsConfig, infra.QueueURL())
results := make(chan queue.RegionsAggData)
go func() {
for result := range queue.Aggregate(awsConfig, infra.QueueURL(), t.config.TotalRequests) {
results <- result
}
infra.Clean()
close(results)
}()
return results
}
示例4: ListBuckets
func ListBuckets(region string) {
config := aws.NewConfig().WithRegion(region)
sess := session.New(config)
svc := s3.New(sess)
var params *s3.ListBucketsInput
resp, err := svc.ListBuckets(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.Prettify(resp))
}
示例5: listS3
func listS3(wg *sync.WaitGroup, index int, results chan<- []string) {
var creds *credentials.Credentials
if *accessFlag != "" && *secretFlag != "" {
creds = credentials.NewStaticCredentials(*accessFlag, *secretFlag, "")
} else {
creds = credentials.AnonymousCredentials
}
sess := session.New(aws.NewConfig().WithCredentials(creds).WithRegion(*regionFlag).WithEndpoint(*endpointFlag).WithS3ForcePathStyle(true))
prefix := fmt.Sprintf("%s%x", *prefixFlag, index)
svc := s3.New(sess)
inputparams := &s3.ListObjectsInput{
Bucket: aws.String(*bucketFlag),
Prefix: aws.String(prefix),
}
result := make([]string, 0, 1000)
svc.ListObjectsPages(inputparams, func(page *s3.ListObjectsOutput, lastPage bool) bool {
for _, value := range page.Contents {
result = append(result, *value.Key)
}
if lastPage {
results <- result
wg.Done()
return false
} else {
return true
}
})
}
示例6: CreateRecord
// CreateRecord for hosted zone id
func CreateRecord(zone string, record string, dest string) error {
svc := route53.New(session.New(), aws.NewConfig())
_, err := svc.ChangeResourceRecordSets(&route53.ChangeResourceRecordSetsInput{
ChangeBatch: &route53.ChangeBatch{
Changes: []*route53.Change{
{
Action: aws.String("CREATE"),
ResourceRecordSet: &route53.ResourceRecordSet{
Name: aws.String(record),
Type: aws.String("A"),
ResourceRecords: []*route53.ResourceRecord{
{
Value: aws.String(dest),
},
},
TTL: aws.Int64(60),
},
},
},
Comment: aws.String("ResourceDescription"),
},
HostedZoneId: aws.String(zone),
})
return err
}
示例7: init
func init() {
gucumber.Before("@efs", func() {
// FIXME remove custom region
gucumber.World["client"] = efs.New(smoke.Session,
aws.NewConfig().WithRegion("us-west-2"))
})
}
示例8: preRun
// PreRun sets up global tasks used for most commands, some use PreRunNoop
// to remove this default behaviour.
func preRun(c *cobra.Command, args []string) error {
if l, err := log.ParseLevel(logLevel); err == nil {
log.SetLevel(l)
}
config := aws.NewConfig()
if profile != "" {
config = config.WithCredentials(credentials.NewSharedCredentials("", profile))
}
Session = session.New(config)
Project = &project.Project{
Log: log.Log,
Path: ".",
}
if dryRun {
log.SetLevel(log.WarnLevel)
Project.Service = dryrun.New(Session)
Project.Concurrency = 1
} else {
Project.Service = lambda.New(Session)
}
if chdir != "" {
if err := os.Chdir(chdir); err != nil {
return err
}
}
return Project.Open()
}
示例9: createConf
func createConf() *aws.Config {
conf := aws.NewConfig()
if config.Log.LogDebug == config.Log_Flag_OFF {
conf.WithLogLevel(aws.LogOff)
} else {
loglevel := aws.LogDebug
if config.Log.LogSigning == config.Log_Flag_ON {
loglevel |= aws.LogDebugWithSigning
}
if config.Log.LogHTTPBody == config.Log_Flag_ON {
loglevel |= aws.LogDebugWithHTTPBody
}
if config.Log.LogRequestRetries == config.Log_Flag_ON {
loglevel |= aws.LogDebugWithRequestRetries
}
if config.Log.LogRequestErrors == config.Log_Flag_ON {
loglevel |= aws.LogDebugWithRequestErrors
}
conf.WithLogLevel(loglevel)
}
return conf
}
示例10: preRun
func (pv *PersistentValues) preRun(c *cobra.Command, args []string) {
if l, err := log.ParseLevel(pv.LogLevel); err == nil {
log.SetLevel(l)
}
pv.session = session.New(aws.NewConfig())
pv.project = &project.Project{
Log: log.Log,
Path: ".",
}
if pv.DryRun {
log.SetLevel(log.WarnLevel)
pv.project.Service = dryrun.New(pv.session)
pv.project.Concurrency = 1
} else {
pv.project.Service = lambda.New(pv.session)
}
if pv.Chdir != "" {
if err := os.Chdir(pv.Chdir); err != nil {
log.Fatalf("error: %s", err)
}
}
if err := pv.project.Open(); err != nil {
log.Fatalf("error opening project: %s", err)
}
}
示例11: NewAwsAsgEbs
func NewAwsAsgEbs(maxRetries int) *AwsAsgEbs {
awsAsgEbs := &AwsAsgEbs{}
metadata := ec2metadata.New(session.New())
region, err := metadata.Region()
if err != nil {
log.WithFields(log.Fields{"error": err}).Fatal("Failed to get region from instance metadata")
}
log.WithFields(log.Fields{"region": region}).Info("Setting region")
awsAsgEbs.Region = region
availabilityZone, err := metadata.GetMetadata("placement/availability-zone")
if err != nil {
log.WithFields(log.Fields{"error": err}).Fatal("Failed to get availability zone from instance metadata")
}
log.WithFields(log.Fields{"az": availabilityZone}).Info("Setting availability zone")
awsAsgEbs.AvailabilityZone = availabilityZone
instanceId, err := metadata.GetMetadata("instance-id")
if err != nil {
log.WithFields(log.Fields{"error": err}).Fatal("Failed to get instance id from instance metadata")
}
log.WithFields(log.Fields{"instance_id": instanceId}).Info("Setting instance id")
awsAsgEbs.InstanceId = instanceId
awsAsgEbs.AwsConfig = aws.NewConfig().
WithRegion(region).
WithCredentials(ec2rolecreds.NewCredentials(session.New())).
WithMaxRetries(maxRetries)
return awsAsgEbs
}
示例12: Init
func (r *Route53Provider) Init(rootDomainName string) error {
var region, accessKey, secretKey string
if region = os.Getenv("AWS_REGION"); len(region) == 0 {
return fmt.Errorf("AWS_REGION is not set")
}
if accessKey = os.Getenv("AWS_ACCESS_KEY"); len(accessKey) == 0 {
return fmt.Errorf("AWS_ACCESS_KEY is not set")
}
if secretKey = os.Getenv("AWS_SECRET_KEY"); len(secretKey) == 0 {
return fmt.Errorf("AWS_SECRET_KEY is not set")
}
// Comply with the API's 5 req/s rate limit. If there are other
// clients using the same account the AWS SDK will throttle the
// requests automatically if the global rate limit is exhausted.
r.limiter = ratelimit.NewBucketWithRate(5.0, 1)
creds := credentials.NewStaticCredentials(accessKey, secretKey, "")
config := aws.NewConfig().WithMaxRetries(route53MaxRetries).
WithCredentials(creds).
WithRegion(region)
r.client = awsRoute53.New(session.New(config))
if err := r.setHostedZone(rootDomainName); err != nil {
return err
}
logrus.Infof("Configured %s with hosted zone %s in region %s",
r.GetName(), rootDomainName, region)
return nil
}
示例13: presignURL
// presignURL will presign the request by using SoureRegion to sign with. SourceRegion is not
// sent to the service, and is only used to not have the SDKs parsing ARNs.
func presignURL(r *request.Request, sourceRegion *string, newParams interface{}) *string {
cfg := r.Config.Copy(aws.NewConfig().
WithEndpoint("").
WithRegion(aws.StringValue(sourceRegion)))
clientInfo := r.ClientInfo
resolved, err := r.Config.EndpointResolver.EndpointFor(
clientInfo.ServiceName, aws.StringValue(cfg.Region),
func(opt *endpoints.Options) {
opt.DisableSSL = aws.BoolValue(cfg.DisableSSL)
opt.UseDualStack = aws.BoolValue(cfg.UseDualStack)
},
)
if err != nil {
r.Error = err
return nil
}
clientInfo.Endpoint = resolved.URL
clientInfo.SigningRegion = resolved.SigningRegion
// Presign a request with modified params
req := request.New(*cfg, clientInfo, r.Handlers, r.Retryer, r.Operation, newParams, r.Data)
req.Operation.HTTPMethod = "GET"
uri, err := req.Presign(5 * time.Minute) // 5 minutes should be enough.
if err != nil { // bubble error back up to original request
r.Error = err
return nil
}
// We have our URL, set it on params
return &uri
}
示例14: stackConfig
func (c Cluster) stackConfig(opts StackTemplateOptions, compressUserData bool) (*stackConfig, error) {
assets, err := ReadTLSAssets(opts.TLSAssetsDir)
if err != nil {
return nil, err
}
stackConfig := stackConfig{}
if stackConfig.Config, err = c.Config(); err != nil {
return nil, err
}
awsConfig := aws.NewConfig()
awsConfig = awsConfig.WithRegion(stackConfig.Config.Region)
kmsSvc := kms.New(session.New(awsConfig))
compactAssets, err := assets.compact(stackConfig.Config, kmsSvc)
if err != nil {
return nil, fmt.Errorf("failed to compress TLS assets: %v", err)
}
stackConfig.Config.TLSConfig = compactAssets
if stackConfig.UserDataWorker, err = execute(opts.WorkerTmplFile, stackConfig.Config, compressUserData); err != nil {
return nil, fmt.Errorf("failed to render worker cloud config: %v", err)
}
if stackConfig.UserDataController, err = execute(opts.ControllerTmplFile, stackConfig.Config, compressUserData); err != nil {
return nil, fmt.Errorf("failed to render controller cloud config: %v", err)
}
return &stackConfig, nil
}
示例15: ValidateRegion
// ValidateRegion checks that an AWS region name is valid
func ValidateRegion(region string) error {
glog.V(2).Infof("Querying EC2 for all valid regions")
request := &ec2.DescribeRegionsInput{}
config := aws.NewConfig().WithRegion("us-east-1")
client := ec2.New(session.New(), config)
response, err := client.DescribeRegions(request)
if err != nil {
return fmt.Errorf("Got an error while querying for valid regions (verify your AWS credentials?)")
}
for _, r := range response.Regions {
name := aws.StringValue(r.RegionName)
if name == region {
return nil
}
}
if os.Getenv("SKIP_REGION_CHECK") != "" {
glog.Infof("AWS region does not appear to be valid, but skipping because SKIP_REGION_CHECK is set")
return nil
}
return fmt.Errorf("Region is not a recognized EC2 region: %q (check you have specified valid zones?)", region)
}