|
| 1 | +# -------------------------------------------------------------------------------------------- |
| 2 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +# Licensed under the MIT License. See License.txt in the project root for license information. |
| 4 | +# -------------------------------------------------------------------------------------------- |
| 5 | + |
| 6 | +""" |
| 7 | +Module for handling what-if functionality in Azure CLI. |
| 8 | +This module provides the core logic for preview mode execution without actually running commands. |
| 9 | +
|
| 10 | +IMPORTANT: The what-if service requires client-side authentication to operate under the |
| 11 | +caller's subscription and permissions. Server-side authentication is not supported for |
| 12 | +what-if operations as it would not provide access to the caller's subscription. |
| 13 | +
|
| 14 | +This client now uses AzureCliCredential to obtain an access token for the caller's subscription. |
| 15 | + |
| 16 | +The what-if service will use your configured credentials to access your subscription |
| 17 | +and preview deployment changes under your permissions. |
| 18 | +""" |
| 19 | + |
| 20 | +import requests |
| 21 | +from typing import Dict, Any, Optional |
| 22 | +from azure.identity import AzureCliCredential |
| 23 | +from datetime import datetime, timezone |
| 24 | +from knack.log import get_logger |
| 25 | + |
| 26 | +logger = get_logger(__name__) |
| 27 | + |
| 28 | +# Configuration |
| 29 | +FUNCTION_APP_URL = "https://azcli-script-insight.azurewebsites.net" |
| 30 | + |
| 31 | + |
| 32 | +def get_azure_cli_access_token() -> Optional[str]: |
| 33 | + """ |
| 34 | + Get access token for the caller's subscription using AzureCliCredential |
| 35 | +
|
| 36 | + Returns: |
| 37 | + Access token string if successful, None if failed |
| 38 | + """ |
| 39 | + token_info = get_azure_cli_token_info() |
| 40 | + return token_info.get("accessToken") if token_info else None |
| 41 | + |
| 42 | + |
| 43 | +def get_azure_cli_token_info() -> Optional[Dict[str, Any]]: |
| 44 | + """ |
| 45 | + Get complete token information using AzureCliCredential including expiration |
| 46 | + |
| 47 | + Returns: |
| 48 | + Dictionary with token info including accessToken, expiresOn, etc., or None if failed |
| 49 | + """ |
| 50 | + try: |
| 51 | + # Use AzureCliCredential for Azure CLI authentication |
| 52 | + cli_credential = AzureCliCredential(process_timeout=30) |
| 53 | + |
| 54 | + # Get access token for Azure Resource Manager |
| 55 | + token = cli_credential.get_token("https://management.azure.com/.default") |
| 56 | + |
| 57 | + token_info = { |
| 58 | + "accessToken": token.token, |
| 59 | + "expiresOn": datetime.fromtimestamp(token.expires_on, tz=timezone.utc).isoformat(), |
| 60 | + "tokenType": "Bearer" |
| 61 | + } |
| 62 | + |
| 63 | + return token_info |
| 64 | + |
| 65 | + except Exception as e: |
| 66 | + logger.warning(f"Error getting access token with AzureCliCredential: {str(e)}") |
| 67 | + return None |
| 68 | + |
| 69 | + |
| 70 | +def what_if_preview(azcli_script: str, subscription_id: Optional[str] = None) -> Dict[str, Any]: |
| 71 | + """ |
| 72 | + Preview deployment changes using Azure what-if functionality |
| 73 | + |
| 74 | + Args: |
| 75 | + function_app_url: Base URL of your Azure Function App |
| 76 | + azcli_script: Azure CLI script to analyze |
| 77 | + subscription_id: Optional fallback subscription ID if not in script |
| 78 | + |
| 79 | + Returns: |
| 80 | + Dictionary with what-if preview result |
| 81 | + """ |
| 82 | + url = f"{FUNCTION_APP_URL.rstrip('/')}/api/what_if_preview" |
| 83 | + |
| 84 | + headers = { |
| 85 | + 'Content-Type': 'application/json', |
| 86 | + 'Accept': 'application/json' |
| 87 | + } |
| 88 | + |
| 89 | + # Get access token from Azure CLI |
| 90 | + access_token = get_azure_cli_access_token() |
| 91 | + if not access_token: |
| 92 | + return { |
| 93 | + "error": "Failed to get access token from Azure CLI. Please ensure you are logged in with 'az login'", |
| 94 | + "details": "The what-if service requires client credentials to access your subscription. Please provide an access token.", |
| 95 | + "success": False |
| 96 | + } |
| 97 | + |
| 98 | + # Use Authorization header for access token |
| 99 | + headers['Authorization'] = f'Bearer {access_token}' |
| 100 | + |
| 101 | + payload = {"azcli_script": azcli_script} |
| 102 | + if subscription_id: |
| 103 | + payload["subscription_id"] = subscription_id |
| 104 | + |
| 105 | + try: |
| 106 | + response = requests.post(url, json=payload, headers=headers, timeout=300) |
| 107 | + return response.json() |
| 108 | + except requests.RequestException as e: |
| 109 | + raise e |
0 commit comments