Azure / azure-cli

Azure Command-Line Interface
MIT License
4.02k stars 2.99k forks source link

Allow to set update mode for `az resource update` command #25670

Closed t-bzhan closed 1 year ago

t-bzhan commented 1 year ago

Related command

az resource update --ids /subscriptions/27cafca8-b9a4-4264-b399-45d0c9cca1ab/resourcegroups/bo-private/providers/Microsoft.Cdn/profiles/migprofile101 --set identity.type=SystemAssigned --api-version 2022-11-01-preview --debug

Is your feature request related to a problem? Please describe.

From the diagnostic output, it looks like az resource update underlyingly will issue a "GET" request first and then issue a "PUT" instead of "PATCH" to service side.

That might cause problems when the GET API returns read only properties (extendedProperties in below GET response), the following "PUT" might be rejected by backend service.

{
  "id": "/subscriptions/27cafca8-b9a4-4264-b399-45d0c9cca1ab/resourcegroups/bo-private/providers/Microsoft.Cdn/profiles/migprofile101",
  "type": "Microsoft.Cdn/profiles",
  "name": "migprofile101",
  "location": "Global",
  "kind": "frontdoor",
  "tags": {},
  "sku": {
    "name": "Standard_AzureFrontDoor"
  },
  "identity": {
    "type": "SystemAssigned",
    "principalId": "e1acf994-6083-4e83-a90d-cd0f0c5bf42a",
    "tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db47"
  },
  "properties": {
    "originResponseTimeoutSeconds": 30,
    "frontDoorId": "6eb57058-9599-4dc7-b390-b8ce6c277fe4",
    "extendedProperties": {
      "MigratedFrom": "/subscriptions/27cafca8-b9a4-4264-b399-45d0c9cca1ab/resourceGroups/bo-private/providers/Microsoft.Network/frontdoors/mig101"
    },
    "resourceState": "Active",
    "provisioningState": "Succeeded"
  }
}

Describe the solution you'd like

Is it possible to add a new parameter such as --update-mode to indicate whether "PATCH" or "PUT" should be used.

Describe alternatives you've considered

Another way is CLI underlyingly check whether PATCH is supported by the resource, it will prefer "PATCH" and only use "PUT" as a fallback when updating resources.

Additional context

Command diagnostic output:

cli.knack.cli: Command arguments: ['resource', 'update', '--ids', '/subscriptions/27cafca8-b9a4-4264-b399-45d0c9cca1ab/resourcegroups/bo-private/providers/Microsoft.Cdn/profiles/migprofile101', '--set', 'identity.type=SystemAssigned', '--api-version', '2022-11-01-preview', '--debug'] cli.knack.cli: init debug log: Enable color in terminal. Enable VT mode. cli.knack.cli: Event: Cli.PreExecute [] cli.knack.cli: Event: CommandParser.OnGlobalArgumentsCreate [<function CLILogging.on_global_arguments at 0x036C94A8>, <function OutputProducer.on_global_arguments at 0x038AE778>, <function CLIQuery.on_global_arguments at 0x038C33D0>] cli.knack.cli: Event: CommandInvoker.OnPreCommandTableCreate [] cli.azure.cli.core: Modules found from index for 'resource': ['azure.cli.command_modules.resource'] cli.azure.cli.core: Loading command modules: cli.azure.cli.core: Name Load Time Groups Commands cli.azure.cli.core: resource 0.014 47 207 cli.azure.cli.core: Total (1) 0.014 47 207 cli.azure.cli.core: These extensions are not installed and will be skipped: ['azext_ai_examples', 'azext_next'] cli.azure.cli.core: Loading extensions: cli.azure.cli.core: Name Load Time Groups Commands Directory cli.azure.cli.core: Total (0) 0.000 0 0 cli.azure.cli.core: Loaded 47 groups, 207 commands. cli.azure.cli.core: Found a match in the command table. cli.azure.cli.core: Raw command : resource update cli.azure.cli.core: Command table: resource update cli.knack.cli: Event: CommandInvoker.OnPreCommandTableTruncate [<function AzCliLogging.init_command_file_logging at 0x04AAA808>] cli.azure.cli.core.azlogging: metadata file logging enabled - writing logs to 'C:\Users\bzhan.azure\commands\2023-03-03.15-07-56.resource_update.58600.log'. az_command_data_logger: command args: resource update --ids {} --set {} --api-version {} --debug cli.knack.cli: Event: CommandInvoker.OnPreArgumentLoad [<function register_global_subscription_argument..add_subscription_parameter at 0x04B123D0>] cli.knack.cli: Event: CommandInvoker.OnPostArgumentLoad [] cli.knack.cli: Event: CommandInvoker.OnPostCommandTableCreate [<function register_ids_argument..add_ids_arguments at 0x04B12460>, <function register_cache_arguments..add_cache_arguments at 0x04B124F0>] cli.knack.cli: Event: CommandInvoker.OnCommandTableLoaded [] cli.knack.cli: Event: CommandInvoker.OnPreParseArgs [] cli.knack.cli: Event: CommandInvoker.OnPostParseArgs [<function OutputProducer.handle_output_argument at 0x038AE7C0>, <function CLIQuery.handle_query_parameter at 0x038C3418>, <function register_ids_argument..parse_ids_arguments at 0x04B124A8>] cli.azure.cli.core.commands.client_factory: Getting management service client client_type=ResourceManagementClient cli.azure.cli.core.auth.persistence: build_persistence: location='C:\Users\bzhan\.azure\msal_token_cache.bin', encrypt=True cli.azure.cli.core.auth.binary_cache: load: C:\Users\bzhan.azure\msal_http_cache.bin urllib3.util.retry: Converted retries value: 1 -> Retry(total=1, connect=None, read=None, redirect=None, status=None) msal.authority: openid_config = {'token_endpoint': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/token', 'token_endpoint_auth_methods_supported': ['client_secret_post', 'private_key_jwt', 'client_secret_basic'], 'jwks_uri': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/discovery/v2.0/keys', 'response_modes_supported': ['query', 'fragment', 'form_post'], 'subject_types_supported': ['pairwise'], 'id_token_signing_alg_values_supported': ['RS256'], 'response_types_supported': ['code', 'id_token', 'code id_token', 'id_token token'], 'scopes_supported': ['openid', 'profile', 'email', 'offline_access'], 'issuer': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0', 'request_uri_parameter_supported': False, 'userinfo_endpoint': 'https://graph.microsoft.com/oidc/userinfo', 'authorization_endpoint': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/authorize', 'device_authorization_endpoint': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/devicecode', 'http_logout_supported': True, 'frontchannel_logout_supported': True, 'end_session_endpoint': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/logout', 'claims_supported': ['sub', 'iss', 'cloud_instance_name', 'cloud_instance_host_name', 'cloud_graph_host_name', 'msgraph_host', 'aud', 'exp', 'iat', 'auth_time', 'acr', 'nonce', 'preferred_username', 'name', 'tid', 'ver', 'at_hash', 'c_hash', 'email'], 'kerberos_endpoint': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/kerberos', 'tenant_region_scope': 'WW', 'cloud_instance_name': 'microsoftonline.com', 'cloud_graph_host_name': 'graph.windows.net', 'msgraph_host': 'graph.microsoft.com', 'rbac_url': 'https://pas.windows.net'} cli.azure.cli.core.auth.credential_adaptor: CredentialAdaptor.get_token: scopes=('https://management.core.windows.net//.default',), kwargs={} cli.azure.cli.core.auth.msal_authentication: UserCredential.get_token: scopes=('https://management.core.windows.net//.default',), kwargs={} msal.application: Cache hit an AT msal.telemetry: Generate or reuse correlation_id: e5248445-53ef-4110-975f-ede86d7526cc cli.azure.cli.core.sdk.policies: Request URL: 'https://management.azure.com/subscriptions/27cafca8-b9a4-4264-b399-45d0c9cca1ab/resourcegroups/bo-private/providers/Microsoft.Cdn/profiles/migprofile101?api-version=2022-11-01-preview' cli.azure.cli.core.sdk.policies: Request method: 'GET' cli.azure.cli.core.sdk.policies: Request headers: cli.azure.cli.core.sdk.policies: 'Accept': 'application/json' cli.azure.cli.core.sdk.policies: 'x-ms-client-request-id': '1fa8f44e-b992-11ed-b1f2-c8d9d2133ae1' cli.azure.cli.core.sdk.policies: 'CommandName': 'resource update' cli.azure.cli.core.sdk.policies: 'ParameterSetName': '--ids --set --api-version --debug' cli.azure.cli.core.sdk.policies: 'User-Agent': 'AZURECLI/2.40.0 (MSI) azsdk-python-azure-mgmt-resource/21.1.0b1 Python/3.10.5 (Windows-10-10.0.19045-SP0)' cli.azure.cli.core.sdk.policies: 'Authorization': '' cli.azure.cli.core.sdk.policies: Request body: cli.azure.cli.core.sdk.policies: This request has no body urllib3.connectionpool: Starting new HTTPS connection (1): management.azure.com:443 urllib3.connectionpool: https://management.azure.com:443 "GET /subscriptions/27cafca8-b9a4-4264-b399-45d0c9cca1ab/resourcegroups/bo-private/providers/Microsoft.Cdn/profiles/migprofile101?api-version=2022-11-01-preview HTTP/1.1" 200 None cli.azure.cli.core.sdk.policies: Response status: 200 cli.azure.cli.core.sdk.policies: Response headers: cli.azure.cli.core.sdk.policies: 'Cache-Control': 'no-cache' cli.azure.cli.core.sdk.policies: 'Pragma': 'no-cache' cli.azure.cli.core.sdk.policies: 'Transfer-Encoding': 'chunked' cli.azure.cli.core.sdk.policies: 'Content-Type': 'application/json; charset=utf-8' cli.azure.cli.core.sdk.policies: 'Content-Encoding': 'gzip' cli.azure.cli.core.sdk.policies: 'Expires': '-1' cli.azure.cli.core.sdk.policies: 'Vary': 'Accept-Encoding' cli.azure.cli.core.sdk.policies: 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains' cli.azure.cli.core.sdk.policies: 'x-ms-request-id': 'dde091d6-b89e-414e-ba7e-9cdf76976410' cli.azure.cli.core.sdk.policies: 'x-ms-client-request-id': '1fa8f44e-b992-11ed-b1f2-c8d9d2133ae1' cli.azure.cli.core.sdk.policies: 'Server': 'Kestrel' cli.azure.cli.core.sdk.policies: 'x-ms-ratelimit-remaining-subscription-resource-requests': '49' cli.azure.cli.core.sdk.policies: 'x-ms-correlation-request-id': '58df5356-0488-40fe-9488-f2c38ac97bc6' cli.azure.cli.core.sdk.policies: 'x-ms-routing-request-id': 'SOUTHEASTASIA:20230303T070802Z:58df5356-0488-40fe-9488-f2c38ac97bc6' cli.azure.cli.core.sdk.policies: 'X-Content-Type-Options': 'nosniff' cli.azure.cli.core.sdk.policies: 'Date': 'Fri, 03 Mar 2023 07:08:02 GMT' cli.azure.cli.core.sdk.policies: Response content: cli.azure.cli.core.sdk.policies: {"id":"/subscriptions/27cafca8-b9a4-4264-b399-45d0c9cca1ab/resourcegroups/bo-private/providers/Microsoft.Cdn/profiles/migprofile101","type":"Microsoft.Cdn/profiles","name":"migprofile101","location":"Global","kind":"frontdoor","tags":{},"sku":{"name":"Standard_AzureFrontDoor"},"identity":{"type":"SystemAssigned","principalId":"e1acf994-6083-4e83-a90d-cd0f0c5bf42a","tenantId":"72f988bf-86f1-41af-91ab-2d7cd011db47"},"properties":{"originResponseTimeoutSeconds":30,"frontDoorId":"6eb57058-9599-4dc7-b390-b8ce6c277fe4","extendedProperties":{"MigratedFrom":"/subscriptions/27cafca8-b9a4-4264-b399-45d0c9cca1ab/resourceGroups/bo-private/providers/Microsoft.Network/frontdoors/mig101"},"resourceState":"Active","provisioningState":"Succeeded"}} cli.azure.cli.core.util: malformed node or string on line 1: <ast.Name object at 0x03B75C28> cli.azure.cli.core.commands.client_factory: Getting management service client client_type=ResourceManagementClient urllib3.util.retry: Converted retries value: 1 -> Retry(total=1, connect=None, read=None, redirect=None, status=None) msal.authority: openid_config = {'token_endpoint': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/token', 'token_endpoint_auth_methods_supported': ['client_secret_post', 'private_key_jwt', 'client_secret_basic'], 'jwks_uri': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/discovery/v2.0/keys', 'response_modes_supported': ['query', 'fragment', 'form_post'], 'subject_types_supported': ['pairwise'], 'id_token_signing_alg_values_supported': ['RS256'], 'response_types_supported': ['code', 'id_token', 'code id_token', 'id_token token'], 'scopes_supported': ['openid', 'profile', 'email', 'offline_access'], 'issuer': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0', 'request_uri_parameter_supported': False, 'userinfo_endpoint': 'https://graph.microsoft.com/oidc/userinfo', 'authorization_endpoint': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/authorize', 'device_authorization_endpoint': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/devicecode', 'http_logout_supported': True, 'frontchannel_logout_supported': True, 'end_session_endpoint': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/logout', 'claims_supported': ['sub', 'iss', 'cloud_instance_name', 'cloud_instance_host_name', 'cloud_graph_host_name', 'msgraph_host', 'aud', 'exp', 'iat', 'auth_time', 'acr', 'nonce', 'preferred_username', 'name', 'tid', 'ver', 'at_hash', 'c_hash', 'email'], 'kerberos_endpoint': 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/kerberos', 'tenant_region_scope': 'WW', 'cloud_instance_name': 'microsoftonline.com', 'cloud_graph_host_name': 'graph.windows.net', 'msgraph_host': 'graph.microsoft.com', 'rbac_url': 'https://pas.windows.net'} cli.azure.cli.core.auth.credential_adaptor: CredentialAdaptor.get_token: scopes=('https://management.core.windows.net//.default',), kwargs={} cli.azure.cli.core.auth.msal_authentication: UserCredential.get_token: scopes=('https://management.core.windows.net//.default',), kwargs={} msal.application: Cache hit an AT msal.telemetry: Generate or reuse correlation_id: 134168d1-fe03-4ddc-88ce-c987a570446e cli.azure.cli.core.sdk.policies: Request URL: 'https://management.azure.com/subscriptions/27cafca8-b9a4-4264-b399-45d0c9cca1ab/resourcegroups/bo-private/providers/Microsoft.Cdn/profiles/migprofile101?api-version=2022-11-01-preview' cli.azure.cli.core.sdk.policies: Request method: 'PUT' cli.azure.cli.core.sdk.policies: Request headers: cli.azure.cli.core.sdk.policies: 'Content-Type': 'application/json' cli.azure.cli.core.sdk.policies: 'Content-Length': '474' cli.azure.cli.core.sdk.policies: 'Accept': 'application/json' cli.azure.cli.core.sdk.policies: 'x-ms-client-request-id': '1fa8f44e-b992-11ed-b1f2-c8d9d2133ae1' cli.azure.cli.core.sdk.policies: 'CommandName': 'resource update' cli.azure.cli.core.sdk.policies: 'ParameterSetName': '--ids --set --api-version --debug' cli.azure.cli.core.sdk.policies: 'User-Agent': 'AZURECLI/2.40.0 (MSI) azsdk-python-azure-mgmt-resource/21.1.0b1 Python/3.10.5 (Windows-10-10.0.19045-SP0)' cli.azure.cli.core.sdk.policies: 'Authorization': '' cli.azure.cli.core.sdk.policies: Request body: cli.azure.cli.core.sdk.policies: {"location": "Global", "tags": {}, "properties": {"originResponseTimeoutSeconds": 30, "frontDoorId": "6eb57058-9599-4dc7-b390-b8ce6c277fe4", "extendedProperties": {"MigratedFrom": "/subscriptions/27cafca8-b9a4-4264-b399-45d0c9cca1ab/resourceGroups/bo-private/providers/Microsoft.Network/frontdoors/mig101"}, "resourceState": "Active", "provisioningState": "Succeeded"}, "kind": "frontdoor", "sku": {"name": "Standard_AzureFrontDoor"}, "identity": {"type": "SystemAssigned"}}urllib3.connectionpool: Starting new HTTPS connection (1): management.azure.com:443 urllib3.connectionpool: https://management.azure.com:443 "PUT /subscriptions/27cafca8-b9a4-4264-b399-45d0c9cca1ab/resourcegroups/bo-private/providers/Microsoft.Cdn/profiles/migprofile101?api-version=2022-11-01-preview HTTP/1.1" 400 136 cli.azure.cli.core.sdk.policies: Response status: 400 cli.azure.cli.core.sdk.policies: Response headers: cli.azure.cli.core.sdk.policies: 'Cache-Control': 'no-cache' cli.azure.cli.core.sdk.policies: 'Pragma': 'no-cache' cli.azure.cli.core.sdk.policies: 'Content-Length': '136' cli.azure.cli.core.sdk.policies: 'Content-Type': 'application/json' cli.azure.cli.core.sdk.policies: 'Expires': '-1' cli.azure.cli.core.sdk.policies: 'x-ms-ratelimit-remaining-subscription-resource-requests': '24' cli.azure.cli.core.sdk.policies: 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains' cli.azure.cli.core.sdk.policies: 'x-ms-request-id': 'e26596d1-8c4d-4743-a240-d400e3247a6e' cli.azure.cli.core.sdk.policies: 'x-ms-client-request-id': '1fa8f44e-b992-11ed-b1f2-c8d9d2133ae1' cli.azure.cli.core.sdk.policies: 'Server': 'Kestrel' cli.azure.cli.core.sdk.policies: 'x-ms-correlation-request-id': '35bbfd6c-dcfc-4a2d-ab1f-22282449fac5' cli.azure.cli.core.sdk.policies: 'x-ms-routing-request-id': 'SOUTHEASTASIA:20230303T070804Z:35bbfd6c-dcfc-4a2d-ab1f-22282449fac5' cli.azure.cli.core.sdk.policies: 'X-Content-Type-Options': 'nosniff' cli.azure.cli.core.sdk.policies: 'Date': 'Fri, 03 Mar 2023 07:08:04 GMT' cli.azure.cli.core.sdk.policies: Response content: cli.azure.cli.core.sdk.policies: { "error": { "code": "BadRequest", "message": "Property 'Profile.ExtendedProperties' is read-only and cannot be changed" } } cli.azure.cli.core.util: azure.cli.core.util.handle_exception is called with an exception: cli.azure.cli.core.util: Traceback (most recent call last): File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\knack/cli.py", line 233, in invoke File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/init.py", line 663, in execute File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/init.py", line 726, in _run_jobs_serially File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/init.py", line 697, in _run_job File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/init.py", line 333, in call File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/command_operation.py", line 240, in handler File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/init.py", line 452, in cached_put File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/init.py", line 446, in _put_operation File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/command_modules/resource/custom.py", line 1775, in update_resource File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/command_modules/resource/custom.py", line 1775, in File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/command_modules/resource/custom.py", line 3455, in update File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/core/tracing/decorator.py", line 73, in wrapper_use_tracer File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/mgmt/resource/resources/v2021_04_01/operations/_operations.py", line 9476, in begin_create_or_update_by_id File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/mgmt/resource/resources/v2021_04_01/operations/_operations.py", line 9418, in _create_or_update_by_id_initial azure.core.exceptions.HttpResponseError: (BadRequest) Property 'Profile.ExtendedProperties' is read-only and cannot be changed Code: BadRequest Message: Property 'Profile.ExtendedProperties' is read-only and cannot be changed

cli.azure.cli.core.azclierror: (BadRequest) Property 'Profile.ExtendedProperties' is read-only and cannot be changed Code: BadRequest Message: Property 'Profile.ExtendedProperties' is read-only and cannot be changed az_command_data_logger: (BadRequest) Property 'Profile.ExtendedProperties' is read-only and cannot be changed Code: BadRequest Message: Property 'Profile.ExtendedProperties' is read-only and cannot be changed cli.knack.cli: Event: Cli.PostExecute [<function AzCliLogging.deinit_cmd_metadata_logging at 0x04AAA928>] az_command_data_logger: exit code: 1 cli.main: Command ran in 9.542 seconds (init: 0.987, invoke: 8.555) telemetry.main: Begin splitting cli events and extra events, total events: 1 telemetry.client: Accumulated 0 events. Flush the clients. telemetry.main: Finish splitting cli events and extra events, cli events: 1 telemetry.save: Save telemetry record of length 3347 in cache telemetry.check: Returns Positive. telemetry.main: Begin creating telemetry upload process. telemetry.process: Creating upload process: "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\python.exe C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\Lib\site-packages\azure\cli\telemetry__init__.pyc C:\Users\bzhan.azure" telemetry.process: Return from creating process telemetry.main: Finish creating telemetry upload process.

yonzhan commented 1 year ago

@zhoxing-ms for awareness

ardeshir commented 1 year ago

@zhoxing-ms We're seeing this error now, "Profile.ExtendedProperties' is read-only and cannot be changed" when running our bicep modules to update the FrontDoor:


{
  "code": "DeploymentFailed",
  "message": "At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/arm-deployment-operations for usage details.",
  "details": [
    {
      "code": "BadRequest",
      "message": "Property 'Profile.ExtendedProperties' is read-only and cannot be changed"
    }
  ]
}

This works fine with the following az cli but fails within AzureDevOps tasks, so I'm not sure what needs fixing: 
// Main.bicep 

@description('The name of the Front Door endpoint to create. This must be globally unique.')
param endpointName string = 'shared-cds-frontdoor-premium-sb'

@description('The profileName becomes the Front Door UI name. This must be globally unique.')
param profileName string = 'FrontDoorPremiumNonProd'

@description('The name of the SKU to use when creating the Front Door profile.')
@allowed([
  'Standard_AzureFrontDoor'
  'Premium_AzureFrontDoor'
])
param skuName string = 'Standard_AzureFrontDoor'

resource profile 'Microsoft.Cdn/profiles@2022-11-01-preview' = {
  name: profileName
  location: 'Global'
  sku: {
    name: skuName
  }
  kind: 'frontdoor'
  properties: {
    originResponseTimeoutSeconds: 240
    extendedProperties: {
    }
  }
}

resource endpoint 'Microsoft.Cdn/profiles/afdendpoints@2022-11-01-preview' = {
  parent: profile
  name: endpointName
  location: 'Global'
  properties: {
    enabledState: 'Enabled'
  }
}

param dom array = []
param org array = []
param orgG array = []
param rts array = []

resource customDomains 'Microsoft.Cdn/profiles/customdomains@2022-11-01-preview' = [ for domain in dom: {
  parent: profile
  name: domain.Name // 'cdsapi-cargilldigitalsolutions-com'
  properties: {
    hostName: domain.hostName // 'cdsapi.cargilldigitalsolutions.com'
    tlsSettings: {
      certificateType: 'ManagedCertificate'
      minimumTlsVersion: 'TLS12'
    }
  } 
}]

resource originGroup 'Microsoft.Cdn/profiles/origingroups@2022-11-01-preview' = {
  parent: profile 
  name: orgG[0].Name // 'og-cds-api-service'
      properties: {
          loadBalancingSettings: {
            sampleSize: 4
            successfulSamplesRequired: 3
            additionalLatencyInMilliseconds: 0
          }
          healthProbeSettings: {
            probePath: '/'
            probeRequestType: 'HEAD'
            probeProtocol: 'Http'
            probeIntervalInSeconds: 100
         }
      sessionAffinityState: 'Disabled'
  }
}

resource origins 'Microsoft.Cdn/profiles/origingroups/origins@2022-11-01-preview' =  [ for origin in org : {
  name: origin.Name // 'cds-api-service'
  parent: originGroup
  properties: {
    hostName: origin.HostName // 'cds-api-service.azurewebsites.net'
    httpPort: 80
    httpsPort: 443
    originHostHeader: origin.HostHeader //  'cds-api-service.azurewebsites.net'
    priority: 1
    weight: 1000
    enabledState: 'Enabled'
    enforceCertificateNameCheck: true
  }
}]

resource routesResource 'Microsoft.Cdn/profiles/afdendpoints/routes@2022-11-01-preview' =  {
  name: rts[0].Name
  parent: endpoint 
  properties: {
    cacheConfiguration: {
      compressionSettings: {
        isCompressionEnabled: false
        contentTypesToCompress: []
      }
      queryStringCachingBehavior: 'IgnoreQueryString'
    }
    customDomains: [
      {
        id: customDomains[0].id
      }
    ]
    originGroup: {
       id: originGroup.id
    }
    ruleSets: []
    supportedProtocols: [
      'Http'
      'Https'
    ]
    patternsToMatch: [
      '/*'
    ]
    forwardingProtocol: 'HttpsOnly'
    linkToDefaultDomain: 'Enabled'
    httpsRedirect: 'Enabled'
    enabledState: 'Enabled'
  }

} 

// parameters.json 

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "profileName": {
            "value": "FrontDoorPremiumNonprod"
        },
        "skuName": {
            "value": "Standard_AzureFrontDoor"
        }, 
        "endpointName": {
            "value": "shared-cds-frontdoor-premium-sb"
        },
        "dom" : {
            "value" : [ 
                {
                    "Name" : "cdsapi-cargilldigitalsolutions-com",
                    "hostName" : "cdsapi.cargilldigitalsolutions.com"
                }
            ]
        },
        "org" : {
            "value" : [ 
                {

                    "Name": "cds-api-service",
                    "HostName": "cds-api-service.azurewebsites.net",
                    "HostHeader":  "cds-api-service.azurewebsites.net"
                }
            ]
        }, 
        "orgG" : {
            "value" : [ 
                {
                    "Name" :  "og-cds-api-service"
                }
            ]
        }, 
        "rts": {
            "value" : [
                { 
                    "Name": "r-cds-api-service"
                }
            ]
        }
    }
} ```
yanzhudd commented 1 year ago

Hi @t-bzhan, if a new parameter such as --update-mode be added to indicate whether "PATCH" or "PUT" should be used, more codes need to be changed compared to adding new commands. In order to avoid bug bringing and be more convenient for users to use, we suggest adding a new command az resource patch to support "PATCH" request for updating resource.

Could you please help to check if this solution meets your expectation?

t-bzhan commented 1 year ago

Hi @t-bzhan, if a new parameter such as --update-mode be added to indicate whether "PATCH" or "PUT" should be used, more codes need to be changed compared to adding new commands. In order to avoid bug bringing and be more convenient for users to use, we suggest adding a new command az resource patch to support "PATCH" request for updating resource.

Could you please help to check if this solution meets your expectation?

I think that is great, thanks so much!