Reputation: 13
import boto3
client = boto3.client('iam')
users = client.list_users()
def lambda_handler(event,context):
for user in users['Users']:
print("UserName: {0}\nUserID: {1}\nARN: {2}\nCreatedOn: {3}\n\n"
.format(user['UserName'], user['UserId'], user['Arn'], user['CreateDate']))
from this code i have got IAM users list but it prints in the function log not in the response and the response is null i want to get the output in the api endpoint but it is showing null
and i used return in place of print and it list only one iam user can anyone please give me the code for this and i am very much new to the coding and i dont know any fundamentals of python
Upvotes: 1
Views: 706
Reputation: 13
import boto3
import json
client = boto3.client('iam')
users = client.list_users()
def lambda_handler(event,context):
users_list = []
for user in users['Users']:
user_dict = {"UserName": user['UserName'], "UserId": user['UserId'],
"Arn": user['Arn'], "CreateDate": user['CreateDate']}
users_list.append(user_dict)
return json.dumps(users_list, default=str,)
Upvotes: 0
Reputation: 758
It seems like you want the function lambda_handler
to return a list where each element represents an IAM user. There is a few ways to do this. A suggestion that looks like you code as much as possible is a for loop that creates a dictionary with "UserName"
, "UserId"
etc. as keys and the dictionary values equals each users information:
import boto3
client = boto3.client('iam')
users = client.list_users()
def lambda_handler(event,context):
users_list = []
for user in users['Users']:
user_dict = {"UserName": user['UserName'], "UserId": user['UserId'],
"Arn": user['Arn'], "CreateDate": user['CreateDate']}
users_list.append(user_dict)
return users_list
After completing the for loop the list users
should contain dictionaries of all users and the function should simply return that object. Another option of course is to create tuples instead of dictionaries:
def lambda_handler(event,context):
users_list = []
for user in users['Users']:
user_tuple = (user['UserName'], user['UserId'],
user['Arn'], user['CreateDate'])
users_list.append(user_tuple)
return users_list
You could also cram this into a list-comprehension (to keep it short) but in my opinion this is a bit unreadable since the tuple is rather long:
def lambda_handler(event,context):
users_list = [(u['UserName'], u['UserId'], u['Arn'], u['CreateDate']) for u in users['Users']]
return users_list
Upvotes: 1