Skip to content

Instantly share code, notes, and snippets.

@inokappa
Created July 8, 2017 01:04
Show Gist options
  • Save inokappa/5b236aa1bf93394a4072686496024790 to your computer and use it in GitHub Desktop.
Save inokappa/5b236aa1bf93394a4072686496024790 to your computer and use it in GitHub Desktop.
Assume Role して環境変数にセットしつつ引数で指定したコマンドを実行するやつ
package main
import (
"os"
"os/exec"
"fmt"
"flag"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/service/sts"
)
var (
argProfile = flag.String("profile", "", "AWS Shared Credential の Profile 名を指定する")
argRegion = flag.String("region", "ap-northeast-1", "AWS Region 名を指定する")
argCommand = flag.String("command", "", "指定したコマンドを実行する")
argRoleArn = flag.String("role_arn", "", "Role Arn を指定する")
argRoleSessionName = flag.String("role_session_name", "RoleSession", "Role Session Name を指定する")
argDurationSeconds = flag.Int64("duration", 900, "Duration Seconds を指定する")
)
func exec_command(command string, access_key_id string, secret_access_key string, session_token string) {
cmd := exec.Command("sh", "-c", command)
env := os.Environ()
env = append(env, fmt.Sprintf("AWS_ACCESS_KEY_ID=%s", access_key_id))
env = append(env, fmt.Sprintf("AWS_SECRET_ACCESS_KEY=%s", secret_access_key))
env = append(env, fmt.Sprintf("AWS_SECURITY_TOKEN=%s", session_token))
cmd.Env = env
out, err := cmd.Output()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(string(out))
}
func aws_sts_client(profile string, region string) *sts.STS {
var config aws.Config
if profile != "" {
creds := credentials.NewSharedCredentials("", profile)
config = aws.Config{Region: aws.String(region), Credentials: creds}
} else {
config = aws.Config{Region: aws.String(region)}
}
sess := session.New(&config)
sts_client := sts.New(sess)
return sts_client
}
func main() {
flag.Parse()
sts_client := aws_sts_client(*argProfile, *argRegion)
params := &sts.AssumeRoleInput{
DurationSeconds: aws.Int64(*argDurationSeconds),
RoleArn: aws.String(*argRoleArn),
RoleSessionName: aws.String(*argRoleSessionName),
}
res, err := sts_client.AssumeRole(params)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
access_key_id := *res.Credentials.AccessKeyId
secret_access_key := *res.Credentials.SecretAccessKey
session_token := *res.Credentials.SessionToken
if *argCommand != "" {
exec_command(*argCommand, access_key_id, secret_access_key, session_token)
} else {
fmt.Println("AWS_ACCESS_KEY_ID : " + access_key_id)
fmt.Println("AWS_SECRET_ACCESS_KEY : " + secret_access_key)
fmt.Println("AWS_SECURITY_TOKEN : " + session_token)
}
}
@inokappa
Copy link
Author

inokappa commented Jul 8, 2017

以下のように実行する。

./oreno-assume -role_arn arn:aws:iam::xxxxxxxx0001:role/role-01 -command "aws s3 ls s3://foobar/"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment