· 7 years ago · Dec 20, 2018, 12:36 AM
1# To run this script from the command line, enter:
2# python iam_key_creation.py <aws cli profile> <username> <aws group>
3# You must have python and boto3 installed
4# Keys will be written to a file named <username>_keys.csv in the same directory
5
6import sys
7import boto3
8import csv
9import datetime
10
11def create_keys(profile, username, group):
12
13 default = boto3.session.Session(profile_name=profile)
14
15 client = default.client("iam")
16
17 # create user
18 client.create_user(UserName=username)
19 print "User {} has been created".format(username)
20 # add user to group
21 client.add_user_to_group(
22 GroupName=group,
23 UserName=username
24 )
25 print "User {} has been added to {} group".format(username, group)
26 # create access keys
27 keys = client.create_access_key(
28 UserName=username
29 )
30 userName = keys['AccessKey']['UserName']
31 AccessKey = keys['AccessKey']['AccessKeyId']
32 SecretKey = keys['AccessKey']['SecretAccessKey']
33 print "Keys have been created"
34 # add access keys to csv
35 with open('{}_keys.csv'.format(username), 'wb') as csvfile:
36 f = csv.writer(csvfile, quoting = csv.QUOTE_ALL)
37 f.writerow(['Keys generated at {}'.format(datetime.datetime.now())])
38 f.writerow(['User', 'Account', 'AccessKeyID', 'SecretAccessKey'])
39 f.writerow([userName, profile, AccessKey, SecretKey])
40 print "Keys have been written to file"
41 return csvfile
42
43if __name__ == '__main__':
44 # Map command line arguments to function arguments.
45 create_keys(*sys.argv[1:])