0

I am now getting to the end of resolving a lambda exception issue. After getting some help debugging the recent exceptions and resolving them, there is one i cannot resolve, so would like to pass it.

import boto3

sts_client = boto3.client('sts')
assumed_role_object=sts_client.assume_role(
    RoleArn="arn:aws:iam::11111111:role/role",
    RoleSessionName="AssumedRoleSession2"
)
credentials=assumed_role_object['Credentials']

def lambda_handler(context,event):
    client                  = boto3.client(
        'iam',
        aws_access_key_id=credentials['AccessKeyId'],
        aws_secret_access_key=credentials['SecretAccessKey'],
        aws_session_token=credentials['SessionToken'],
    )
    sns                     = boto3.client('sns')
    response                = client.list_users()
    userVirtualMfa          = client.list_virtual_mfa_devices()
    mfaNotEnabled           = []
    virtualEnabled          = []
    physicalString          = ''

    # loop through virtual mfa to find users that actually have it
    for virtual in userVirtualMfa['VirtualMFADevices']:
        if 'User' not in virtual or 'UserName' not in virtual['User']:
     # Catch the exception
           raise Exception("Invalid virtual %s" % virtual)

        virtualEnabled.append(virtual['User']['UserName'])

    # loop through users to find physical MFA
    for user in response['Users']:
        userMfa  = client.list_mfa_devices(UserName=user['UserName'])

        if len(userMfa['MFADevices']) == 0:
            if user['UserName'] not in virtualEnabled:
                mfaNotEnabled.append(user['UserName']) 


    if len(mfaNotEnabled) > 0:
        physicalString = 'Physical & Virtual MFA is not enabled for the following users: \n\n' + '\n'.join(mfaNotEnabled)
    else:
        physicalString = 'All Users have Physical and Virtual MFA enabled'

    response = sns.publish(
        TopicArn='arn:aws:sns:eu-west-2:222222222:sns',
        Message= physicalString,
        Subject='Enable MFA',
    )

    return mfaNotEnabled

The exception is reporting correctly, but i would like the function to continue

Response:
{
  "stackTrace": [
    [
      "/var/task/lambda_mfa_function.py",
      27,
      "lambda_handler",
      "raise Exception(\"Invalid virtual %s\" % virtual)"
    ]
  ],
  "errorType": "Exception",
  "errorMessage": "Invalid virtual {u'SerialNumber': 'arn:aws:iam::11111111:mfa/blah-mfa-device', u'EnableDate': datetime.datetime(2016, 05, 16, 01, 6, 35, tzinfo=tzlocal()), u'User': {u'PasswordLastUsed': datetime.datetime(2018, 5, 1, 02, 35, 27, tzinfo=tzlocal()), u'CreateDate': datetime.datetime(2014, 7, 17, 13, 43, 27, tzinfo=tzlocal()), u'UserId': '11111111', u'Arn': 'arn:aws:iam::11111111:blah'}}"
}

Request ID:
"c11a70c9-3a59-486a-9aa9-7286a0cb0b94"

Function Logs:
START RequestId: c11a70c9-3a59-486a-9aa9-7286a0cb0b94 Version: $LATEST
Invalid virtual {u'SerialNumber': 'arn:aws:iam::11111111:mfa/blah-mfa-device', u'EnableDate': datetime.datetime(2016, 11, 16, 22, 6, 35, tzinfo=tzlocal()), u'User': {u'PasswordLastUsed': datetime.datetime(2020, 5, 1, 14, 35, 27, tzinfo=tzlocal()), u'CreateDate': datetime.datetime(2015, 7, 17, 13, 43, 27, tzinfo=tzlocal()), u'UserId': '265742304136', u'Arn': 'arn:aws:iam::11111111:blah'}}: Exception
Traceback (most recent call last):
  File "/var/task/lambda_mfa_function.py", line 27, in lambda_handler
    raise Exception("Invalid virtual %s" % virtual)
Exception: Invalid virtual {u'SerialNumber': 'arn:aws:iam::11111111:mfa/blah-mfa-device', u'EnableDate': datetime.datetime(2014, 12, 12, 02, 6, 35, tzinfo=tzlocal()), u'User': {u'PasswordLastUsed': datetime.datetime(2016, 7, 2, 1, 15, 27, tzinfo=tzlocal()), u'CreateDate': datetime.datetime(2014, 2, 7, 3, 33, 17, tzinfo=tzlocal()), u'UserId': '11111111', u'Arn': 'arn:aws:iam::11111111:blah'}}

Its throwing a key error on the root MFA i expect due to the nature in which the root name is held

  File "/var/task/lambda_mfa_function.py", line 26, in lambda_handler
    virtualEnabled.append(virtual['User']['UserName'])
KeyError: 'UserName'

Addin an

except:
    pass

Is causing the lambda to fail. Can someone kindly point me into the right direction?

thanks Nick

2
  • If you want the function to continue, then don't raise an exception. Commented Jun 4, 2020 at 10:45
  • Yeah just worked that out. Thankyou Commented Jun 4, 2020 at 10:46

1 Answer 1

1

This fixed it for me and was posted on an earlier question

userVirtualMfa = client.list_virtual_mfa_devices()
try:
    for virtual in userVirtualMfa['VirtualMFADevices']:
        virtualEnabled.append(virtual['User']['UserName'])
except:
    print("'UserName' is not a valid key")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.