AWS use-stsrole with MFA

Welcome Forums General PowerShell Q&A AWS use-stsrole with MFA

This topic contains 1 reply, has 2 voices, and was last updated by

1 week, 4 days ago.

  • Author
  • #174748

    Topics: 3
    Replies: 3
    Points: 12
    Rank: Member

    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
  • #175597

    Topics: 0
    Replies: 100
    Points: 363
    Helping Hand
    Rank: Contributor


    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"

You must be logged in to reply to this topic.