简体   繁体   中英

How to get only KMS Customer managed keys alone from AWS Account using python boto3?

I am trying to get only the count of Customer managed keys from AWS Account. I am getting the double count of what is there in AWS Account. It is getting AWS managed keys as well. So i want to know how to get the count of only Customer managed keys from KMS.

Python code:

for region in ec2_regions:
    conn = boto3.client('kms', aws_access_key_id=access_key, 
                    aws_secret_access_key=secret_key,region_name=region)

    resp = conn.list_keys()
    for keys in resp:
      kms_count.append(keys)
print("kms" + str(len(kms_count)))

You can use the list_aliases method to do so. For AWS managed keys, the alias has 'alias/aws/' as a prefix string. You can apply your logic over the same to get only the Customer Managed keys from KMS.

I've updated your code snippet as per the requirement:

kms_count=[]
for region in ec2_regions:
    conn = boto3.client('kms', aws_access_key_id=access_key, aws_secret_access_key=secret_key,region_name=region)

    resp = conn.list_aliases()['Aliases']
    for keys in resp:
        if 'alias/aws/' not in keys['AliasName']:
            kms_count.append(keys)
print("kms count: " + str(len(kms_count)))

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM