Forcing Powershell scripts to use AWS MFA

Finally, I get to do some “real” AWS work.

So after getting my credentials,  for this new account, it turns out that they don’t let people get access keys.   Yep, it’s a security risk.  So to minimize it, I created simple policy to disallow 99% of the items except for the ability to read your MFA token ID.   (iam:ListMFADevices)

So the policy I created is below:


 "Version": "2012-10-17",
 "Statement": [
    "Sid": "DenyWhenMFAIsNotPresent",
    "Effect": "Deny",
    "NotAction": "iam:ListMFADevices",
    "Resource": "*",
    "Condition": {
     "BoolIfExists": {
      "aws:MultiFactorAuthPresent": false

Also remember you need to grant yourself the proper rights in another policy, so that you can do what you need to do.

So if you have your Powershell set up to run with multiple credentials, it’s easy to switch between them, you have to get a temporary token by calling Get-STSSessionToken

Get-AWSCredential -ListProfileDetail
#changes context to run as that id, same as -credential on all aws commands
Set-AWSCredential -ProfileName <whatever>

#saves credentail for future use
Set-AWSCredential -ProfileName <whatever> -StoreAs <something>
#sets up a new session to use MFA session

$MFASession=Get-STSSessionToken -SerialNumber (Get-IAMMFADevice).SerialNumber -TokenCode  <CurrentMFAToken>
#now use it or do -credential $MFASession.credentials on any AWS call that needs this
Set-AWSCredential -Credential $MFASession







$MFASession=Get-STSSessionToken -SerialNumber (Get-IAMMFADevice).SerialNumber -TokenCode
Set-AWSCredential -Credential $MFASession


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: