Skip to content

az rest cmd with json body calling #30527

@LRomano72

Description

@LRomano72

Describe the bug

Describe the bug

When using a mix of PowerShell, AZ CLI, VS code with .azcli file, the az rest cmd returns the

In trying to work with Azure Cost Management's Scheduled Actions: https://learn.microsoft.com/en-us/rest/api/cost-management/scheduled-actions/create-or-update-by-scope?view=rest-cost-management-2022-10-01&tabs=HTTP

The goal was to subscribe to cost details of the Accumulated Costs View via emails but I wanted to create they programmatically vs the Azure Portal.

To reduce the number of tools and util's required, I used the "az rest" cmd to build up the payload, request and response. All the code and json object is the same but when called the Az Rest cmd it fails. PowerShell's Invoke-RestMethod is able to handle this. Details to follow.

Related command

az rest

Errors

Error:
cli.azure.cli.core.azclierror: Traceback (most recent call last):
File "D:\a_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\knack/cli.py", line 233, in invoke
File "D:\a_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/init.py", line 666, in execute
File "D:\a_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/init.py", line 733, in _run_jobs_serially
File "D:\a_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/init.py", line 703, in _run_job
File "D:\a_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/init.py", line 336, in call
File "D:\a_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/command_operation.py", line 121, in handler
File "D:\a_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/command_modules/util/custom.py", line 24, in rest_call
File "D:\a_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/util.py", line 1010, in send_raw_request
azure.cli.core.azclierror.HTTPError: Bad Request({"error":{"code":"BadRequest","message":"Invalid property in the request. PropertyName: ","details":null}})

cli.azure.cli.core.azclierror: Bad Request({"error":{"code":"BadRequest","message":"Invalid property in the request. PropertyName: ","details":null}})
az_command_data_logger: Bad Request({"error":{"code":"BadRequest","message":"Invalid property in the request. PropertyName: ","details":null}})
cli.knack.cli: Event: Cli.PostExecute [<function AzCliLogging.deinit_cmd_metadata_logging at 0x00000284CC311EE0>]
az_command_data_logger: exit code: 1
cli.main: Command ran in 3.696 seconds (init: 0.330, invoke: 3.367)
cli.azure.cli.core.decorators: Suppress exception:
Traceback (most recent call last):
File "D:\a_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/main.py", line 53, in
File "D:\a_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/main.py", line 46, in
SystemExit: 1

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:\a_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/decorators.py", line 79, in wrapped_func
File "D:\a_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/telemetry.py", line 129, in generate_payload
File "json_init
.py", line 238, in dumps
File "json\encoder.py", line 200, in encode
File "json\encoder.py", line 258, in iterencode
File "json\encoder.py", line 180, in default
TypeError: Object of type HTTPError is not JSON serializable

telemetry.main: Split cli events and extra events failure: the JSON object must be str, bytes or bytearray, not NoneType

Issue script & Debug output

To Reproduce:

Steps to reproduce the behavior. Note that argument values have been redacted, as they may contain sensitive information.

  • Install Az cli latest
  • Install PowerShell 7+
  • Install VS Code
  • Login to Azure with Az Login, connect to your tenant and subscription
  • Create a file Testfile.azcli and use the PowerShell code below, update for your scenario and specifics:

Create or update a scheduled action at Subscription level

$subscriptionName = "<subscription_name>"
$apiVersion = "2022-10-01" #Matches the version in Azure Portal calls but not the latest
$subscriptionId = (az account list --query "[?name=='$subscriptionName'].id" -o tsv)
$startDate = (Get-Date).ToString("yyyy-MM-ddT13:00:00.000Z")
$endDate = (Get-Date).AddDays(365).ToString("yyyy-MM-ddT05:00:00.000Z")
$notificationEmail = "<notify_email>"
#$toEmail = "<to_email>"
$message = "This is the weekly accumulated cost report for: $subscriptionName"
$displayName = "$subscriptionName Accumulated Costs - Weekly Report"
$subject = "$subscriptionName Accumulated Costs - Weekly Report"
$scope = "/subscriptions/$subscriptionId"
#$scheduledActionName = $displayName -replace ' ', '' -replace '[A-Z]', { $_.Value.ToLower() } #Name field
$scheduledActionName = "<testnameforscheduledAction>"
$baseUrlCreateScheduledAction = "https://management.azure.com/${scope}/providers/Microsoft.CostManagement/scheduledActions/${scheduledActionName}"
#$baseUrlCreateScheduledAction = "https://management.azure.com/providers/Microsoft.CostManagement/scheduledActions/${scheduledActionName}"
$viewId = "/subscriptions/$subscriptionId/providers/Microsoft.CostManagement/views/ms:AccumulatedCosts"
$status = "Enabled"
# Create the JSON object, PowerShell Hash
    $jsonObject = @{
        kind = "Email"
        properties = @{
            displayName = $displayName
            notification = @{
                message = $message
                subject = $subject
                to = @($toEmail)
            }
            notificationEmail = $notificationEmail
            schedule = @{
                daysOfWeek = @("Monday")
                endDate = $endDate
                frequency = "Weekly"
                startDate = $startDate
                hourOfDay = 13
            }
            fileDestination = @{
                fileFormats = @()
            }
            scope = $scope
            status = $status
            viewId = $viewId
        }
    }
    # Test the JSON object
    $jsonString = $jsonObject | ConvertTo-Json -Depth 10
    Write-Output $jsonString

**# Not Working
az rest --debug --subscription $subscriptionId --method put --url "${baseUrlCreateScheduledAction}?api-version=${apiVersion}" --headers "Content-Type=application/json" --body $jsonString**

# Make the API call using PowerShell Invoke-RestMethod with debugging - Works
    # Get the auth token using az cli
    $authToken = (az account get-access-token --query accessToken -o tsv)

    try {
        $response = Invoke-RestMethod -Uri "${baseUrlCreateScheduledAction}?api-version=${apiVersion}" -Method Put -Headers @{
            "Authorization" = "Bearer $authToken"
            "Content-Type" = "application/json"
            "Subscription" = $subscriptionId
        } -Body $jsonString -Debug -Verbose

        # Output the response as a JSON string on one line
        Write-Output "Response: $(ConvertTo-Json $response -Depth 10)"
    } catch {
        Write-Error "Error making API call: $_"
    }

Expected behavior

Az Rest would work or provide more details on why it didn't work for this scenario

Environment Summary

Windows-10-10.0.19045-SP0
Python 3.12.7
Installer: MSI

azure-cli 2.67.0

Extensions:
application-insights 1.2.2
appservice-kube 0.1.10
azure-devops 1.0.1
datafactory 1.0.2
logic 1.1.0
resource-graph 2.1.0

Dependencies:
msal 1.31.0
azure-mgmt-resource 23.1.1

Additional context

Metadata

Metadata

Assignees

Labels

ARMaz resource/group/lock/tag/deployment/policy/managementapp/account management-groupAuto-AssignAuto assign by botService AttentionThis issue is responsible by Azure service team.Similar-IssuebugThis issue requires a change to an existing behavior in the product in order to be resolved.customer-reportedIssues that are reported by GitHub users external to the Azure organization.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions