Skip to content

Commit

Permalink
add locking for credentials file. fixes #9
Browse files Browse the repository at this point in the history
  • Loading branch information
felixb committed Feb 28, 2018

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent c5fe7a9 commit 996367f
Showing 2 changed files with 24 additions and 4 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## swamp v0.6

* add locking for credentials file (#6)

## swamp v0.5.2

* enable cgo for default linux build
24 changes: 20 additions & 4 deletions swamp.go
Original file line number Diff line number Diff line change
@@ -14,6 +14,7 @@ import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/go-ini/ini"
"github.com/golang-utils/lockfile"
)

const (
@@ -63,11 +64,23 @@ func writeProfile(cred *sts.Credentials, targetProfile, region *string) {
}

awsPath := filepath.Join(usr.HomeDir, ".aws")
filename := filepath.Join(awsPath, "credentials")
credentialsPath := filepath.Join(awsPath, "credentials")
lockPath := filepath.Join(awsPath, ".credentials.lock")

cfg, err := ini.Load(filename)
// get a lock to prevent concurrent writes on credentials file
lock := lockfile.New()
for {
if err := lock.Lock(lockPath); err == nil {
break
} else {
fmt.Printf("Waiting for lock %s\n", lockPath)
time.Sleep(time.Second)
}
}

cfg, err := ini.Load(credentialsPath)
if err != nil {
fmt.Printf("Unable to find credentials file %s. Creating new file.\n", filename)
fmt.Printf("Unable to find credentials file %s. Creating new file.\n", credentialsPath)

if err := os.MkdirAll(awsPath, os.ModePerm); err != nil {
die("Error creating aws config path", err)
@@ -86,10 +99,13 @@ func writeProfile(cred *sts.Credentials, targetProfile, region *string) {
updateKey(sec, "aws_secret_access_key", cred.SecretAccessKey)
updateKey(sec, "aws_session_token", cred.SessionToken)

if err := cfg.SaveTo(filename); err != nil {
if err := cfg.SaveTo(credentialsPath); err != nil {
die("Error writing credentials file", err)
}

// release the lock manually
os.Remove(lockPath)

fmt.Printf("Wrote session token for profile %s\n", *targetProfile)
fmt.Printf("Token is valid until: %v\n", cred.Expiration)
}

0 comments on commit 996367f

Please sign in to comment.