How to disable an AWS IAM Access Key based on tag with a date value?

Is there a way using a lambda function writing in python 3.8 to disable an iam access key if it has a tag assigned to it that includes a data? I have the code below that I have been working on, any help would be appreciated, trying to figure a way out to evaluate based on the tag value assigned and disable the access key if it matches the date value within the tag.

import datetime
from datetime import datetime, timezone
import json
import logging
import os
import traceback
import time
import boto3
from botocore.exceptions import ClientError
import jmespath
 
ACCOUNT = None
ALIAS = os.getenv('ALIAS')
BUCKET = os.getenv('BUCKET')
CLIENT = boto3.client('iam')
CWLOG = boto3.client('logs')
DISABLE_DAYS = int(os.getenv('DISABLE_DAYS', '90'))
DELETE_DAYS = int(os.getenv('DELETE_DAYS', '120'))
DISABLE_DRYRUN = os.getenv('DISABLE_DRYRUN', 'false')
__DisableOn = datetime.datetime()
DELETE_DRYRUN = os.getenv('DELETE_DRYRUN', 'true')
LOGDICT = {}
LOG_NAME = os.getenv('LOG_NAME', '/aws/lambda/GBTS-Restrict-IAM-Users-Keys-Splunk')
STREAM = None
TME = datetime.utcnow()
CURRENT_DATE = TME.replace(tzinfo=timezone.utc)
LOG = logging.getLogger()
 
def check_user(user):
    '''Checks user and return dictionary. Dictionary will contain
    action to disable or delete user
    '''
    username = user['UserName']
    checks = {
        'user': username,
        'action': "",
        'lastused': "",
        '__DisableOn': ""
    }
    last_used_date = user.get('PasswordLastUsed', user.get('CreateDate'))
    delta = CURRENT_DATE - last_used_date
    disable_on_date = user.get('__DisableOn')
    charlie = CURRENT_DATE - disable_on_date
    checks['__DisableOn'] = charlie.date
    checks['lastused'] = delta.days
    try:
        CLIENT.get_login_profile(UserName=username)
    except ClientError as err:
        if err.response['Error']['Code'] == 'NoSuchEntity':
            if delta.days > DELETE_DAYS:
                checks['action'] = 'delete'
                return checks
        else:
            raise
        if charlie.date >= disable_on_date:
            checks['action'] = 'disable'
            return checks
    if delta.days > DISABLE_DAYS:
        checks['action'] = 'disable'
    return checks

Source: Python Questions

LEAVE A COMMENT