|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +""" |
| 4 | +This module is used to create an AWS account alias, which is required by the deploy.py script. |
| 5 | +
|
| 6 | +It provides a function to create an account alias using the AWS CLI, as this specific |
| 7 | +operation is not supported by the AWS CDK. |
| 8 | +""" |
| 9 | + |
| 10 | +import logging |
| 11 | +import re |
| 12 | +import subprocess |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +def _is_valid_alias(alias_name: str) -> bool: |
| 18 | + """ |
| 19 | + Check if the provided alias name is valid according to AWS rules. |
| 20 | +
|
| 21 | + AWS account alias must be unique and must be between 3 and 63 characters long. |
| 22 | + Valid characters are a-z, 0-9 and '-'. |
| 23 | +
|
| 24 | + Args: |
| 25 | + alias_name (str): The alias name to validate. |
| 26 | +
|
| 27 | + Returns: |
| 28 | + bool: True if the alias is valid, False otherwise. |
| 29 | + """ |
| 30 | + pattern = r"^[a-z0-9](([a-z0-9]|-){0,61}[a-z0-9])?$" |
| 31 | + return bool(re.match(pattern, alias_name)) and 3 <= len(alias_name) <= 63 |
| 32 | + |
| 33 | + |
| 34 | +def _log_aws_cli_version() -> None: |
| 35 | + """ |
| 36 | + Log the version of the AWS CLI installed on the system. |
| 37 | + """ |
| 38 | + try: |
| 39 | + result = subprocess.run(["aws", "--version"], capture_output=True, text=True) |
| 40 | + logger.info(f"AWS CLI version: {result.stderr.strip()}") |
| 41 | + except Exception as e: |
| 42 | + logger.warning(f"Unable to determine AWS CLI version: {str(e)}") |
| 43 | + |
| 44 | + |
| 45 | +def create_account_alias(alias_name: str) -> None: |
| 46 | + """ |
| 47 | + Create a new account alias with the given name. |
| 48 | +
|
| 49 | + This function exists because the CDK does not support the specific |
| 50 | + CreateAccountAliases API call. It attempts to create an account alias |
| 51 | + using the AWS CLI and logs the result. |
| 52 | +
|
| 53 | + If the account alias is created successfully, it logs a success message. |
| 54 | + If the account alias already exists, it logs a message indicating that. |
| 55 | + If there is any other error, it logs the error message. |
| 56 | +
|
| 57 | + Args: |
| 58 | + alias_name (str): The desired name for the account alias. |
| 59 | + """ |
| 60 | + # Log AWS CLI version when the function is called |
| 61 | + _log_aws_cli_version() |
| 62 | + |
| 63 | + if not _is_valid_alias(alias_name): |
| 64 | + logger.error( |
| 65 | + f"Invalid alias name '{alias_name}'. It must be between 3 and 63 characters long and contain only lowercase letters, numbers, and hyphens." |
| 66 | + ) |
| 67 | + return |
| 68 | + |
| 69 | + command = ["aws", "iam", "create-account-alias", "--account-alias", alias_name] |
| 70 | + |
| 71 | + try: |
| 72 | + subprocess.run( |
| 73 | + command, |
| 74 | + stdout=subprocess.PIPE, |
| 75 | + stderr=subprocess.PIPE, |
| 76 | + text=True, |
| 77 | + check=True, |
| 78 | + ) |
| 79 | + logger.info(f"Account alias '{alias_name}' created successfully.") |
| 80 | + except subprocess.CalledProcessError as e: |
| 81 | + if "EntityAlreadyExists" in e.stderr: |
| 82 | + logger.info(f"Account alias '{alias_name}' already exists.") |
| 83 | + elif "AccessDenied" in e.stderr: |
| 84 | + logger.error( |
| 85 | + f"Access denied when creating account alias '{alias_name}'. Check your AWS credentials and permissions." |
| 86 | + ) |
| 87 | + elif "ValidationError" in e.stderr: |
| 88 | + logger.error( |
| 89 | + f"Validation error when creating account alias '{alias_name}'. The alias might not meet AWS requirements." |
| 90 | + ) |
| 91 | + else: |
| 92 | + logger.error(f"Error creating account alias '{alias_name}': {e.stderr}") |
| 93 | + except Exception as e: |
| 94 | + logger.error( |
| 95 | + f"Unexpected error occurred while creating account alias '{alias_name}': {str(e)}" |
| 96 | + ) |
| 97 | + |
| 98 | + |
| 99 | +def main(): |
| 100 | + import argparse |
| 101 | + |
| 102 | + # Set up logging |
| 103 | + logging.basicConfig( |
| 104 | + level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" |
| 105 | + ) |
| 106 | + |
| 107 | + # Create argument parser |
| 108 | + parser = argparse.ArgumentParser(description="Create an AWS account alias") |
| 109 | + parser.add_argument("alias", help="The alias name for the AWS account") |
| 110 | + |
| 111 | + # Parse arguments |
| 112 | + args = parser.parse_args() |
| 113 | + |
| 114 | + # Call the function with the provided alias |
| 115 | + create_account_alias(args.alias) |
| 116 | + |
| 117 | +if __name__ == "__main__": |
| 118 | + main() |
0 commit comments