diff --git a/leverage/_backend_config.py b/leverage/_backend_config.py index fe50368..0994fd8 100644 --- a/leverage/_backend_config.py +++ b/leverage/_backend_config.py @@ -168,5 +168,8 @@ def get_backend_key(config_file: Union[str, Path]) -> Optional[str]: f"Possible invalid expression in [bold]config.tf[/bold] near line {error.line}, column {error.column}\n" f"{error.get_context(config_content)}", ) + except ExitError: + # Let our own, more specific errors (e.g. missing backend block) through untouched + raise except Exception: raise ExitError(1, f"Malformed [bold]config.tf[/bold] file. Unable to parse.") diff --git a/leverage/modules/credentials.py b/leverage/modules/credentials.py index 813b266..0e1c4c0 100644 --- a/leverage/modules/credentials.py +++ b/leverage/modules/credentials.py @@ -34,10 +34,7 @@ # https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html#API_CreateUser_RequestParameters KEY_ID = r"[A-Z0-9]{20}" SECRET_KEY = r"[a-zA-Z0-9/\+]{40}" -REGION = ( - r"[a-z]{2}-[gov-]?" - r"(?:central|north|south|east|west|northeast|northwest|southeast|southwest|secret|topsecret)-[1-3]" -) +REGION = r"(([a-z]{2}(-gov)?)-(central|(north|south)?(east|west)?)-\d)" ACCOUNT_ID = r"[0-9]{12}" MFA_SERIAL = rf"arn:aws:iam::{ACCOUNT_ID}:mfa/{USERNAME}" @@ -484,7 +481,7 @@ def _credentials_are_valid(awscli: Runner, profile: str): """ error_code, output, _ = awscli.exec("sts", "get-caller-identity", "--profile", profile, raises=False) - return error_code != 255 and "InvalidClientTokenId" not in output + return error_code == 0 @pass_runner @@ -518,11 +515,19 @@ def _get_organization_accounts(awscli: Runner, profile: str, project_name: str): Returns: dict: Mapping of organization accounts names to ids. """ - exit_code, organization_accounts, _ = awscli.exec( + exit_code, organization_accounts, error = awscli.exec( "organizations", "list-accounts", "--output", "json", "--profile", profile, raises=False ) if exit_code: + if "AWSOrganizationsNotInUseException" in error: + logger.warning( + "The account is not a member of an AWS Organization (standalone account). " + "Accounts ids will not be fetched from the organization; only the ones already set in the " + "project configuration will be used." + ) + else: + logger.warning(f"Unable to fetch organization accounts: {error or organization_accounts}") return {} organization_accounts = json.loads(organization_accounts)["Accounts"] diff --git a/tests/test_backend_config.py b/tests/test_backend_config.py index 9c65db8..eedbdd4 100644 --- a/tests/test_backend_config.py +++ b/tests/test_backend_config.py @@ -151,10 +151,39 @@ def test_set_backend_key_raises_for_missing_backend(config_without_backend): def test_get_backend_key_raises_for_missing_backend(config_without_backend): """Test that get_backend_key raises ExitError when backend block is missing.""" - with pytest.raises(ExitError, match="Malformed"): + with pytest.raises(ExitError, match="Missing backend block"): get_backend_key(config_without_backend) +def test_get_backend_key_reports_missing_backend_when_backend_is_commented_out(tmp_path): + """A valid config.tf whose backend block is commented out (as in the tf-backend layer template before its first + apply) must report the missing backend, not a generic parsing error.""" + config_file = tmp_path / "config.tf" + config_file.write_text( + 'provider "aws" {\n' + " region = var.region\n" + "}\n" + "\n" + 'provider "aws" {\n' + ' alias = "secondary_region"\n' + " region = var.region_secondary\n" + "}\n" + "\n" + "terraform {\n" + ' required_version = "~> 1.2"\n' + "\n" + " required_providers {\n" + ' aws = "~> 5.0"\n' + " }\n" + ' # backend "s3" {\n' + ' # key = "management/tf-backend/terraform.tfstate"\n' + " # }\n" + "}\n" + ) + with pytest.raises(ExitError, match="Missing backend block"): + get_backend_key(config_file) + + def test_set_backend_key_with_complex_formatting(tmp_path): """Test with various formatting styles.""" config_file = tmp_path / "config.tf" diff --git a/tests/test_modules/test_credentials.py b/tests/test_modules/test_credentials.py index 1f637ee..59dd0ce 100644 --- a/tests/test_modules/test_credentials.py +++ b/tests/test_modules/test_credentials.py @@ -311,6 +311,22 @@ def test_get_organization_accounts_error(): assert _get_organization_accounts("foo", "bar") == {} +def test_get_organization_accounts_standalone_account(propagate_logs, caplog): + """ + Test that a standalone account (not member of an AWS Organization) is reported clearly and an empty dict returned. + """ + awscli = awscli_returning( + 254, + "", + "An error occurred (AWSOrganizationsNotInUseException) when calling the ListAccounts operation: " + "Your account is not a member of an organization.", + ) + with cli_context(runner=awscli): + assert _get_organization_accounts("foo", "bar") == {} + + assert "not a member of an AWS Organization" in caplog.text + + def test_get_mfa_serial(): """ Test that we fetch the mfa devices from the profile and return the serial number of the first one that is valid.