| 20 | |
| 21 | # snippet-start:[python.example_code.kms.AliasManager.decl] |
| 22 | class AliasManager: |
| 23 | def __init__(self, kms_client): |
| 24 | self.kms_client = kms_client |
| 25 | self.created_key = None |
| 26 | |
| 27 | @classmethod |
| 28 | def from_client(cls) -> "AliasManager": |
| 29 | """ |
| 30 | Creates an AliasManager instance with a default KMS client. |
| 31 | |
| 32 | :return: An instance of AliasManager initialized with the default KMS client. |
| 33 | """ |
| 34 | kms_client = boto3.client("kms") |
| 35 | return cls(kms_client) |
| 36 | |
| 37 | # snippet-end:[python.example_code.kms.AliasManager.decl] |
| 38 | |
| 39 | def setup(self): |
| 40 | """ |
| 41 | Sets up a key for the demo. Either creates a new key or uses one supplied by |
| 42 | the user. |
| 43 | |
| 44 | :return: The ARN or ID of the key to use for the demo. |
| 45 | """ |
| 46 | answer = input("Do you want to create a new key for the demo (y/n)? ") |
| 47 | if answer.lower() == "y": |
| 48 | try: |
| 49 | key = self.kms_client.create_key( |
| 50 | Description="Alias management demo key" |
| 51 | )["KeyMetadata"] |
| 52 | self.created_key = key |
| 53 | except ClientError as err: |
| 54 | logger.error( |
| 55 | "Couldn't create key. Here's why: %s", |
| 56 | err.response["Error"]["Message"], |
| 57 | ) |
| 58 | raise |
| 59 | else: |
| 60 | key_id = key["KeyId"] |
| 61 | else: |
| 62 | key_id = input("Enter a key ID or ARN to use for the demo: ") |
| 63 | if key_id == "": |
| 64 | key_id = None |
| 65 | return key_id |
| 66 | |
| 67 | def teardown(self): |
| 68 | """ |
| 69 | Deletes any resources that were created for the demo. |
| 70 | """ |
| 71 | if self.created_key is not None: |
| 72 | answer = input( |
| 73 | f"Key {self.created_key['KeyId']} was created for this demo. Do you " |
| 74 | f"want to delete it (y/n)? " |
| 75 | ) |
| 76 | if answer.lower() == "y": |
| 77 | try: |
| 78 | self.kms_client.schedule_key_deletion( |
| 79 | KeyId=self.created_key["KeyId"], PendingWindowInDays=7 |
no outgoing calls