|
22 | 22 | from azure.cli.core.util import user_confirmation |
23 | 23 | from azure.cli.core.azclierror import ( |
24 | 24 | AzureInternalError, |
| 25 | + AzureResponseError, |
25 | 26 | FileOperationError, |
26 | 27 | InvalidArgumentValueError, |
27 | 28 | RequiredArgumentMissingError, |
@@ -550,7 +551,40 @@ def __read_kv_from_file( |
550 | 551 | except OSError: |
551 | 552 | raise FileOperationError("File is not available.") |
552 | 553 |
|
| 554 | + flattened_data = __flatten_config_data( |
| 555 | + config_data=config_data, |
| 556 | + format_=format_, |
| 557 | + content_type=content_type, |
| 558 | + prefix_to_add=prefix_to_add, |
| 559 | + depth=depth, |
| 560 | + separator=separator |
| 561 | + ) |
| 562 | + |
| 563 | + # convert to KeyValue list |
| 564 | + key_values = [] |
| 565 | + for k, v in flattened_data.items(): |
| 566 | + if validate_import_key(key=k): |
| 567 | + key_values.append(KeyValue(key=k, value=v)) |
| 568 | + return key_values |
| 569 | + |
| 570 | + |
| 571 | +def __flatten_config_data(config_data, format_, content_type, prefix_to_add="", depth=None, separator=None): |
| 572 | + """ |
| 573 | + Flatten configuration data into a dictionary of key-value pairs. |
| 574 | +
|
| 575 | + Args: |
| 576 | + config_data: The configuration data to flatten (dict or list) |
| 577 | + format_ (str): The format of the configuration data ('json', 'yaml', 'properties') |
| 578 | + content_type (str): Content type for JSON validation |
| 579 | + prefix_to_add (str): Prefix to add to each key |
| 580 | + depth (int): Maximum depth for flattening hierarchical data |
| 581 | + separator (str): Separator for hierarchical keys |
| 582 | +
|
| 583 | + Returns: |
| 584 | + dict: Flattened key-value pairs |
| 585 | + """ |
553 | 586 | flattened_data = {} |
| 587 | + |
554 | 588 | if format_ == "json" and content_type and is_json_content_type(content_type): |
555 | 589 | for key in config_data: |
556 | 590 | __flatten_json_key_value( |
@@ -582,13 +616,7 @@ def __read_kv_from_file( |
582 | 616 | separator=separator, |
583 | 617 | ) |
584 | 618 |
|
585 | | - # convert to KeyValue list |
586 | | - key_values = [] |
587 | | - for k, v in flattened_data.items(): |
588 | | - if validate_import_key(key=k): |
589 | | - key_values.append(KeyValue(key=k, value=v)) |
590 | | - return key_values |
591 | | - |
| 619 | + return flattened_data |
592 | 620 |
|
593 | 621 | # App Service <-> List of KeyValue object |
594 | 622 |
|
@@ -715,6 +743,170 @@ def __read_kv_from_app_service( |
715 | 743 | raise CLIError("Failed to read key-values from appservice.\n" + str(exception)) |
716 | 744 |
|
717 | 745 |
|
| 746 | +def __read_kv_from_kubernetes_configmap( |
| 747 | + cmd, |
| 748 | + aks_cluster, |
| 749 | + configmap_name, |
| 750 | + format_, |
| 751 | + namespace="default", |
| 752 | + prefix_to_add="", |
| 753 | + content_type=None, |
| 754 | + depth=None, |
| 755 | + separator=None |
| 756 | +): |
| 757 | + """ |
| 758 | + Read key-value pairs from a Kubernetes ConfigMap using aks_runcommand. |
| 759 | +
|
| 760 | + Args: |
| 761 | + cmd: The command context object |
| 762 | + aks_cluster (str): Name of the AKS cluster |
| 763 | + configmap_name (str): Name of the ConfigMap to read from |
| 764 | + format_ (str): Format of the data in the ConfigMap (e.g., "json", "yaml") |
| 765 | + namespace (str): Kubernetes namespace where the ConfigMap resides (default: "default") |
| 766 | + prefix_to_add (str): Prefix to add to each key in the ConfigMap |
| 767 | + content_type (str): Content type to apply to the key-values |
| 768 | + depth (int): Maximum depth for flattening hierarchical data |
| 769 | + separator (str): Separator for hierarchical keys |
| 770 | +
|
| 771 | + Returns: |
| 772 | + list: List of KeyValue objects |
| 773 | + """ |
| 774 | + key_values = [] |
| 775 | + from azure.cli.command_modules.acs.custom import aks_runcommand |
| 776 | + from azure.cli.command_modules.acs._client_factory import cf_managed_clusters |
| 777 | + |
| 778 | + # Preserve only the necessary CLI context data |
| 779 | + original_subscription = cmd.cli_ctx.data.get('subscription_id') |
| 780 | + original_safe_params = cmd.cli_ctx.data.get('safe_params', []) |
| 781 | + |
| 782 | + try: |
| 783 | + # Temporarily modify the CLI context |
| 784 | + cmd.cli_ctx.data['subscription_id'] = aks_cluster["subscription"] |
| 785 | + params_to_keep = ["--debug", "--verbose"] |
| 786 | + cmd.cli_ctx.data['safe_params'] = [p for p in original_safe_params if p in params_to_keep] |
| 787 | + # It must be set to return the result. |
| 788 | + cmd.cli_ctx.data['safe_params'].append("--output") |
| 789 | + # Get the AKS client from the factory |
| 790 | + aks_client = cf_managed_clusters(cmd.cli_ctx) |
| 791 | + |
| 792 | + # Command to get the ConfigMap and output it as JSON |
| 793 | + command = f"kubectl get configmap {configmap_name} -n {namespace} -o json" |
| 794 | + |
| 795 | + # Execute the command on the cluster |
| 796 | + result = aks_runcommand(cmd, aks_client, aks_cluster["resource_group"], aks_cluster["name"], command_string=command) |
| 797 | + |
| 798 | + if hasattr(result, 'logs') and result.logs: |
| 799 | + if not hasattr(result, 'exit_code') or result.exit_code == 0: |
| 800 | + try: |
| 801 | + configmap_data = json.loads(result.logs) |
| 802 | + |
| 803 | + # Extract the data section which contains the key-value pairs |
| 804 | + kvs = __extract_kv_from_configmap_data( |
| 805 | + configmap_data, content_type, prefix_to_add, format_, depth, separator) |
| 806 | + |
| 807 | + key_values.extend(kvs) |
| 808 | + except json.JSONDecodeError: |
| 809 | + raise ValueError( |
| 810 | + f"The result from ConfigMap {configmap_name} could not be parsed. {result.logs.strip()}" |
| 811 | + ) |
| 812 | + else: |
| 813 | + raise AzureResponseError(f"{result.logs.strip()}") |
| 814 | + else: |
| 815 | + raise AzureResponseError("Unable to get the ConfigMap.") |
| 816 | + |
| 817 | + return key_values |
| 818 | + except Exception as exception: |
| 819 | + raise AzureInternalError( |
| 820 | + f"Failed to read key-values from ConfigMap '{configmap_name}' in namespace '{namespace}'.\n{str(exception)}" |
| 821 | + ) |
| 822 | + finally: |
| 823 | + # Restore original CLI context data |
| 824 | + cmd.cli_ctx.data['subscription_id'] = original_subscription |
| 825 | + cmd.cli_ctx.data['safe_params'] = original_safe_params |
| 826 | + |
| 827 | + |
| 828 | +def __extract_kv_from_configmap_data(configmap, content_type, prefix_to_add="", format_=None, depth=None, separator=None): |
| 829 | + """ |
| 830 | + Helper function to extract key-value pairs from ConfigMap data. |
| 831 | +
|
| 832 | + Args: |
| 833 | + configmap (dict): The ConfigMap data as a dictionary |
| 834 | + prefix_to_add (str): Prefix to add to each key |
| 835 | + content_type (str): Content type to apply to the key-values |
| 836 | + format_ (str): Format of the data in the ConfigMap (e.g., "json", "yaml") |
| 837 | + depth (int): Maximum depth for flattening hierarchical data |
| 838 | + separator (str): Separator for hierarchical keys |
| 839 | +
|
| 840 | + Returns: |
| 841 | + list: List of KeyValue objects |
| 842 | + """ |
| 843 | + key_values = [] |
| 844 | + |
| 845 | + if not configmap.get('data', None): |
| 846 | + logger.warning("ConfigMap exists but has no data") |
| 847 | + return key_values |
| 848 | + |
| 849 | + for key, value in configmap['data'].items(): |
| 850 | + if format_ in ("json", "yaml", "properties"): |
| 851 | + if format_ == "json": |
| 852 | + try: |
| 853 | + value = json.loads(value) |
| 854 | + except json.JSONDecodeError: |
| 855 | + logger.warning( |
| 856 | + 'Value "%s" for key "%s" is not a well formatted JSON data.', |
| 857 | + value, key |
| 858 | + ) |
| 859 | + continue |
| 860 | + elif format_ == "yaml": |
| 861 | + try: |
| 862 | + value = yaml.safe_load(value) |
| 863 | + except yaml.YAMLError: |
| 864 | + logger.warning( |
| 865 | + 'Value "%s" for key "%s" is not a well formatted YAML data.', |
| 866 | + value, key |
| 867 | + ) |
| 868 | + continue |
| 869 | + else: |
| 870 | + try: |
| 871 | + value = javaproperties.load(io.StringIO(value)) |
| 872 | + except javaproperties.InvalidUEscapeError: |
| 873 | + logger.warning( |
| 874 | + 'Value "%s" for key "%s" is not a well formatted properties data.', |
| 875 | + value, key |
| 876 | + ) |
| 877 | + continue |
| 878 | + |
| 879 | + flattened_data = __flatten_config_data( |
| 880 | + config_data=value, |
| 881 | + format_=format_, |
| 882 | + content_type=content_type, |
| 883 | + prefix_to_add=prefix_to_add, |
| 884 | + depth=depth, |
| 885 | + separator=separator |
| 886 | + ) |
| 887 | + |
| 888 | + for k, v in flattened_data.items(): |
| 889 | + if validate_import_key(key=k): |
| 890 | + key_values.append(KeyValue(key=k, value=v)) |
| 891 | + |
| 892 | + elif validate_import_key(key): |
| 893 | + # If content_type is JSON, validate the value |
| 894 | + if content_type and is_json_content_type(content_type): |
| 895 | + try: |
| 896 | + json.loads(value) |
| 897 | + except json.JSONDecodeError: |
| 898 | + logger.warning( |
| 899 | + 'Value "%s" for key "%s" is not a valid JSON object, which conflicts with the provided content type "%s".', |
| 900 | + value, key, content_type |
| 901 | + ) |
| 902 | + continue |
| 903 | + |
| 904 | + kv = KeyValue(key=prefix_to_add + key, value=value) |
| 905 | + key_values.append(kv) |
| 906 | + |
| 907 | + return key_values |
| 908 | + |
| 909 | + |
718 | 910 | def __validate_import_keyvault_ref(kv): |
719 | 911 | if kv and validate_import_key(kv.key): |
720 | 912 | try: |
|
0 commit comments