Created
February 11, 2019 13:36
-
-
Save Yasuhisa/677baea3474c8f0406dddf0e726e7727 to your computer and use it in GitHub Desktop.
AssumeRole Sample using AWS SDK for Go.
This file contains 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 ( | |
"fmt" | |
"github.com/aws/aws-sdk-go/aws" | |
"github.com/aws/aws-sdk-go/aws/credentials" | |
"github.com/aws/aws-sdk-go/aws/credentials/stscreds" | |
"github.com/aws/aws-sdk-go/aws/session" | |
"github.com/aws/aws-sdk-go/service/ec2" | |
) | |
var ( | |
profile = "default" | |
region = "ap-northeast-1" | |
// FIXME: Rewrite your AWS Account ID and IAM Role Name. | |
roleArn = "arn:aws:iam::<123456789012>:role/<Your-Role-Name>" | |
) | |
// AssumeRoleWithSession returns switched role session from argument session and IAM role's arn in same region. | |
func AssumeRoleWithSession(sess *session.Session, rolearn string) *session.Session { | |
sCreds := stscreds.NewCredentials(sess, rolearn) | |
sConfig := aws.Config{Region: sess.Config.Region, Credentials: sCreds} | |
sSess := session.New(&sConfig) | |
return sSess | |
} | |
func main() { | |
// Get credentials from default(~/.aws/credentials) path. | |
// 開発環境などで使用している認証情報を取得する。 | |
creds := credentials.NewSharedCredentials("", profile) | |
config := aws.Config{Region: aws.String(region), Credentials: creds} | |
dSess := session.New(&config) | |
// Get the Switched Role Session. | |
// 本番環境など、開発環境で使用している認証情報を取得する。 | |
sSess := AssumeRoleWithSession(dSess, roleArn) | |
// Example: Get EC2 info using the switched session. | |
// 開発環境の認証情報から、本番環境の EC2 情報などが(IAM ロールの権限で許可された範囲内で)取得できる。 | |
result, _ := ec2.New(sSess).DescribeInstances(nil) | |
fmt.Println(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment