Skip to content

Commit

Permalink
feat: refresh AWS credentials periodically (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
kmushegi committed May 16, 2023
1 parent bb62e1e commit ffbba32
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
1 change: 1 addition & 0 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ func New(ctx context.Context, logger *zap.Logger, cfg Config) (*Api, error) {
}
// Refresh endpoints periodically
br.RefreshEndpointsPeriodically(ctx)
br.RefreshAWSCredentialsPeriodically(ctx, logger)

return &Api{
logger: logger,
Expand Down
39 changes: 38 additions & 1 deletion boltrouter/aws_credentials_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import (
"context"
"fmt"
"sync"
"time"

"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"go.uber.org/zap"
)

// awsCredentialsMap is used to cache aws credentials for a given region.
Expand All @@ -17,7 +19,6 @@ func getAwsCredentialsFromRegion(ctx context.Context, region string) (aws.Creden
if awsCred, ok := awsCredentialsMap.Load(region); ok {
return awsCred.(aws.Credentials), nil
}

return newAwsCredentialsFromRegion(ctx, region)
}

Expand All @@ -32,6 +33,42 @@ func newAwsCredentialsFromRegion(ctx context.Context, region string) (aws.Creden
if err != nil {
return aws.Credentials{}, fmt.Errorf("could not retrieve aws credentials: %w", err)
}

awsCredentialsMap.Store(awsConfig.Region, cred)
return cred, nil
}

func refreshAWSCredentials(ctx context.Context, logger *zap.Logger) {

awsCredentialsMap.Range(func(key, value interface{}) bool {
region := key.(string)
cred := value.(aws.Credentials)

if cred.CanExpire {
// if credential can expire, get new credentials for the region
refreshedCreds, err := newAwsCredentialsFromRegion(ctx, region)
if err != nil {
logger.Error(fmt.Sprintf("aws credential refresh failed for region %s", region), zap.Error(err))
return true
}
awsCredentialsMap.Store(region, refreshedCreds)
}
return true
})
}

func (br *BoltRouter) RefreshAWSCredentialsPeriodically(ctx context.Context, logger *zap.Logger) {
ticker := time.NewTicker(30 * time.Minute)

go func() {
for {
select {
case <-ctx.Done():
ticker.Stop()
return
case <-ticker.C:
refreshAWSCredentials(ctx, logger)
}
}
}()
}

0 comments on commit ffbba32

Please sign in to comment.