Create a new EC2 key pair. Args: key_name: Name for the key pair. save_to_file: If provided, save the private key to this file path. tags: Dictionary of tags to apply. Returns: Details of the created key p
(
self,
key_name: str,
save_to_file: Optional[str] = None,
tags: Optional[Dict[str, str]] = None
)
| 484 | |
| 485 | @aws_operation("create_key_pair") |
| 486 | def create_key_pair( |
| 487 | self, |
| 488 | key_name: str, |
| 489 | save_to_file: Optional[str] = None, |
| 490 | tags: Optional[Dict[str, str]] = None |
| 491 | ) -> Dict[str, Any]: |
| 492 | """ |
| 493 | Create a new EC2 key pair. |
| 494 | |
| 495 | Args: |
| 496 | key_name: Name for the key pair. |
| 497 | save_to_file: If provided, save the private key to this file path. |
| 498 | tags: Dictionary of tags to apply. |
| 499 | |
| 500 | Returns: |
| 501 | Details of the created key pair, including the private key. |
| 502 | """ |
| 503 | # Prepare tags |
| 504 | all_tags = self.DEFAULT_TAGS.copy() |
| 505 | if tags: |
| 506 | all_tags.update(tags) |
| 507 | |
| 508 | tag_specs = [{ |
| 509 | 'ResourceType': 'key-pair', |
| 510 | 'Tags': [{'Key': k, 'Value': v} for k, v in all_tags.items()] |
| 511 | }] |
| 512 | |
| 513 | # Create the key pair |
| 514 | response = self.client.create_key_pair( |
| 515 | KeyName=key_name, |
| 516 | TagSpecifications=tag_specs |
| 517 | ) |
| 518 | |
| 519 | # Save the private key to a file if requested |
| 520 | if save_to_file and 'KeyMaterial' in response: |
| 521 | save_path = os.path.expanduser(save_to_file) |
| 522 | os.makedirs(os.path.dirname(save_path), exist_ok=True) |
| 523 | |
| 524 | with open(save_path, 'w') as f: |
| 525 | f.write(response['KeyMaterial']) |
| 526 | |
| 527 | # Set correct permissions for private key |
| 528 | os.chmod(save_path, 0o600) |
| 529 | |
| 530 | logger.info(f"Private key saved to {save_path}") |
| 531 | |
| 532 | return response |
| 533 | |
| 534 | @aws_operation("delete_key_pair") |
| 535 | def delete_key_pair(self, key_name: str) -> None: |
no outgoing calls