Created
October 4, 2018 02:25
-
-
Save ysugimoto/04a72007bf87b5b5c06385af16dbf31e to your computer and use it in GitHub Desktop.
Get IAM profile credentials for golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"context" | |
"errors" | |
"fmt" | |
"time" | |
"encoding/json" | |
"net/http" | |
) | |
const ( | |
securityCredentialURL = "http://169.254.169.254/latest/meta-data/iam/security-credentials/" | |
) | |
type Credential struct { | |
AccessKeyId string `json:"AccessKeyId"` | |
SecretAccessKey string `json:"SecretAccessKey"` | |
} | |
func main() { | |
credential, err := getCredential("") | |
fmt.Println(Credential, err) | |
} | |
func getCredential(profile string) (Credential, error) { | |
root := context.Background() | |
var c Credential | |
if role == "" { | |
var err error | |
if role, err = getProfileFromList(root); err != nil { | |
return cred, err | |
} | |
} | |
req, err := http.NewRequest("GET", securityCredentialURL+role, nil) | |
if err != nil { | |
return c, err | |
} | |
ctx, cancel := context.WithTimeout(root, 100*time.Millisecond) | |
defer cancel() | |
resp, err := http.DefaultClient.Do(req.WithContext(ctx)) | |
if err != nil { | |
return c, err | |
} | |
defer resp.Body.Close() | |
err = json.NewDecoder(resp.Body).Decode(&c) | |
return cred, err | |
} | |
func getProfileFromList(root context.Context) (string, error) { | |
req, err := http.NewClient("GET", securityCredentialURL, nil) | |
if err != nil { | |
return "", err | |
} | |
ctx, cancel := context.WithTimeout(root, 100*time.Millisecond) | |
defer cancel() | |
resp, err := http.DefaultClient.Do(req.WithContext(ctx)) | |
if err != nil { | |
return "", err | |
} | |
defer resp.Body.Close() | |
// Returns first profile | |
scanner := bufio.NewScanner(resp.Body) | |
for scanner.Scan() { | |
return scanner.Text(), nil | |
} | |
return "", errors.New("IAM profile is empty") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment