tail -f /dev/null

産まれたばかりの仔羊. If you haven't had any obstacles lately, you're not challenging. be the worst.

PowerShell で A -> B account へ STSRole

PowerShell で実施する手順をメモ.

# Import AWS module.
Set-ExecutionPolicy RemoteSigned
Import-Module AWSPowerShell

# Set AWS credentials.
Set-AWSCredential -AccessKey xxx -SecretKey xxx -StoreAs A_default
Set-AWSCredentials -ProfileName A_default
Initialize-AWSDefaults -ProfileName A_default -Region ap-northeast-1
Set-DefaultAWSRegion ap-northeast-1

# Get AWS credentials.
$tokenCode = Read-Host "enter A_default mfa device token code"
$cred = (Use-STSRole -RoleArn arn:aws:iam::<B_aws_account_id>:role/<B_iam_role> -RoleSessionName xxx -SerialNumber "arn:aws:iam::<A_aws_account_id>:mfa/<A_iam_user_name>" -TokenCode $tokenCode).Credentials

# Check if this cred can get s3 object. 
$bucketName = "examp1e-bucket"
$key="000/111/test.jpg"
Get-S3Object -BucketName $bucketName -MaxKeys 10 -Credential $cred
Get-S3Object -BucketName $bucketName -Key $key -Credential $cred
ETag         : "2123908r4023784y23u0049u230"
BucketName   : examp1e-bucket
Key          : 000/111/test.jpg
LastModified : 2019/04/12 16:26:17
Owner        : Amazon.S3.Model.Owner
Size         : 45
StorageClass : STANDARD

環境変数に $cred の各種機微情報を格納しても -Credential $cred で指定しないと default の key (A) を向いてしまうようで Access Denied となった.

$env:AWS_ACCESS_KEY_ID=$cred.AccessKeyId
$env:AWS_SECRET_ACCESS_KEY=$cred.SecretAccessKey
$env:AWS_SESSION_TOKEN=$cred.SessionToken