Skip to content

Instantly share code, notes, and snippets.

@gildas
Last active October 12, 2021 01:10
Show Gist options
  • Save gildas/03e744ee62bd4b58c6c6804a325bd622 to your computer and use it in GitHub Desktop.
Save gildas/03e744ee62bd4b58c6c6804a325bd622 to your computer and use it in GitHub Desktop.
Starts a new AWS session with an MFA Code
function New-AWSSession {
<#
.SYNOPSIS
Authenticates with AWS using MFA
.DESCRIPTION
Authenticates the current IAM user with AWS via the assigned MFA device
.PARAMETER MFA
The MFA Code to authenticate with
.PARAMETER Profile
The AWS Profile to authenticate or "Default" if absent
.EXAMPLE
New-AWSSession 123456
Authenticates the current IAM with the Default Profile and the MFA Code 123456
.EXAMPLE
New-AWSSession -MFA 123456
Authenticates the current IAM with the Default Profile and the MFA Code 123456
.EXAMPLE
New-AWSSession -Profile my-project 123456
Authenticates the current IAM with the "my-profile" Profile and the MFA Code 123456
.EXAMPLE
New-AWSSession 123456 my-project
Authenticates the current IAM with the "my-profile" Profile and the MFA Code 123456
#>
[CmdletBinding(ConfirmImpact='Low')]
Param(
[Parameter(Position=1, ValueFromPipeline, Mandatory=$true)]
[string] $MFA,
[Parameter(Position=2, Mandatory=$false)]
[string] $Profile = "Default"
)
$env:AWS_ACCESS_KEY_ID = ""
$env:AWS_SECRET_ACCESS_KEY = ""
$env:AWS_SESSION_TOKEN = ""
$env:AWS_SESSION_TOKEN_EXPIRATION = ""
$aws_identity = aws sts get-caller-identity --output json | ConvertFrom-Json
$aws_user = ($aws_identity.Arn -split("/"))[-1]
$aws_arn = "arn:aws:iam::$($aws_identity.Account):mfa/$aws_user"
Write-Verbose "Authenticating ARN $aws_arn"
$aws_creds = aws sts get-session-token --serial-number $aws_arn --token-code $MFA --duration-seconds 129600 --output json | ConvertFrom-Json
$env:AWS_ACCESS_KEY_ID = $aws_creds.Credentials.AccessKeyId
$env:AWS_SECRET_ACCESS_KEY = $aws_creds.Credentials.SecretAccessKey
$env:AWS_SESSION_TOKEN = $aws_creds.Credentials.SessionToken
$env:AWS_SESSION_TOKEN_EXPIRATION = $aws_creds.Credentials.Expiration
}
@gildas
Copy link
Author

gildas commented Sep 28, 2021

This function should be sourced in your environment

. .\new-aws-session.ps1

Or included in your PowerShell profile.ps1

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