LoginSignup
10
5

More than 5 years have passed since last update.

aws-sdk-goでEC2のIAMロールとAWS認証情報ファイルの両方に対応する

Last updated at Posted at 2017-02-19

Amazon Elasticsearch Service用の認証プロキシを作る際に、クレデンシャルの取得部分でとてもハマったのでメモしておきます。

assumerole用とかアクセスキー用とかのプロバイダもあるので、それらを組み合わせればAWSCLIと同等のものを簡単にれるかと思います。

コードとしてはこの辺でやってます。
https://github.com/ikeisuke/amzn-es-proxy/blob/master/signer.go#L29

EC2のIAMロールのクレデンシャルの取得

ec2m := ec2metadata.New(session.New(), &aws.Config{
    HTTPClient: &http.Client{Timeout: time.Second},
})
creds := ec2rolecreds.EC2RoleProvider{
    Client: ec2m,
}

AWS認証情報ファイルからの取得

creds := credentials.SharedCredentialsProvider{
    Profile: profile,
}

二つをまとめて1つのクレデンシャルとして取得

ec2m := ec2metadata.New(session.New(), &aws.Config{
    HTTPClient: &http.Client{Timeout: time.Second},
})
creds := credentials.NewChainCredentials([]credentials.Provider{
    &credentials.SharedCredentialsProvider{
        Profile: profile,
    },
    &ec2rolecreds.EC2RoleProvider{
        Client: ec2m,
    },
})
10
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5