使用Python3过滤输出

时间:2018-11-01 20:32:53

标签: json python-3.x amazon-web-services boto3

我有一个脚本,该脚本使用boto3遍历我的所有AWS账户,以从我拥有的每个CloudTrail账户中获取AWS跟踪的列表。我遇到的问题是,这些路径是使用StackSets进行的,因此名称都是动态的。因此,当我尝试按跟踪名称进行过滤时,进入每个帐户并手动查找名称是不可扩展的,因为我拥有很多帐户。运行脚本时,我会看到所需的路径名称,但是如何仅针对该特定路径名称进行过滤?下面是我的代码和输出。

CODE:

import boto3

def get_sts_token(**kwargs):
    role_arn = kwargs['RoleArn']
    region_name = kwargs['RegionName']
    sts = boto3.client(
        'sts',
    region_name=region_name,
    )
    token = sts.assume_role(
        RoleArn=role_arn,
        RoleSessionName='GetInstances',
        DurationSeconds=900,
    )
    return token["Credentials"]

def get_acct_nums():
    region_name = 'us-east-1'

    dynamo = boto3.client('dynamodb')
    dynamo_response = dynamo.scan(TableName='AllAccountNums')

    for item in dynamo_response['Items']:
        account = item['Accounts']['S']

        role_arn = "arn:aws:iam: 
    {}:role/ExecutionRole".format(account)
        tokens = get_sts_token(RoleArn=role_arn, RegionName=region_name)

        access_key = tokens['AccessKeyId']
        secret_key = tokens['SecretAccessKey']      
        session_token = tokens['SessionToken']

        ctrail = boto3.client('cloudtrail',
            aws_access_key_id=access_key,
            aws_secret_access_key=secret_key,
            aws_session_token=session_token)

        ctrail_response = ctrail.describe_trails()

        for trail in ctrail_response['trailList']:
            trail_name = trail['Name']

            print(trail_name)

get_acct_nums()

Output:

StackSet-trail-56ab8f59-F7VFM147fe3

cloud-trail-7327093746523

StackSet-trail-03353e-1HLJF22QI1Dw2

cloud-trail-5702290092543

等等等

我只希望这一行输出:StackSet-trail-xxxx-yyyy(并不总是第一行)。

1 个答案:

答案 0 :(得分:1)

代替遍历所有元素,这只会为您提供第一个元素的名称

ctrail_response['trailList'][0]['Name']

但是,如果只需要StackSet-trail的第一行:

for trail in ctrail_response['trailList']:
    trail_name = trail['Name']
    if 'StackSet-trail' in trail_name:
        print(trail_name)
        break   # remove this if you want all StackSet-trail to appear