How to get all keys from AWS KMS in python with boto3

Last updated 4 years, 1 month ago | 3167 views 75     5

Python | get all keys from AWS KMS in python with boto3

This is an example of how we can get all the CMK(Customer Master Key) from AWS KMS. 
To get all keys from AWS lets first, specify some necessary items which let you get the keys

import boto3

AWS_ACCESS_KEY_ID = 'some-access-key-id'
AWS_SECRET_ACCESS_KEY = 'some-aws-secret-access-key'
REGION_NAME = 'eu-west-1'

Now creating a botocore.client.KMS object

kms_client = boto3.client(
    'kms',
    aws_access_key_id=AWS_ACCESS_KEY_ID,
    aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
    region_name=REGION_NAME
)

let's check kms_client 

print(kms_client)
#Output: <botocore.client.KMS object at 0x000001A673B08438>

print(type(kms_client))
#Output: <class 'botocore.client.KMS'>

List keys

so kms_client is created, now use list_keys() function to get all the CMK available in KMS.

response = kms_client.list_keys()

let's check the response

print (type(response))
# Output: <class 'dict'>

print(response)
'''
Output : 
{
    'Keys': [
        {
            'KeyId': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
            'KeyArn': 'arn:aws:kms:eu-west-1:444444444444:key/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
        },
        {
            'KeyId': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
            'KeyArn': 'arn:aws:kms:eu-west-1:444444444444:key/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
        },
        {
            'KeyId': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
            'KeyArn': 'arn:aws:kms:eu-west-1:444444444444:key/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
        }
    ],
    'Truncated': False,
    'ResponseMetadata': {
        'RequestId': '22b6011a-3cca-4444-a333-0a621b99fa39',
        'HTTPStatusCode': 200,
        'HTTPHeaders': {
            'x-amzn-requestid': '22b6011a-3cca-4444-a333-0a621b99fa39',
            'cache-control': 'no-cache, no-store, must-revalidate, private',
            'expires': '0',
            'pragma': 'no-cache',
            'date': 'Tue, 13 Apr 2020 09:05:12 GMT',
            'content-type': 'application/x-amz-json-1.1',
            'content-length': '857'
        },
        'RetryAttempts': 0
    }
}
'''

let's get only keys

print (response[Keys])
'''
Output :
[
	{
		'KeyId': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
		'KeyArn': 'arn:aws:kms:eu-west-1:444444444444:key/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
	},
	{
		'KeyId': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
		'KeyArn': 'arn:aws:kms:eu-west-1:444444444444:key/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
	},
	{
		'KeyId': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
		'KeyArn': 'arn:aws:kms:eu-west-1:444444444444:key/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
	}
]
'''