Skip to content

Azure - Reference

This section provides a structured breakdown of the main application module and its supporting utilities used in the eraXplor_azure project.

eraXplor source code


Main Application Module

Entry Point

eraXplor - Azure Cost Export Tool

This is the main entry point for the eraXplor_azure CLI tool, which enables users to export Azure cost and usage data using the Azure Cost Management API.

The tool supports multiple grouping dimensions (subscription, ServiceName, ResourceGroupName) and provides both daily and monthly cost aggregation granularity.

Command Line Arguments

--start-date, -s DATE Start date in YYYY,MM,DD format. Default: 3 months prior

--end-date, -e DATE End date in YYYY,MM,DD format. Default: Today date.

--group-by, -g GROUPBY Cost grouping dimension. Options: - subscription (default) - ServiceName - ResourceGroupName

--granularity, -G GRANULARITY Time granularity. Options: - Monthly (default) - Daily

--out, -o FILENAME Output CSV filename. Default: az_cost_report.csv

Examples:

  1. Basic usage with default settings: eraXplor-azure

  2. Custom date range: eraXplor-azure -s 2025,01,01 -e 2025,03,30

  3. Group by service name with daily granularity: eraXplor-azure -g ServiceName -G Daily

  4. Export to custom filename: eraXplor-azure -o my_cost_report.csv

Notes
  • Ensure that the environment is properly authenticated with Azure using DefaultAzureCredential.
  • Date strings must follow the exact "YYYY,MM,DD" format to avoid parsing errors.
  • Depending on the size of the date range and granularity, response time may vary.
  • The tool queries all subscriptions accessible by the authenticated principal.

main()

Orchestrates and manage the cost export workflow.

This function serves as the main entry point for the eraXplor_azure CLI tool. It coordinates the entire cost export process by: 1. Displaying the application banner with version information 2. Parsing command-line arguments for configuration 3. Retrieving all accessible Azure subscriptions 4. Fetching cost data using the Azure Cost Management API 5. Exporting the results to a CSV file

The function uses the following workflow
  • generate_banner(): Displays the eraXplor banner
  • parser(): Parses CLI arguments
  • list_subs(): Retrieves subscription details
  • cost_export(): Fetches cost data for all subscriptions
  • csv_export(): Writes results to CSV format

Returns:

Name Type Description
None None

This function does not return a value. It prints output directly to the console and writes the cost report to a CSV file.

Example

if name == "main": ... main()

Note

This function is typically called from the command line and should not be imported directly for programmatic use. For programmatic use, import and call the individual utility functions directly.

Source code in src/eraXplor_azure/__main__.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def main() -> None:
    """
    Orchestrates and manage the cost export workflow.

    This function serves as the main entry point for the eraXplor_azure CLI tool.
    It coordinates the entire cost export process by:
    1. Displaying the application banner with version information
    2. Parsing command-line arguments for configuration
    3. Retrieving all accessible Azure subscriptions
    4. Fetching cost data using the Azure Cost Management API
    5. Exporting the results to a CSV file

    The function uses the following workflow:
        - generate_banner(): Displays the eraXplor banner
        - parser(): Parses CLI arguments
        - list_subs(): Retrieves subscription details
        - cost_export(): Fetches cost data for all subscriptions
        - csv_export(): Writes results to CSV format

    Returns:
        None: This function does not return a value. It prints output directly
              to the console and writes the cost report to a CSV file.

    Raises:
        Any exceptions raised by the underlying Azure SDK calls or file I/O
        operations are propagated to the caller.

    Example:
        >>> if __name__ == "__main__":
        ...     main()

    Note:
        This function is typically called from the command line and should
        not be imported directly for programmatic use. For programmatic use,
        import and call the individual utility functions directly.
    """

    # Banner
    banner_format, copyright_notice = generate_banner()
    print(f"\n\n {termcolor.colored(banner_format, color="green")}")
    print(f"{termcolor.colored(copyright_notice, color="green")}", end="\n\n")

    # Fetch Parsed parameters by command line
    arg_parser = parser().parse_args()
    start_date_input = arg_parser.start_date
    end_date_input = arg_parser.end_date
    group_by = arg_parser.group_by
    granularity_input = arg_parser.granularity
    filename_input = arg_parser.out

    # Fetch detailed subscriptions list
    subscriptions_list_detailed = list_subs()

    # Parsing data to subscription cost export func
    cm_client_query_results = cost_export(
        group_by=group_by,
        subscriptions_list_detailed=subscriptions_list_detailed,
        start_date=start_date_input,
        end_date=end_date_input,
        granularity=granularity_input,
    )

    # Parsing date to csv_export func
    csv_export(cm_client_query_results=cm_client_query_results, filename=filename_input)

This is the primary script responsible for orchestrating the user workflow. It handles user input, invokes Azure cost data retrieval, and manages data export functionality.


Utility Modules

Module to display the eraXplor application banner and copyright notice.

This module provides the visual branding elements for the eraXplor Azure cost export tool. It uses pyfiglet to generate an ASCII art banner and includes version and copyright information for display in the CLI interface.

The banner is displayed at the start of the main() function to provide visual feedback to users and establish the application's identity.

Dependencies
  • pyfiglet: For generating ASCII art text banners
Example

from eraXplor_azure.utils.banner_utils import banner banner_format, copyright_notice = banner() print(banner_format)

banner()

Generates a banner and copyright notice for the eraXplor application.

Creates an ASCII art banner using the 'slant' font with the application name, along with a formatted copyright notice containing version information and contact details.

Returns:

Name Type Description
tuple

A tuple containing two strings: - banner_format (str): ASCII art banner with the text "eraXplor" - copyright_notice (str): Formatted copyright and version information

Example

banner_format, copyright_notice = banner() print(banner_format) print(copyright_notice)

Note

The copyright year is currently set to 2025 and should be updated annually. The version number reflects the current release version of the eraXplor package.

Source code in src/eraXplor_azure/utils/banner_utils.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def banner():
    """
    Generates a banner and copyright notice for the eraXplor application.

    Creates an ASCII art banner using the 'slant' font with the application name,
    along with a formatted copyright notice containing version information and
    contact details.

    Returns:
        tuple: A tuple containing two strings:
            - banner_format (str): ASCII art banner with the text "eraXplor"
            - copyright_notice (str): Formatted copyright and version information

    Example:
        >>> banner_format, copyright_notice = banner()
        >>> print(banner_format)
        >>> print(copyright_notice)

    Note:
        The copyright year is currently set to 2025 and should be updated
        annually. The version number reflects the current release version
        of the eraXplor package.
    """

    copyright_notice = """╔══════════════════════════════════════════════════╗
║  © 2025 Mohamed eraki                            ║
║  mohamed-ibrahim2021@outlook.com                 ║
║  Version: 3.3.0                                  ║
║  eraXplor - Azure Cost exporter Tool             ║
╚══════════════════════════════════════════════════╝
    """
    banner_format = pyfiglet.figlet_format("eraXplor", font='slant')
    return banner_format, copyright_notice

Responsible for rendering styled ASCII banners and displaying copyright information used in the CLI interface.


Cost Export Utilities

Module for exporting Azure cost data using the Azure Cost Management API.

This module provides functionality to query and retrieve Azure cost and usage data using the Azure Cost Management API. It supports multiple grouping dimensions including subscription, ServiceName, and ResourceGroupName, with both daily and monthly granularity options.

The module includes
  • cost_export: Main function to fetch cost data across all subscriptions
  • list_subs: Retrieves details of all accessible Azure subscriptions
  • _subs_cost_export: Internal function for subscription-level cost export
  • _cost_export_subfunc: Internal function for dimension-based cost export
Dependencies
  • azure-identity: For DefaultAzureCredential authentication
  • azure-mgmt-costmanagement: For Cost Management API access
  • azure-mgmt-resource: For Subscription Client access
  • rich: For live progress display
Example

from eraXplor_azure.utils.cost_export_utils import cost_export, list_subs subscriptions = list_subs() cost_data = cost_export( ... group_by='subscription', ... subscriptions_list_detailed=subscriptions, ... start_date='2025,01,01', ... end_date='2025,01,31', ... granularity='Monthly' ... )

cost_export(group_by='subscription', subscriptions_list_detailed=None, start_date=None, end_date=None, granularity='Monthly')

Retrieve Azure cost data for all subscriptions over a specified time range.

Executes cost management queries using the Azure Cost Management API to extract cost data for all accessible subscriptions, aggregated by the selected dimension and granularity (Daily or Monthly).

This is the main entry point for fetching cost data. The function delegates to internal helper functions based on the group_by parameter: - 'subscription': Uses _subs_cost_export for per-subscription breakdown - 'ServiceName' or 'ResourceGroupName': Uses _cost_export_subfunc

Parameters:

Name Type Description Default
group_by str

Dimension to group costs by. Valid values: - 'subscription' (default): Group by Azure subscription - 'ServiceName': Group by Azure service name - 'ResourceGroupName': Group by resource group

'subscription'
subscriptions_list_detailed List[dict[str, Any]]

List of subscription dictionaries as returned by list_subs(). Each dictionary should contain 'Subscription_ID', 'Display_Name', and 'Tags'. If None, the function will attempt to retrieve subscriptions automatically.

None
start_date str

Start date of the report period (inclusive). Format: "YYYY,MM,DD" Default: 3 months ago from today.

None
end_date str

End date of the report period (inclusive). Format: "YYYY,MM,DD" Default: Today's date.

None
granularity str

Level of time granularity for aggregation. Valid values: - 'Monthly' (default): Monthly aggregated cost records - 'Daily': Daily cost records

'Monthly'

Returns:

Type Description
List[_CostRecord]

List[_CostRecord]: A list of structured cost records, where each record contains: - TIME_PERIOD: Date or date range (dict with 'Start'/'End' keys for monthly, string for daily) - GROUP_BY: The grouping dimension used - SUBSCRIPTION_ID: Azure subscription ID - DISPLAY_NAME: Subscription display name - PreTaxCost: Formatted cost string with currency (e.g. "123.45 USD") - TAGS: Dictionary of subscription tags or "None"

Raises:

Type Description
AzureError

For Azure API errors.

Exception

For any authentication failures or network issues.

Example

from eraXplor_azure.utils.cost_export_utils import cost_export, list_subs subs = list_subs() costs = cost_export( ... group_by='subscription', ... subscriptions_list_detailed=subs, ... start_date='2025,01,01', ... end_date='2025,01,31', ... granularity='Monthly' ... ) for record in costs: ... print(f"{record['DISPLAY_NAME']}: {record['PreTaxCost']}")

Notes
  • Ensure that the environment is properly authenticated with Azure using DefaultAzureCredential.
  • Date strings must follow the exact "YYYY,MM,DD" format to avoid parsing errors.
  • Depending on the size of the date range and granularity, response time may vary.
  • The function displays progress using rich.live for real-time feedback.
Source code in src/eraXplor_azure/utils/cost_export_utils.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def cost_export(
    group_by: str = 'subscription',
    subscriptions_list_detailed: List[dict[str, Any]] = None,
    start_date: str = None,
    end_date: str = None,
    granularity: str = 'Monthly',
) -> List[_CostRecord]:
    """
    Retrieve Azure cost data for all subscriptions over a specified time range.

    Executes cost management queries using the Azure Cost Management API to extract
    cost data for all accessible subscriptions, aggregated by the selected dimension
    and granularity (Daily or Monthly).

    This is the main entry point for fetching cost data. The function delegates to
    internal helper functions based on the group_by parameter:
        - 'subscription': Uses _subs_cost_export for per-subscription breakdown
        - 'ServiceName' or 'ResourceGroupName': Uses _cost_export_subfunc

    Args:
        group_by (str, optional):
            Dimension to group costs by. Valid values:
            - 'subscription' (default): Group by Azure subscription
            - 'ServiceName': Group by Azure service name
            - 'ResourceGroupName': Group by resource group

        subscriptions_list_detailed (List[dict[str, Any]], optional):
            List of subscription dictionaries as returned by list_subs().
            Each dictionary should contain 'Subscription_ID', 'Display_Name',
            and 'Tags'. If None, the function will attempt to retrieve
            subscriptions automatically.

        start_date (str, optional):
            Start date of the report period (inclusive).
            Format: "YYYY,MM,DD"
            Default: 3 months ago from today.

        end_date (str, optional):
            End date of the report period (inclusive).
            Format: "YYYY,MM,DD"
            Default: Today's date.

        granularity (str, optional):
            Level of time granularity for aggregation. Valid values:
            - 'Monthly' (default): Monthly aggregated cost records
            - 'Daily': Daily cost records

    Returns:
        List[_CostRecord]:
            A list of structured cost records, where each record contains:
            - TIME_PERIOD: Date or date range (dict with 'Start'/'End' keys for monthly,
              string for daily)
            - GROUP_BY: The grouping dimension used
            - SUBSCRIPTION_ID: Azure subscription ID
            - DISPLAY_NAME: Subscription display name
            - PreTaxCost: Formatted cost string with currency (e.g. "123.45 USD")
            - TAGS: Dictionary of subscription tags or "None"

    Raises:
        azure.core.exceptions.AzureError: For Azure API errors.
        Exception: For any authentication failures or network issues.

    Example:
        >>> from eraXplor_azure.utils.cost_export_utils import cost_export, list_subs
        >>> subs = list_subs()
        >>> costs = cost_export(
        ...     group_by='subscription',
        ...     subscriptions_list_detailed=subs,
        ...     start_date='2025,01,01',
        ...     end_date='2025,01,31',
        ...     granularity='Monthly'
        ... )
        >>> for record in costs:
        ...     print(f"{record['DISPLAY_NAME']}: {record['PreTaxCost']}")

    Notes:
        - Ensure that the environment is properly authenticated with Azure using
          `DefaultAzureCredential`.
        - Date strings must follow the exact "YYYY,MM,DD" format to avoid parsing errors.
        - Depending on the size of the date range and granularity, response time may vary.
        - The function displays progress using rich.live for real-time feedback.
    """

    credential = DefaultAzureCredential()
    cm_client = CostManagementClient(credential)
    cm_client_query_results = []

    if group_by == 'subscription':
        _subs_cost_export(
            group_by=group_by,
            subscriptions_list_detailed=subscriptions_list_detailed,
            start_date=start_date,
            end_date=end_date,
            granularity=granularity,
            cm_client=cm_client,
            cm_client_query_results=cm_client_query_results,
        )
        return cm_client_query_results


    if group_by == 'ServiceName':
        _cost_export_subfunc(
            group_by=group_by,
            subscriptions_list_detailed=subscriptions_list_detailed,
            start_date=start_date,
            end_date=end_date,
            granularity=granularity,
            cm_client=cm_client,
            cm_client_query_results=cm_client_query_results,
        )
        return cm_client_query_results    

    if group_by == 'ResourceGroupName':
        _cost_export_subfunc(
            group_by=group_by,
            subscriptions_list_detailed=subscriptions_list_detailed,
            start_date=start_date,
            end_date=end_date,
            granularity=granularity,
            cm_client=cm_client,
            cm_client_query_results=cm_client_query_results,
        )
        return cm_client_query_results   

list_subs()

Retrieve details of all Azure subscriptions accessible by the authenticated principal.

Uses the Azure SubscriptionClient to list all subscriptions available to the current authentication context (DefaultAzureCredential). Returns detailed information including subscription ID, display name, tenant ID, and tags.

Returns:

Type Description

List[dict[str, Any]]: A list of subscription dictionaries, where each dictionary contains: - 'Subscription_ID' (str): The unique Azure subscription ID - 'Display_Name' (str): The human-readable subscription name - 'Tenant_ID' (str): The Azure tenant ID associated with the subscription - 'Tags' (dict or None): Dictionary of subscription tags if any exist

Raises:

Type Description
AzureError

For Azure API errors.

Exception

For authentication failures.

Example

from eraXplor_azure.utils.cost_export_utils import list_subs subscriptions = list_subs() for sub in subscriptions: ... print(f"{sub['Display_Name']}: {sub['Subscription_ID']}")

Note
  • Requires appropriate Azure RBAC permissions to list subscriptions.
  • The authenticated principal must have Reader role or equivalent on the subscriptions to be listed.
  • Tags are optional and may be None for subscriptions without tags.
Source code in src/eraXplor_azure/utils/cost_export_utils.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def list_subs():
    """
    Retrieve details of all Azure subscriptions accessible by the authenticated principal.

    Uses the Azure SubscriptionClient to list all subscriptions available to the
    current authentication context (DefaultAzureCredential). Returns detailed
    information including subscription ID, display name, tenant ID, and tags.

    Returns:
        List[dict[str, Any]]:
            A list of subscription dictionaries, where each dictionary contains:
            - 'Subscription_ID' (str): The unique Azure subscription ID
            - 'Display_Name' (str): The human-readable subscription name
            - 'Tenant_ID' (str): The Azure tenant ID associated with the subscription
            - 'Tags' (dict or None): Dictionary of subscription tags if any exist

    Raises:
        azure.core.exceptions.AzureError: For Azure API errors.
        Exception: For authentication failures.

    Example:
        >>> from eraXplor_azure.utils.cost_export_utils import list_subs
        >>> subscriptions = list_subs()
        >>> for sub in subscriptions:
        ...     print(f"{sub['Display_Name']}: {sub['Subscription_ID']}")

    Note:
        - Requires appropriate Azure RBAC permissions to list subscriptions.
        - The authenticated principal must have Reader role or equivalent
          on the subscriptions to be listed.
        - Tags are optional and may be None for subscriptions without tags.
    """
    _credential = DefaultAzureCredential()
    _subscription_client = SubscriptionClient(_credential)
    _subscriptions = list(_subscription_client.subscriptions.list())

    subscriptions_list_detailed = []
    # subscriptions_with_tags_list = []

    for sub in _subscriptions:
        subscriptions_list_detailed.append(
            {
                "Subscription_ID": sub.subscription_id,
                "Display_Name": sub.display_name,
                "Tenant_ID": sub.tenant_id,
                "Tags": sub.tags,
            }
        )
    return subscriptions_list_detailed

Contains functions for retrieving cost and usage reports from Azure Cost Explorer using CostManagementClient


CSV Export Utilities

Module for exporting Azure cost data to CSV format.

This module provides functionality to write Azure cost and usage data to CSV files with standardized formatting. It is typically used in conjunction with the cost_export() function to persist cost data for further analysis or reporting.

The CSV output includes the following columns
  • TIME_PERIOD: Date or date range for the cost record
  • GROUP_BY: The grouping dimension used (e.g. 'SUBSCRIPTION_ID', currency)
  • SUBSCRIPTION_ID: The Azure subscription ID
  • DISPLAY_NAME: The subscription display name
  • PreTaxCost: The cost amount with currency
  • TAGS: Subscription tags (if available)
Example

from eraXplor_azure.utils.cost_export_utils import cost_export, list_subs from eraXplor_azure.utils.csv_export_utils import csv_export subs = list_subs() costs = cost_export( ... group_by='subscription', ... subscriptions_list_detailed=subs, ... start_date='2025,01,01', ... end_date='2025,01,31' ... ) csv_export(cm_client_query_results=costs, filename='cost_report.csv')

csv_export(cm_client_query_results, filename)

Exports Azure cost data to a CSV file with standardized formatting.

Takes the output from cost_export() and writes it to a CSV file with consistent column headers and proper formatting. The CSV will contain cost records with their associated metadata including time period, grouping information, subscription details, and tags.

Parameters:

Name Type Description Default
cm_client_query_results List[Dict[str, Any]]

List of cost data dictionaries as returned by cost_export(). Each dictionary should contain the following keys: - TIME_PERIOD (str): Date or date range for the cost record - GROUP_BY (str): The grouping dimension used - SUBSCRIPTION_ID (str): The Azure subscription ID - DISPLAY_NAME (str): The subscription display name - PreTaxCost (str): Cost amount formatted with currency - TAGS (dict or str): Subscription tags or "None"

required
filename str

Output filename for the CSV file. Defaults to 'az_cost_report.csv' if not specified. The file will be created in the current working directory unless a path is included in the filename.

required

Returns:

Name Type Description
None None

This function writes directly to file and prints a confirmation message to stdout, but does not return any value.

Raises:

Type Description
IOError

If the file cannot be created or written to.

KeyError

If required keys are missing from the input dictionaries.

Example

from eraXplor_azure.utils.csv_export_utils import csv_export costs = [ ... { ... 'TIME_PERIOD': {'Start': '2025-01-01', 'End': '2025-01-31'}, ... 'GROUP_BY': 'SUBSCRIPTION_ID', ... 'SUBSCRIPTION_ID': 'sub-12345', ... 'DISPLAY_NAME': 'My Subscription', ... 'PreTaxCost': '123.45 USD', ... 'TAGS': {'env': 'production'} ... } ... ] csv_export(cm_client_query_results=costs, filename='report.csv') Data exported to report.csv

Notes
  • The function uses UTF-8 encoding for proper handling of special characters.
  • A confirmation message is printed to console upon successful export.
  • Existing files with the same name will be overwritten.
Source code in src/eraXplor_azure/utils/csv_export_utils.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def csv_export(
    cm_client_query_results: List[Dict[str, Any]],
    filename: str,
    ) -> None:
    """
    Exports Azure cost data to a CSV file with standardized formatting.

    Takes the output from cost_export() and writes it to a CSV file with
    consistent column headers and proper formatting. The CSV will contain
    cost records with their associated metadata including time period,
    grouping information, subscription details, and tags.

    Args:
        cm_client_query_results (List[Dict[str, Any]]):
            List of cost data dictionaries as returned by cost_export().
            Each dictionary should contain the following keys:
            - TIME_PERIOD (str): Date or date range for the cost record
            - GROUP_BY (str): The grouping dimension used
            - SUBSCRIPTION_ID (str): The Azure subscription ID
            - DISPLAY_NAME (str): The subscription display name
            - PreTaxCost (str): Cost amount formatted with currency
            - TAGS (dict or str): Subscription tags or "None"

        filename (str):
            Output filename for the CSV file. Defaults to 'az_cost_report.csv'
            if not specified. The file will be created in the current working
            directory unless a path is included in the filename.

    Returns:
        None: This function writes directly to file and prints a confirmation
              message to stdout, but does not return any value.

    Raises:
        IOError: If the file cannot be created or written to.
        KeyError: If required keys are missing from the input dictionaries.

    Example:
        >>> from eraXplor_azure.utils.csv_export_utils import csv_export
        >>> costs = [
        ...     {
        ...         'TIME_PERIOD': {'Start': '2025-01-01', 'End': '2025-01-31'},
        ...         'GROUP_BY': 'SUBSCRIPTION_ID',
        ...         'SUBSCRIPTION_ID': 'sub-12345',
        ...         'DISPLAY_NAME': 'My Subscription',
        ...         'PreTaxCost': '123.45 USD',
        ...         'TAGS': {'env': 'production'}
        ...     }
        ... ]
        >>> csv_export(cm_client_query_results=costs, filename='report.csv')
        Data exported to report.csv

    Notes:
        - The function uses UTF-8 encoding for proper handling of special characters.
        - A confirmation message is printed to console upon successful export.
        - Existing files with the same name will be overwritten.
    """
    # Create a CSV file with write mode
    with open(filename, mode="w", newline="", encoding="utf-8") as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(
            [
                "TIME_PERIOD",
                "GROUP_BY",
                "SUBSCRIPTION_ID",
                "DISPLAY_NAME",
                "PreTaxCost",
                "TAGS",
            ]
        )
        for row in cm_client_query_results:
            time_period = row["TIME_PERIOD"]
            group_by = row["GROUP_BY"]
            subscription_id = row["SUBSCRIPTION_ID"]
            display_name = row["DISPLAY_NAME"]
            PreTaxCost = row.get("PreTaxCost")
            tags = row.get("TAGS", {})
            writer.writerow(
                [time_period, group_by, subscription_id, display_name, PreTaxCost, tags]
                )
    print(f"\n Data exported to {filename}")

Provides functionality to export retrieved cost data into a structured CSV format.