2

i'm using this code to get IAM user:

    #!/usr/bin/env python


    import boto3
    import json


    client = boto3.client('iam')

    response = client.list_users(

    )

    print response

and getting:

{u'Users': [{u'UserName': 'ja', u'Path': '/', u'CreateDate': datetime.datetime(2018, 4, 6, 12, 41, 18, tzinfo=tzutc()), u'UserId': 'AIDAJXIHXCSI62ZQKLGZM', u'Arn': 'arn:aws:iam::233135199200:user/ja'}, {u'UserName': 'test', u'Path': '/', u'CreateDate': datetime.datetime(2018, 4, 7, 10, 55, 58, tzinfo=tzutc()), u'UserId': 'AIDAIENHQD6YWMX3A45TY', u'Arn': 'arn:aws:iam::233135199200:user/test'}], 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': 'ebd600f0-3a52-11e8-bc50-d37153ae8ac5', 'HTTPHeaders': {'x-amzn-requestid': 'ebd600f0-3a52-11e8-bc50-d37153ae8ac5', 'date': 'Sat, 07 Apr 2018 11:00:44 GMT', 'content-length': '785', 'content-type': 'text/xml'}}, u'IsTruncated': False}

I saved response to JSON file

I need only to extract Usernames so that output should be 2 lines in this case:

ja
test

when adding

print response['Users'][0]['UserName']

get only first name, if set [] then incorrect syntax

Milister
  • 648
  • 1
  • 15
  • 33

1 Answers1

10

There is no need to convert to JSON. The response comes back as a Python object:

import boto3
client = boto3.client('iam')
response = client.list_users()

print ([user['UserName'] for user in response['Users']])

This will result in:

['ja', 'test']

Or, you could use:

for user in response['Users']:
  print (user['UserName'])

This results in:

ja
test
John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
  • 1
    Thanks John, meanwhile i found workaround:`#!/usr/bin/env python import boto3 import json client = boto3.client('iam') response = client.list_users( ) for i in range (0, len (response['Users'])): print response['Users'][i]['UserName']` – Milister Apr 07 '18 at 11:51
  • You can also use the [AWS Command-Line Interface (CLI)](http://aws.amazon.com/cli/): `aws iam list-users --query Users[*].UserName` – John Rotenstein Apr 07 '18 at 21:42