Skip to content

Commit

Permalink
move http calls to help function, support ecs and instance keys
Browse files Browse the repository at this point in the history
  • Loading branch information
ajbeach2 committed Dec 31, 2018
1 parent 864ae0b commit 6f77db9
Showing 1 changed file with 39 additions and 24 deletions.
63 changes: 39 additions & 24 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,10 @@ type mdCreds struct {
Expiration string
}

// InstanceKeys Requests the AWS keys from the instance-based metadata on EC2
// Assumes only one IAM role.
func InstanceKeys() (keys Keys, err error) {

rolePath := "http://169.254.169.254/latest/meta-data/iam/security-credentials/"
// Helper funciton to make a get request to a role path
func getRoleCredentials(roleUrl string) (keys Keys, err error) {
var creds mdCreds

// request the role name for the instance
// assumes there is only one
resp, err := ClientWithTimeout(2 * time.Second).Get(rolePath)
resp, err := http.Get(roleUrl)
if err != nil {
return
}
Expand All @@ -45,14 +39,42 @@ func InstanceKeys() (keys Keys, err error) {
err = newRespError(resp)
return
}
role, err := ioutil.ReadAll(resp.Body)

metadata, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}

// request the credential metadata for the role
resp, err = http.Get(rolePath + string(role))
if err = json.Unmarshal([]byte(metadata), &creds); err != nil {
return
}
keys = Keys{
AccessKey: creds.AccessKeyID,
SecretKey: creds.SecretAccessKey,
SecurityToken: creds.Token,
}

return
}

// ECSKeys gets credentials from a diffrent ip for ecs task roles
// for use inside ECS task containers.
// See https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html
func ECSKeys() (keys Keys, err error) {
roleUri := os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")
rolePath := fmt.Sprint("169.254.170.2", roleUri)

return getRoleCredentials(rolePath)
}

// InstanceKeys Requests the AWS keys from the instance-based metadata on EC2
// Assumes only one IAM role.
func InstanceKeys() (keys Keys, err error) {

rolePath := "http://169.254.169.254/latest/meta-data/iam/security-credentials/"

// request the role name for the instance
// assumes there is only one
resp, err := ClientWithTimeout(2 * time.Second).Get(rolePath)
if err != nil {
return
}
Expand All @@ -61,21 +83,14 @@ func InstanceKeys() (keys Keys, err error) {
err = newRespError(resp)
return
}
metadata, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
role, err := ioutil.ReadAll(resp.Body)

if err = json.Unmarshal([]byte(metadata), &creds); err != nil {
if err != nil {
return
}
keys = Keys{
AccessKey: creds.AccessKeyID,
SecretKey: creds.SecretAccessKey,
SecurityToken: creds.Token,
}

return
// request the credential metadata for the role
return getRoleCredentials(rolePath + string(role))
}

// EnvKeys Reads the AWS keys from the environment
Expand Down

0 comments on commit 6f77db9

Please sign in to comment.