# Buggy code
def _template_progress(self, correlation_id):  # pylint: disable=no-self-use
    """gets the progress for template deployments"""
    from azure.cli.core.commands.client_factory import get_mgmt_service_client
    from azure.monitor import MonitorClient

    if correlation_id is not None:  # pylint: disable=too-many-nested-blocks
        formatter = "eventTimestamp ge {}"

        end_time = datetime.datetime.utcnow()
        start_time = end_time - datetime.timedelta(seconds=DEFAULT_QUERY_TIME_RANGE)
        odata_filters = formatter.format(start_time.strftime("%Y-%m-%dT%H:%M:%SZ"))

        odata_filters = "{} and {} eq '{}'".format(
            odata_filters, "correlationId", correlation_id
        )

        activity_log = get_mgmt_service_client(MonitorClient).activity_logs.list(
            filter=odata_filters
        )

        results = []
        max_events = 50  # default max value for events in list_activity_log
        for index, item in enumerate(activity_log):
            if index < max_events:
                results.append(item)
            else:
                break

        if results:
            for event in results:
                update = False
                long_name = event.resource_id.split("/")[-1]
                if long_name not in self.deploy_dict:
                    self.deploy_dict[long_name] = {}
                    update = True
                deploy_values = self.deploy_dict[long_name]

                checked_values = {
                    str(event.resource_type.value): "type",
                    str(event.status.value): "status value",
                    str(event.event_name.value): "request",
                }
                try:
                    checked_values[str(event.properties.get("statusCode", ""))] = (
                        "status"
                    )
                except AttributeError:
                    pass

                if deploy_values.get(
                    "timestamp", None
                ) is None or event.event_timestamp > deploy_values.get("timestamp"):
                    for value in checked_values:
                        if deploy_values.get(checked_values[value], None) != value:
                            update = True
                        deploy_values[checked_values[value]] = value
                    deploy_values["timestamp"] = event.event_timestamp

                    # don't want to show the timestamp
                    json_val = deploy_values.copy()
                    json_val.pop("timestamp", None)
                    if deploy_values["status value"] != "Started":
                        result = deploy_values["status value"] + ": " + long_name
                        result += " (" + deploy_values["type"] + ")"

                        if update:
                            logger.info(result)


# Traceback (KeyError)
ERROR: 'status value'
Traceback (most recent call last):
File "/opt/az/lib/python3.6/site-packages/azure/cli/main.py", line 36, in main
cmd_result = APPLICATION.execute(args)
File "/opt/az/lib/python3.6/site-packages/azure/cli/core/application.py", line 211, in execute
result = expanded_arg.func(params)
File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 352, in __call__
return self.handler(*args, **kwargs)
File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 551, in _execute_command
reraise(*sys.exc_info())
File "/opt/az/lib/python3.6/site-packages/six.py", line 686, in reraise
raise value
File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 538, in _execute_command
return LongRunningOperation('Starting {}'.format(name))(result)
File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 220, in __call__
self._template_progress(correlation_id)
File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 198, in _template_progress
if deploy_values['status value'] != 'Started':
KeyError: 'status value'

Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 290, in load
**kw)
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
Deployment failed.

# Fixed code
def _template_progress(self, correlation_id):  # pylint: disable=no-self-use
    """gets the progress for template deployments"""
    from azure.cli.core.commands.client_factory import get_mgmt_service_client
    from azure.monitor import MonitorClient

    if correlation_id is not None:  # pylint: disable=too-many-nested-blocks
        formatter = "eventTimestamp ge {}"

        end_time = datetime.datetime.utcnow()
        start_time = end_time - datetime.timedelta(seconds=DEFAULT_QUERY_TIME_RANGE)
        odata_filters = formatter.format(start_time.strftime("%Y-%m-%dT%H:%M:%SZ"))

        odata_filters = "{} and {} eq '{}'".format(
            odata_filters, "correlationId", correlation_id
        )

        activity_log = get_mgmt_service_client(MonitorClient).activity_logs.list(
            filter=odata_filters
        )

        results = []
        max_events = 50  # default max value for events in list_activity_log
        for index, item in enumerate(activity_log):
            if index < max_events:
                results.append(item)
            else:
                break

        if results:
            for event in results:
                update = False
                long_name = event.resource_id.split("/")[-1]
                if long_name not in self.deploy_dict:
                    self.deploy_dict[long_name] = {}
                    update = True
                deploy_values = self.deploy_dict[long_name]

                checked_values = {
                    str(event.resource_type.value): "type",
                    str(event.status.value): "status value",
                    str(event.event_name.value): "request",
                }
                try:
                    checked_values[str(event.properties.get("statusCode", ""))] = (
                        "status"
                    )
                except AttributeError:
                    pass

                if deploy_values.get(
                    "timestamp", None
                ) is None or event.event_timestamp > deploy_values.get("timestamp"):
                    for value in checked_values:
                        if deploy_values.get(checked_values[value], None) != value:
                            update = True
                        deploy_values[checked_values[value]] = value
                    deploy_values["timestamp"] = event.event_timestamp

                    # don't want to show the timestamp
                    json_val = deploy_values.copy()
                    json_val.pop("timestamp", None)
                    if deploy_values.get("status value", None) != "Started":
                        result = deploy_values["status value"] + ": " + long_name
                        result += " (" + deploy_values.get("type", "") + ")"

                        if update:
                            logger.info(result)