Last active
April 12, 2019 04:27
-
-
Save andreigec/1c6672e679cec71efb9568cadf85b132 to your computer and use it in GitHub Desktop.
Assume or switch between aws roles, and generate aws keys for use with bash
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
<# | |
.SYNOPSIS | |
Assumes an AWS role based on the name configured in your ~/.aws/credentials file | |
.DESCRIPTION | |
Assumes an AWS role based on the name configured in your ~/.aws/credentials file | |
.PARAMETER profile | |
The name of the profile to assume (the item in your credentials file that has source_profile set) | |
.PARAMETER RoleSessionName | |
The name of the role to assume for that profile. Eg Admin | |
.EXAMPLE | |
Call this script with the parameters separated by spaces | |
#> | |
[CmdletBinding()] | |
Param( | |
[Parameter(Position=1)] | |
[string]$profile = "profile NOT SET", | |
[Parameter(Position=2)] | |
[string]$RoleSessionName = "RoleSessionName NOT SET", | |
[Parameter(Position=3)] | |
[string]$ARN = "ARN NOT SET" | |
) | |
$baseProfile = aws configure get "${profile}.source_profile" | |
echo "profile:$profile" | |
echo "RoleSessionName:$RoleSessionName" | |
echo "baseProfile:$baseProfile" | |
echo "ARN:$ARN" | |
$roleArn="arn:aws:iam::"+$ARN+":role/"+$RoleSessionName | |
Set-AWSCredential -ProfileName $baseProfile | |
Remove-Item -Path Env:AWS_ACCESS_KEY_ID | |
Remove-Item -Path Env:AWS_SECRET_ACCESS_KEY | |
Remove-Item -Path Env:AWS_SESSION_TOKEN | |
$Creds = (Use-STSRole -region ap-southeast-2 -RoleArn $roleArn -RoleSessionName $RoleSessionName).Credentials | |
Set-Item -Path Env:AWS_ACCESS_KEY_ID -Value $Creds.AccessKeyId | |
Set-Item -Path Env:AWS_SECRET_ACCESS_KEY -Value $Creds.SecretAccessKey | |
Set-Item -Path Env:AWS_SESSION_TOKEN -Value $Creds.SessionToken | |
Remove-Item -Path Env:AWS_PROFILE | |
Get-ChildItem Env:AWS_* | |
echo "-----copy below to auth in linux/bash-------`n`n" | |
Write-Host ("export AWS_ACCESS_KEY_ID={0}`nexport AWS_SECRET_ACCESS_KEY={1}`nexport AWS_SESSION_TOKEN={2}`n" -f $Creds.AccessKeyId,$Creds.SecretAccessKey,$Creds.SessionToken) | |
echo "Finished, press any key" | |
$KeyPress = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment