AWS use-stsrole with MFA

Hi All,

Wondering if someone can help me with this script. What I am trying to do is to use powershell to iterate through our various AWS accounts in all the different regions to query out security groups. I am using use-stsrole which assumes a role which has access to all our accounts. However, when I run the script, it just defaults to the AWS account i have stored locally on my credentials file (the root account) and continuously just lists the security groups within this account. When I look to debug the script, I can never see a variable which stores the credentials leading me to believe because it is not getting the credentials it is not able to access any of the other accounts. Can some please review the script I am using and tell me where I am going wrong?

$UserARN = "arn:aws:iam::111111111111:mfa/" + $IAMname

Write-host $UserARN
Write-host $MFACode
$Accounts = @(111111111111, 222222222222,333333333333)
$Regions = (Get-SSMParametersByPath -Path '/aws/service/global-infrastructure/regions' -region eu-west-1).Value
$Accounts | ForEach-Object {
$Account = $_
$RoleArn = "arn:aws:iam::${Account}:role/role"
$Token = (Use-STSRole -RoleArn $RoleArn -RoleSessionName "AMOPS" -Region $Region -TokenCode $MFAcode -SerialNumber $UserARN).Credentials
$Credentials = New-AWSCredentials -AccessKey $OPStoken.Credentials.AccessKeyId -SecretKey $OPStoken.Credentials.SecretAccessKey -SessionToken $OPStoken.Credentials.SessionToken
foreach ($Region in $Regions){
Write-Output $Role $Region
Get-EC2SecurityGroup -Filter @{Name="ip-permission.cidr";Values="x.x.x.x/32"} -Region $Region -Credential $Credentials


This doesn’t look right to me. Please provide your source of information for this construction if you don’t mind.

This doesn’t look correct not going t call the account.Try one of the two variants below.

$RoleArn = "arn:aws:iam::${Account}:role/role"
$RoleArn = "arn:aws:iam::$Account:role/role" 
$RoleArn = "arn:aws:iam::$($Account}:role/role"