Skip to content

Instantly share code, notes, and snippets.

@OnlyInAmerica
Created May 12, 2015 21:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save OnlyInAmerica/8d64038eeb0968129cdc to your computer and use it in GitHub Desktop.
Save OnlyInAmerica/8d64038eeb0968129cdc to your computer and use it in GitHub Desktop.
Delete old IAM AWS users
import boto.iam
'''
Delete the NUM_USERS_TO_DELETE oldest IAM users in your account*
*IMPORTANT: The boto iam api appears to only allow querying 1000 users
at a time so if you have over 1000 IAM users there is no guarantee these
will be the oldest. The deleted users are only guaranteed to be the oldest
among the 1000 aws returns us.
You can authenticate with boto by adding the following to ~/.aws/credentials
[default]
aws_access_key_id = YOUR_ACCESS_KEY_ID
aws_secret_access_key = YOUR_SECRET_ACCESS_KEY
'''
NUM_USERS_TO_DELETE = 100
iam = boto.connect_iam()
#max_items=1000 is the max allowed :/
users = iam.get_all_users('/', max_items=1000)['list_users_response']['list_users_result']['users']
print 'Got %s total users ' % len(users)
users_by_creation_date = {}
for user in users:
'''
{u'path': u'/',
u'create_date': u'2015-04-06T15:02:14Z',
u'user_id': u'AIDAIKMI43EATDAVHNJKG',
u'arn': u'arn:aws:iam::829224601129:user/001i1kay21bo',
u'user_name': u'001i1kay21bo'}
'''
users_by_creation_date[user.create_date] = user.user_name
# Sort by Creation Date, Ascending
#print users_by_creation_date
sorted_creation_dates = sorted(users_by_creation_date)[:NUM_USERS_TO_DELETE]
#print sorted_creation_dates
for creation_date in sorted_creation_dates:
to_delete_user = users_by_creation_date[creation_date]
print 'will delete %s created on %s' % (to_delete_user, creation_date)
# DANGER ZONE
'''
result = raw_input("Delete users? (y/n) ")
if result == 'y':
for creation_date in sorted_creation_dates:
to_delete_user = users_by_creation_date[creation_date]
iam.delete_user(to_delete_user)
print 'done'
else:
print 'cancelled'
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment