How to get an AWS KMS Key description in python with boto3

Last updated 3 months, 2 weeks ago | 187 views 75     5

Python | Get an AWS KMS Key description in python with boto3

The describe_key() function is used to get the key description. It takes KeyArn and returns a dictionary having KeyMetadata.

These are some necessary items that let you get the key description

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
)

Key Description

Now call the describe_key() function with KeyArn.  KeyArn is the combination of AWSAccountId and KeyId. e.g: KeyArn = arn:aws:kms:eu-west-1:<AWSAccountId>:key/<KeyId>

key_info = kms_client.describe_key(KeyId=arn:aws:kms:eu-west-1:444444444444:key/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

lets check key_info

print(key_info)
'''
Output :
{
    'KeyMetadata': {
        'AWSAccountId': '444444444444',
        'KeyId': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        'Arn': 'arn:aws:kms:eu-west-1:444444444444:key/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        'CreationDate': datetime.datetime(2020, 1, 1, 0, 18, 25, 914000, tzinfo=tzlocal()),
        'Enabled': True,
        'Description': 'This is the first encryption key',
        'KeyUsage': 'ENCRYPT_DECRYPT',
        'KeyState': 'Enabled',
        'Origin': 'AWS_KMS',
        'KeyManager': 'CUSTOMER',
        'CustomerMasterKeySpec': 'SYMMETRIC_DEFAULT',
        'EncryptionAlgorithms': ['SYMMETRIC_DEFAULT']
    },
    'ResponseMetadata': {
        'RequestId': '22b6022a-3cca-4444-a333-0a621b99fa39',
        'HTTPStatusCode': 200,
        'HTTPHeaders': {
            'x-amzn-requestid': '22b6022a-3cca-4444-a333-0a621b99fa39',
            'cache-control': 'no-cache, no-store, must-revalidate, private',
            'expires': '0',
            'pragma': 'no-cache', 'date': 'Tue, 13 Apr 2020 09:18:33 GMT',
            'content-type': 'application/x-amz-json-1.1',
            'content-length': '513'
        },
        'RetryAttempts': 0
    }
}
'''

now, lets get only key details

print(key_info['KeyMetadata'])
'''
Output :
{
	'AWSAccountId': '444444444444',
	'KeyId': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
	'Arn': 'arn:aws:kms:eu-west-1:444444444444:key/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
	'CreationDate': datetime.datetime(2020, 1, 1, 0, 18, 25, 914000, tzinfo=tzlocal()),
	'Enabled': True,
	'Description': 'This is the first encryption key',
	'KeyUsage': 'ENCRYPT_DECRYPT',
	'KeyState': 'Enabled',
	'Origin': 'AWS_KMS',
	'KeyManager': 'CUSTOMER',
	'CustomerMasterKeySpec': 'SYMMETRIC_DEFAULT',
	'EncryptionAlgorithms': ['SYMMETRIC_DEFAULT']
}
'''