|
17 | 17 | from jinja2 import Environment, FileSystemLoader |
18 | 18 |
|
19 | 19 |
|
| 20 | +class AzureNotConfiguredError(Exception): |
| 21 | + """Raised when Azure credentials are not available.""" |
| 22 | + |
| 23 | + pass |
| 24 | + |
| 25 | + |
20 | 26 | def get_default_region(): |
21 | 27 | """ |
22 | 28 | Get the default Azure region from Azure configuration. |
@@ -371,3 +377,45 @@ def exit_on_empty_result(result, context, quiet=False): |
371 | 377 | ) |
372 | 378 | print("Run 'az login' to authenticate with Azure.", file=sys.stderr) |
373 | 379 | sys.exit(1) |
| 380 | + |
| 381 | + |
| 382 | +def require_azure_credentials(): |
| 383 | + """ |
| 384 | + Require Azure credentials, raising an exception if not configured. |
| 385 | +
|
| 386 | + This function should be called early in main() to validate Azure |
| 387 | + credentials. If Azure is not configured, it raises AzureNotConfiguredError |
| 388 | + to let the caller decide how to handle it. |
| 389 | +
|
| 390 | + This centralizes the handling of missing Azure credentials and avoids |
| 391 | + TOCTOU race conditions from manual file existence checks. |
| 392 | +
|
| 393 | + Returns: |
| 394 | + str: Subscription ID if credentials are valid |
| 395 | +
|
| 396 | + Raises: |
| 397 | + AzureNotConfiguredError: If Azure credentials are not found |
| 398 | + """ |
| 399 | + try: |
| 400 | + from azure.common.credentials import get_cli_profile |
| 401 | + |
| 402 | + profile = get_cli_profile() |
| 403 | + credentials, subscription_id, _ = profile.get_login_credentials( |
| 404 | + resource="https://management.azure.com" |
| 405 | + ) |
| 406 | + return subscription_id |
| 407 | + except ImportError as e: |
| 408 | + raise AzureNotConfiguredError("Azure SDK not installed") from e |
| 409 | + except Exception as e: |
| 410 | + # Only treat as "not configured" if it looks like an auth/login issue |
| 411 | + error_msg = str(e).lower() |
| 412 | + auth_indicators = [ |
| 413 | + "login", |
| 414 | + "logged in", |
| 415 | + "authenticate", |
| 416 | + "credential", |
| 417 | + "az login", |
| 418 | + ] |
| 419 | + if any(phrase in error_msg for phrase in auth_indicators): |
| 420 | + raise AzureNotConfiguredError("Azure credentials not found") from e |
| 421 | + raise |
0 commit comments