Skip to content

Commit

Permalink
Update example code for Session with Shared Config
Browse files Browse the repository at this point in the history
  • Loading branch information
jasdel committed Aug 2, 2016
1 parent beae13f commit f1b8d6b
Show file tree
Hide file tree
Showing 97 changed files with 14,836 additions and 2,487 deletions.
9 changes: 5 additions & 4 deletions aws/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,11 +130,12 @@ type Config struct {
// client to create a new http.Client. This options is only meaningful if you're not
// already using a custom HTTP client with the SDK. Enabled by default.
//
// Must be set and provided to the session.New() in order to disable the EC2Metadata
// overriding the timeout for default credentials chain.
// Must be set and provided to the session.NewSession() in order to disable
// the EC2Metadata overriding the timeout for default credentials chain.
//
// Example:
// sess := session.New(aws.NewConfig().WithEC2MetadataDiableTimeoutOverride(true))
// sess, err := session.NewSession(aws.NewConfig().WithEC2MetadataDiableTimeoutOverride(true))
//
// svc := s3.New(sess)
//
EC2MetadataDisableTimeoutOverride *bool
Expand All @@ -150,7 +151,7 @@ type Config struct {
// NewConfig returns a new Config pointer that can be chained with builder methods to
// set multiple configuration values inline without using pointers.
//
// sess := session.New(aws.NewConfig().WithRegion("us-west-2").WithMaxRetries(10))
// sess, err := session.NewSession(aws.NewConfig().WithRegion("us-west-2").WithMaxRetries(10))
//
func NewConfig() *Config {
return &Config{}
Expand Down
4 changes: 2 additions & 2 deletions aws/corehandlers/param_validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/corehandlers"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/awstesting/unit"
"github.com/aws/aws-sdk-go/service/kinesis"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -242,7 +242,7 @@ func BenchmarkValidateAny(b *testing.B) {
input.Records = append(input.Records, record)
}

req, _ := kinesis.New(session.New()).PutRecordsRequest(input)
req, _ := kinesis.New(unit.Session).PutRecordsRequest(input)

b.ResetTimer()
for i := 0; i < b.N; i++ {
Expand Down
12 changes: 6 additions & 6 deletions aws/credentials/ec2rolecreds/ec2_role_provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/awstesting/unit"
)

const credsRespTmpl = `{
Expand Down Expand Up @@ -55,7 +55,7 @@ func TestEC2RoleProvider(t *testing.T) {
defer server.Close()

p := &ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")}),
Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}),
}

creds, err := p.Retrieve()
Expand All @@ -71,7 +71,7 @@ func TestEC2RoleProviderFailAssume(t *testing.T) {
defer server.Close()

p := &ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")}),
Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}),
}

creds, err := p.Retrieve()
Expand All @@ -92,7 +92,7 @@ func TestEC2RoleProviderIsExpired(t *testing.T) {
defer server.Close()

p := &ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")}),
Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}),
}
p.CurrentTime = func() time.Time {
return time.Date(2014, 12, 15, 21, 26, 0, 0, time.UTC)
Expand All @@ -117,7 +117,7 @@ func TestEC2RoleProviderExpiryWindowIsExpired(t *testing.T) {
defer server.Close()

p := &ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")}),
Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}),
ExpiryWindow: time.Hour * 1,
}
p.CurrentTime = func() time.Time {
Expand All @@ -143,7 +143,7 @@ func BenchmarkEC3RoleProvider(b *testing.B) {
defer server.Close()

p := &ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")}),
Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}),
}
_, err := p.Retrieve()
if err != nil {
Expand Down
20 changes: 10 additions & 10 deletions aws/ec2metadata/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/awstesting/unit"
)

const instanceIdentityDocument = `{
Expand Down Expand Up @@ -61,7 +61,7 @@ func initTestServer(path string, resp string) *httptest.Server {
}

func TestEndpoint(t *testing.T) {
c := ec2metadata.New(session.New())
c := ec2metadata.New(unit.Session)
op := &request.Operation{
Name: "GetMetadata",
HTTPMethod: "GET",
Expand All @@ -79,7 +79,7 @@ func TestGetMetadata(t *testing.T) {
"success", // real response includes suffix
)
defer server.Close()
c := ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")})
c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")})

resp, err := c.GetMetadata("some/path")

Expand All @@ -93,7 +93,7 @@ func TestGetRegion(t *testing.T) {
"us-west-2a", // real response includes suffix
)
defer server.Close()
c := ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")})
c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")})

region, err := c.Region()

Expand All @@ -107,7 +107,7 @@ func TestMetadataAvailable(t *testing.T) {
"instance-id",
)
defer server.Close()
c := ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")})
c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")})

available := c.Available()

Expand All @@ -120,7 +120,7 @@ func TestMetadataIAMInfo_success(t *testing.T) {
validIamInfo,
)
defer server.Close()
c := ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")})
c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")})

iamInfo, err := c.IAMInfo()
assert.NoError(t, err)
Expand All @@ -135,7 +135,7 @@ func TestMetadataIAMInfo_failure(t *testing.T) {
unsuccessfulIamInfo,
)
defer server.Close()
c := ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")})
c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")})

iamInfo, err := c.IAMInfo()
assert.NotNil(t, err)
Expand All @@ -145,7 +145,7 @@ func TestMetadataIAMInfo_failure(t *testing.T) {
}

func TestMetadataNotAvailable(t *testing.T) {
c := ec2metadata.New(session.New())
c := ec2metadata.New(unit.Session)
c.Handlers.Send.Clear()
c.Handlers.Send.PushBack(func(r *request.Request) {
r.HTTPResponse = &http.Response{
Expand All @@ -163,7 +163,7 @@ func TestMetadataNotAvailable(t *testing.T) {
}

func TestMetadataErrorResponse(t *testing.T) {
c := ec2metadata.New(session.New())
c := ec2metadata.New(unit.Session)
c.Handlers.Send.Clear()
c.Handlers.Send.PushBack(func(r *request.Request) {
r.HTTPResponse = &http.Response{
Expand All @@ -185,7 +185,7 @@ func TestEC2RoleProviderInstanceIdentity(t *testing.T) {
instanceIdentityDocument,
)
defer server.Close()
c := ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")})
c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")})

doc, err := c.GetInstanceIdentityDocument()
assert.Nil(t, err, "Expect no error, %v", err)
Expand Down
13 changes: 6 additions & 7 deletions aws/ec2metadata/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,24 @@ import (

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/awstesting/unit"
"github.com/stretchr/testify/assert"
)

func TestClientOverrideDefaultHTTPClientTimeout(t *testing.T) {
svc := ec2metadata.New(session.New())
svc := ec2metadata.New(unit.Session)

assert.NotEqual(t, http.DefaultClient, svc.Config.HTTPClient)
assert.Equal(t, 5*time.Second, svc.Config.HTTPClient.Timeout)
}

func TestClientNotOverrideDefaultHTTPClientTimeout(t *testing.T) {
origClient := *http.DefaultClient
http.DefaultClient.Transport = &http.Transport{}
defer func() {
http.DefaultClient = &origClient
http.DefaultClient.Transport = nil
}()

svc := ec2metadata.New(session.New())
svc := ec2metadata.New(unit.Session)

assert.Equal(t, http.DefaultClient, svc.Config.HTTPClient)

Expand All @@ -38,7 +37,7 @@ func TestClientNotOverrideDefaultHTTPClientTimeout(t *testing.T) {
}

func TestClientDisableOverrideDefaultHTTPClientTimeout(t *testing.T) {
svc := ec2metadata.New(session.New(aws.NewConfig().WithEC2MetadataDisableTimeoutOverride(true)))
svc := ec2metadata.New(unit.Session, aws.NewConfig().WithEC2MetadataDisableTimeoutOverride(true))

assert.Equal(t, http.DefaultClient, svc.Config.HTTPClient)
}
Expand Down Expand Up @@ -69,7 +68,7 @@ func runEC2MetadataClients(t *testing.T, cfg *aws.Config, atOnce int) {
wg.Add(atOnce)
for i := 0; i < atOnce; i++ {
go func() {
svc := ec2metadata.New(session.New(), cfg)
svc := ec2metadata.New(unit.Session, cfg)
_, err := svc.Region()
assert.NoError(t, err)
wg.Done()
Expand Down
4 changes: 2 additions & 2 deletions awstesting/mock/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import (
)

// Session is a mock session which is used to hit the mock server
var Session = session.New(&aws.Config{
var Session = session.Must(session.NewSession(&aws.Config{
DisableSSL: aws.Bool(true),
Endpoint: aws.String(server.URL[7:]),
})
}))

// server is the mock server that simply writes a 200 status back to the client
var server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down
8 changes: 4 additions & 4 deletions awstesting/performance/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/awstesting/unit"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)
Expand Down Expand Up @@ -75,18 +75,18 @@ type outputer interface {
type dynamodbOut struct {
table string // table to write to in dynamodb
region string
db *dynamodb.DynamoDB // the dynamodb session
db *dynamodb.DynamoDB // the dynamodb
}

// init initializes dynamodbOut to have a new session
// init initializes dynamodbOut
func newDynamodbOut(table, region string) *dynamodbOut {
out := dynamodbOut{
table: table,
region: region,
}

out.db = dynamodb.New(
session.New(),
unit.Session,
&aws.Config{Region: &out.region},
)
return &out
Expand Down
4 changes: 2 additions & 2 deletions awstesting/unit/unit.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ import (
)

// Session is a shared session for unit tests to use.
var Session = session.New(aws.NewConfig().
var Session = session.Must(session.NewSession(aws.NewConfig().
WithCredentials(credentials.NewStaticCredentials("AKID", "SECRET", "SESSION")).
WithRegion("mock-region"))
WithRegion("mock-region")))
14 changes: 10 additions & 4 deletions example/service/ec2/filterInstances/filter_ec2_by_tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,28 @@ package main

import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"log"
"os"
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)

// This example will list instances with a filter
//
// Usage:
// go run filter_ec2_by_tag.go <name_filter>
func main() {
sess, err := session.NewSession()
if err != nil {
log.Fatalf("failed to create session %v\n", err)
}

nameFilter := os.Args[1]
awsRegion := "us-east-1"
svc := ec2.New(session.New(&aws.Config{Region: aws.String(awsRegion)}))
svc := ec2.New(sess, &aws.Config{Region: aws.String(awsRegion)})
fmt.Printf("listing instances with tag %v in: %v\n", nameFilter, awsRegion)
params := &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
Expand Down
8 changes: 6 additions & 2 deletions example/service/s3/listObjects/listObjects.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,16 @@ import (
// Usage:
// go run listObjects.go <bucket>
func main() {
sess := session.New()
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}

svc := s3.New(sess)

i := 0
err := svc.ListObjectsPages(&s3.ListObjectsInput{
err = svc.ListObjectsPages(&s3.ListObjectsInput{
Bucket: &os.Args[1],
}, func(p *s3.ListObjectsOutput, last bool) (shouldContinue bool) {
fmt.Println("Page,", i)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
Expand All @@ -32,11 +31,18 @@ func main() {
for _, acc := range accounts {
wg.Add(1)
go func(acc string) {
sess := session.New(&aws.Config{Credentials: credentials.NewSharedCredentials("", acc)})
if err := getAccountBuckets(sess, bucketCh, acc); err != nil {
defer wg.Done()

sess, err := session.NewSessionWithOptions(session.Options{
Profile: acc,
})
if err != nil {
fmt.Fprintf(os.Stderr, "failed to create session for account, %d, %v\n", acc, err)
return
}
if err = getAccountBuckets(sess, bucketCh, acc); err != nil {
fmt.Fprintf(os.Stderr, "failed to get account %s's bucket info, %v\n", acc, err)
}
wg.Done()
}(acc)
}
// Spin off a goroutine which will wait until all account buckets have been collected and
Expand Down
8 changes: 3 additions & 5 deletions models/protocol_tests/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ var extraImports = []string{
"net/url",
"",
"github.com/aws/aws-sdk-go/awstesting",
"github.com/aws/aws-sdk-go/aws/session",
"github.com/aws/aws-sdk-go/awstesting/unit",
"github.com/aws/aws-sdk-go/private/protocol",
"github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil",
"github.com/aws/aws-sdk-go/private/util",
Expand Down Expand Up @@ -125,8 +125,7 @@ func (t *testSuite) TestSuite() string {

var tplInputTestCase = template.Must(template.New("inputcase").Parse(`
func Test{{ .OpName }}(t *testing.T) {
sess := session.New()
svc := New{{ .TestCase.TestSuite.API.StructName }}(sess, &aws.Config{Endpoint: aws.String("https://test")})
svc := New{{ .TestCase.TestSuite.API.StructName }}(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
{{ if ne .ParamsString "" }}input := {{ .ParamsString }}
req, _ := svc.{{ .TestCase.Given.ExportedName }}Request(input){{ else }}req, _ := svc.{{ .TestCase.Given.ExportedName }}Request(nil){{ end }}
r := req.HTTPRequest
Expand Down Expand Up @@ -197,8 +196,7 @@ func (t tplInputTestCaseData) BodyAssertions() string {

var tplOutputTestCase = template.Must(template.New("outputcase").Parse(`
func Test{{ .OpName }}(t *testing.T) {
sess := session.New()
svc := New{{ .TestCase.TestSuite.API.StructName }}(sess, &aws.Config{Endpoint: aws.String("https://test")})
svc := New{{ .TestCase.TestSuite.API.StructName }}(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte({{ .Body }}))
req, out := svc.{{ .TestCase.Given.ExportedName }}Request(nil)
Expand Down
Loading

0 comments on commit f1b8d6b

Please sign in to comment.