diff --git a/sdk/resources/azure-mgmt-resource-policy/CHANGELOG.md b/sdk/resources/azure-mgmt-resource-policy/CHANGELOG.md new file mode 100644 index 000000000000..728d2fbcb3f8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (2026-02-04) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-policy/LICENSE b/sdk/resources/azure-mgmt-resource-policy/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-policy/MANIFEST.in b/sdk/resources/azure-mgmt-resource-policy/MANIFEST.in new file mode 100644 index 000000000000..b0078f5508b5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/MANIFEST.in @@ -0,0 +1,8 @@ +include *.md +include LICENSE +include azure/mgmt/resource/policy/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py +include azure/mgmt/resource/__init__.py diff --git a/sdk/resources/azure-mgmt-resource-policy/README.md b/sdk/resources/azure-mgmt-resource-policy/README.md new file mode 100644 index 000000000000..cf1a9d1392b4 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/README.md @@ -0,0 +1,61 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure Resource Policy Management Client Library. +This package has been tested with Python 3.9+. +For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ + +## Getting started + +### Prerequisites + +- Python 3.9+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) + +### Install the package + +```bash +pip install azure-mgmt-resource-policy +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.resource.policy import PolicyClient +import os + +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = PolicyClient(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` + +## Examples + +Code samples for this package can be found at: +- [Search Resource Policy Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/resources/azure-mgmt-resource-policy/_metadata.json b/sdk/resources/azure-mgmt-resource-policy/_metadata.json new file mode 100644 index 000000000000..a92976f3f261 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/_metadata.json @@ -0,0 +1,11 @@ +{ + "commit": "3805079312b2cd71f794e1a5a9b1e74e72e2986f", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.48.0", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/resources/resource-manager/Microsoft.Authorization/policy/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --tag=package-policy-2023-04 --use=@autorest/python@6.48.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/resources/resource-manager/Microsoft.Authorization/policy/readme.md" +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-policy/apiview-properties.json b/sdk/resources/azure-mgmt-resource-policy/apiview-properties.json new file mode 100644 index 000000000000..517a6d871ee6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/apiview-properties.json @@ -0,0 +1,229 @@ +{ + "CrossLanguagePackageId": null, + "CrossLanguageDefinitionId": { + "azure.mgmt.resource.policy.models.Alias": null, + "azure.mgmt.resource.policy.models.AliasPath": null, + "azure.mgmt.resource.policy.models.AliasPathMetadata": null, + "azure.mgmt.resource.policy.models.AliasPattern": null, + "azure.mgmt.resource.policy.models.DataEffect": null, + "azure.mgmt.resource.policy.models.DataManifestCustomResourceFunctionDefinition": null, + "azure.mgmt.resource.policy.models.DataPolicyManifest": null, + "azure.mgmt.resource.policy.models.DataPolicyManifestListResult": null, + "azure.mgmt.resource.policy.models.ErrorAdditionalInfo": null, + "azure.mgmt.resource.policy.models.ErrorResponse": null, + "azure.mgmt.resource.policy.models.Identity": null, + "azure.mgmt.resource.policy.models.NonComplianceMessage": null, + "azure.mgmt.resource.policy.models.Override": null, + "azure.mgmt.resource.policy.models.ParameterDefinitionsValue": null, + "azure.mgmt.resource.policy.models.ParameterDefinitionsValueMetadata": null, + "azure.mgmt.resource.policy.models.ParameterValuesValue": null, + "azure.mgmt.resource.policy.models.PolicyAssignment": null, + "azure.mgmt.resource.policy.models.PolicyAssignmentListResult": null, + "azure.mgmt.resource.policy.models.PolicyAssignmentUpdate": null, + "azure.mgmt.resource.policy.models.PolicyDefinition": null, + "azure.mgmt.resource.policy.models.PolicyDefinitionGroup": null, + "azure.mgmt.resource.policy.models.PolicyDefinitionListResult": null, + "azure.mgmt.resource.policy.models.PolicyDefinitionReference": null, + "azure.mgmt.resource.policy.models.PolicyDefinitionVersion": null, + "azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult": null, + "azure.mgmt.resource.policy.models.PolicyExemption": null, + "azure.mgmt.resource.policy.models.PolicyExemptionListResult": null, + "azure.mgmt.resource.policy.models.PolicyExemptionUpdate": null, + "azure.mgmt.resource.policy.models.PolicySetDefinition": null, + "azure.mgmt.resource.policy.models.PolicySetDefinitionListResult": null, + "azure.mgmt.resource.policy.models.PolicySetDefinitionVersion": null, + "azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult": null, + "azure.mgmt.resource.policy.models.PolicyVariableColumn": null, + "azure.mgmt.resource.policy.models.PolicyVariableValueColumnValue": null, + "azure.mgmt.resource.policy.models.ResourceSelector": null, + "azure.mgmt.resource.policy.models.ResourceTypeAliases": null, + "azure.mgmt.resource.policy.models.Selector": null, + "azure.mgmt.resource.policy.models.SystemData": null, + "azure.mgmt.resource.policy.models.UserAssignedIdentitiesValue": null, + "azure.mgmt.resource.policy.models.Variable": null, + "azure.mgmt.resource.policy.models.VariableListResult": null, + "azure.mgmt.resource.policy.models.VariableValue": null, + "azure.mgmt.resource.policy.models.VariableValueListResult": null, + "azure.mgmt.resource.policy.models.AliasPatternType": null, + "azure.mgmt.resource.policy.models.AliasPathTokenType": null, + "azure.mgmt.resource.policy.models.AliasPathAttributes": null, + "azure.mgmt.resource.policy.models.AliasType": null, + "azure.mgmt.resource.policy.models.CreatedByType": null, + "azure.mgmt.resource.policy.models.PolicyType": null, + "azure.mgmt.resource.policy.models.ParameterType": null, + "azure.mgmt.resource.policy.models.SelectorKind": null, + "azure.mgmt.resource.policy.models.OverrideKind": null, + "azure.mgmt.resource.policy.models.ResourceIdentityType": null, + "azure.mgmt.resource.policy.models.EnforcementMode": null, + "azure.mgmt.resource.policy.models.ExemptionCategory": null, + "azure.mgmt.resource.policy.models.AssignmentScopeValidation": null, + "azure.mgmt.resource.policy.operations.DataPolicyManifestsOperations.get_by_policy_mode": null, + "azure.mgmt.resource.policy.aio.operations.DataPolicyManifestsOperations.get_by_policy_mode": null, + "azure.mgmt.resource.policy.operations.DataPolicyManifestsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.DataPolicyManifestsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.delete": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.get": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.list_all_builtins": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.list_all_builtins": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.list_all_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.list_all_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.list_all": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.list_all": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.delete": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.get": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.delete": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.get": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.list_all_builtins": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.list_all_builtins": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.list_all_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.list_all_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.list_all": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.list_all": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.delete": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.get": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.get_built_in": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.list_built_in": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations.list_by_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.delete": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.create": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.create": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.get": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.update": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.update": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.list_for_resource_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.list_for_resource_group": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.list_for_resource": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.list_for_resource": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.delete_by_id": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.delete_by_id": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.create_by_id": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.create_by_id": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.get_by_id": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.get_by_id": null, + "azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations.update_by_id": null, + "azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations.update_by_id": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.delete": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.get": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.update": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.update": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.list": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.list_for_resource_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.list_for_resource_group": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.list_for_resource": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.list_for_resource": null, + "azure.mgmt.resource.policy.operations.PolicyExemptionsOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.delete": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.get": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.list": null, + "azure.mgmt.resource.policy.operations.VariablesOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariablesOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.delete": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.delete": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.create_or_update": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.create_or_update": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.get": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.get": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.list": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.list": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.list_for_management_group": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.delete_at_management_group": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.create_or_update_at_management_group": null, + "azure.mgmt.resource.policy.operations.VariableValuesOperations.get_at_management_group": null, + "azure.mgmt.resource.policy.aio.operations.VariableValuesOperations.get_at_management_group": null + } +} \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/__init__.py new file mode 100644 index 000000000000..02f33f3e073a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/__init__.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._policy_client import PolicyClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_configuration.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_configuration.py new file mode 100644 index 000000000000..adb4296d0647 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_configuration.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class PolicyClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for PolicyClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-policy/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_patch.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_policy_client.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_policy_client.py new file mode 100644 index 000000000000..6d154e35759f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_policy_client.py @@ -0,0 +1,176 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from . import models as _models +from ._configuration import PolicyClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import ( + DataPolicyManifestsOperations, + PolicyAssignmentsOperations, + PolicyDefinitionVersionsOperations, + PolicyDefinitionsOperations, + PolicyExemptionsOperations, + PolicySetDefinitionVersionsOperations, + PolicySetDefinitionsOperations, + VariableValuesOperations, + VariablesOperations, +) + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials import TokenCredential + + +class PolicyClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Policy Client. + + :ivar data_policy_manifests: DataPolicyManifestsOperations operations + :vartype data_policy_manifests: + azure.mgmt.resource.policy.operations.DataPolicyManifestsOperations + :ivar policy_definitions: PolicyDefinitionsOperations operations + :vartype policy_definitions: azure.mgmt.resource.policy.operations.PolicyDefinitionsOperations + :ivar policy_definition_versions: PolicyDefinitionVersionsOperations operations + :vartype policy_definition_versions: + azure.mgmt.resource.policy.operations.PolicyDefinitionVersionsOperations + :ivar policy_set_definitions: PolicySetDefinitionsOperations operations + :vartype policy_set_definitions: + azure.mgmt.resource.policy.operations.PolicySetDefinitionsOperations + :ivar policy_set_definition_versions: PolicySetDefinitionVersionsOperations operations + :vartype policy_set_definition_versions: + azure.mgmt.resource.policy.operations.PolicySetDefinitionVersionsOperations + :ivar policy_assignments: PolicyAssignmentsOperations operations + :vartype policy_assignments: azure.mgmt.resource.policy.operations.PolicyAssignmentsOperations + :ivar policy_exemptions: PolicyExemptionsOperations operations + :vartype policy_exemptions: azure.mgmt.resource.policy.operations.PolicyExemptionsOperations + :ivar variables: VariablesOperations operations + :vartype variables: azure.mgmt.resource.policy.operations.VariablesOperations + :ivar variable_values: VariableValuesOperations operations + :vartype variable_values: azure.mgmt.resource.policy.operations.VariableValuesOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = PolicyClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.data_policy_manifests = DataPolicyManifestsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_definitions = PolicyDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_definition_versions = PolicyDefinitionVersionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_set_definitions = PolicySetDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_set_definition_versions = PolicySetDefinitionVersionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_assignments = PolicyAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_exemptions = PolicyExemptionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.variables = VariablesOperations(self._client, self._config, self._serialize, self._deserialize) + self.variable_values = VariableValuesOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/serialization.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/serialization.py new file mode 100644 index 000000000000..6da830e0cf4a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_utils/serialization.py @@ -0,0 +1,2041 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore +from typing_extensions import Self + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_version.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/__init__.py new file mode 100644 index 000000000000..18537e83bff7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._policy_client import PolicyClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PolicyClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_configuration.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_configuration.py new file mode 100644 index 000000000000..1395d715583c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_configuration.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class PolicyClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for PolicyClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.cloud_setting = cloud_setting + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-resource-policy/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_patch.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_policy_client.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_policy_client.py new file mode 100644 index 000000000000..7918f89e1426 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/_policy_client.py @@ -0,0 +1,183 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints + +from .. import models as _models +from .._utils.serialization import Deserializer, Serializer +from ._configuration import PolicyClientConfiguration +from .operations import ( + DataPolicyManifestsOperations, + PolicyAssignmentsOperations, + PolicyDefinitionVersionsOperations, + PolicyDefinitionsOperations, + PolicyExemptionsOperations, + PolicySetDefinitionVersionsOperations, + PolicySetDefinitionsOperations, + VariableValuesOperations, + VariablesOperations, +) + +if TYPE_CHECKING: + from azure.core import AzureClouds + from azure.core.credentials_async import AsyncTokenCredential + + +class PolicyClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """Policy Client. + + :ivar data_policy_manifests: DataPolicyManifestsOperations operations + :vartype data_policy_manifests: + azure.mgmt.resource.policy.aio.operations.DataPolicyManifestsOperations + :ivar policy_definitions: PolicyDefinitionsOperations operations + :vartype policy_definitions: + azure.mgmt.resource.policy.aio.operations.PolicyDefinitionsOperations + :ivar policy_definition_versions: PolicyDefinitionVersionsOperations operations + :vartype policy_definition_versions: + azure.mgmt.resource.policy.aio.operations.PolicyDefinitionVersionsOperations + :ivar policy_set_definitions: PolicySetDefinitionsOperations operations + :vartype policy_set_definitions: + azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionsOperations + :ivar policy_set_definition_versions: PolicySetDefinitionVersionsOperations operations + :vartype policy_set_definition_versions: + azure.mgmt.resource.policy.aio.operations.PolicySetDefinitionVersionsOperations + :ivar policy_assignments: PolicyAssignmentsOperations operations + :vartype policy_assignments: + azure.mgmt.resource.policy.aio.operations.PolicyAssignmentsOperations + :ivar policy_exemptions: PolicyExemptionsOperations operations + :vartype policy_exemptions: + azure.mgmt.resource.policy.aio.operations.PolicyExemptionsOperations + :ivar variables: VariablesOperations operations + :vartype variables: azure.mgmt.resource.policy.aio.operations.VariablesOperations + :ivar variable_values: VariableValuesOperations operations + :vartype variable_values: azure.mgmt.resource.policy.aio.operations.VariableValuesOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is None. + :type base_url: str + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = PolicyClientConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs + ) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.data_policy_manifests = DataPolicyManifestsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_definitions = PolicyDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_definition_versions = PolicyDefinitionVersionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_set_definitions = PolicySetDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_set_definition_versions = PolicySetDefinitionVersionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_assignments = PolicyAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.policy_exemptions = PolicyExemptionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.variables = VariablesOperations(self._client, self._config, self._serialize, self._deserialize) + self.variable_values = VariableValuesOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/__init__.py new file mode 100644 index 000000000000..f302859689f6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/__init__.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import DataPolicyManifestsOperations # type: ignore +from ._operations import PolicyDefinitionsOperations # type: ignore +from ._operations import PolicyDefinitionVersionsOperations # type: ignore +from ._operations import PolicySetDefinitionsOperations # type: ignore +from ._operations import PolicySetDefinitionVersionsOperations # type: ignore +from ._operations import PolicyAssignmentsOperations # type: ignore +from ._operations import PolicyExemptionsOperations # type: ignore +from ._operations import VariablesOperations # type: ignore +from ._operations import VariableValuesOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DataPolicyManifestsOperations", + "PolicyDefinitionsOperations", + "PolicyDefinitionVersionsOperations", + "PolicySetDefinitionsOperations", + "PolicySetDefinitionVersionsOperations", + "PolicyAssignmentsOperations", + "PolicyExemptionsOperations", + "VariablesOperations", + "VariableValuesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_operations.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_operations.py new file mode 100644 index 000000000000..b166b31b9016 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_operations.py @@ -0,0 +1,7433 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import ( + build_data_policy_manifests_get_by_policy_mode_request, + build_data_policy_manifests_list_request, + build_policy_assignments_create_by_id_request, + build_policy_assignments_create_request, + build_policy_assignments_delete_by_id_request, + build_policy_assignments_delete_request, + build_policy_assignments_get_by_id_request, + build_policy_assignments_get_request, + build_policy_assignments_list_for_management_group_request, + build_policy_assignments_list_for_resource_group_request, + build_policy_assignments_list_for_resource_request, + build_policy_assignments_list_request, + build_policy_assignments_update_by_id_request, + build_policy_assignments_update_request, + build_policy_definition_versions_create_or_update_at_management_group_request, + build_policy_definition_versions_create_or_update_request, + build_policy_definition_versions_delete_at_management_group_request, + build_policy_definition_versions_delete_request, + build_policy_definition_versions_get_at_management_group_request, + build_policy_definition_versions_get_built_in_request, + build_policy_definition_versions_get_request, + build_policy_definition_versions_list_all_at_management_group_request, + build_policy_definition_versions_list_all_builtins_request, + build_policy_definition_versions_list_all_request, + build_policy_definition_versions_list_built_in_request, + build_policy_definition_versions_list_by_management_group_request, + build_policy_definition_versions_list_request, + build_policy_definitions_create_or_update_at_management_group_request, + build_policy_definitions_create_or_update_request, + build_policy_definitions_delete_at_management_group_request, + build_policy_definitions_delete_request, + build_policy_definitions_get_at_management_group_request, + build_policy_definitions_get_built_in_request, + build_policy_definitions_get_request, + build_policy_definitions_list_built_in_request, + build_policy_definitions_list_by_management_group_request, + build_policy_definitions_list_request, + build_policy_exemptions_create_or_update_request, + build_policy_exemptions_delete_request, + build_policy_exemptions_get_request, + build_policy_exemptions_list_for_management_group_request, + build_policy_exemptions_list_for_resource_group_request, + build_policy_exemptions_list_for_resource_request, + build_policy_exemptions_list_request, + build_policy_exemptions_update_request, + build_policy_set_definition_versions_create_or_update_at_management_group_request, + build_policy_set_definition_versions_create_or_update_request, + build_policy_set_definition_versions_delete_at_management_group_request, + build_policy_set_definition_versions_delete_request, + build_policy_set_definition_versions_get_at_management_group_request, + build_policy_set_definition_versions_get_built_in_request, + build_policy_set_definition_versions_get_request, + build_policy_set_definition_versions_list_all_at_management_group_request, + build_policy_set_definition_versions_list_all_builtins_request, + build_policy_set_definition_versions_list_all_request, + build_policy_set_definition_versions_list_built_in_request, + build_policy_set_definition_versions_list_by_management_group_request, + build_policy_set_definition_versions_list_request, + build_policy_set_definitions_create_or_update_at_management_group_request, + build_policy_set_definitions_create_or_update_request, + build_policy_set_definitions_delete_at_management_group_request, + build_policy_set_definitions_delete_request, + build_policy_set_definitions_get_at_management_group_request, + build_policy_set_definitions_get_built_in_request, + build_policy_set_definitions_get_request, + build_policy_set_definitions_list_built_in_request, + build_policy_set_definitions_list_by_management_group_request, + build_policy_set_definitions_list_request, + build_variable_values_create_or_update_at_management_group_request, + build_variable_values_create_or_update_request, + build_variable_values_delete_at_management_group_request, + build_variable_values_delete_request, + build_variable_values_get_at_management_group_request, + build_variable_values_get_request, + build_variable_values_list_for_management_group_request, + build_variable_values_list_request, + build_variables_create_or_update_at_management_group_request, + build_variables_create_or_update_request, + build_variables_delete_at_management_group_request, + build_variables_delete_request, + build_variables_get_at_management_group_request, + build_variables_get_request, + build_variables_list_for_management_group_request, + build_variables_list_request, +) +from .._configuration import PolicyClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list + + +class DataPolicyManifestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`data_policy_manifests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get_by_policy_mode(self, policy_mode: str, **kwargs: Any) -> _models.DataPolicyManifest: + """Retrieves a data policy manifest. + + This operation retrieves the data policy manifest with the given policy mode. + + :param policy_mode: The policy mode of the data policy manifest to get. Required. + :type policy_mode: str + :return: DataPolicyManifest or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.DataPolicyManifest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) + cls: ClsType[_models.DataPolicyManifest] = kwargs.pop("cls", None) + + _request = build_data_policy_manifests_get_by_policy_mode_request( + policy_mode=policy_mode, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataPolicyManifest", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models.DataPolicyManifest"]: + """Retrieves data policy manifests. + + This operation retrieves a list of all the data policy manifests that match the optional given + $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not + provided, the unfiltered list includes all data policy manifests for data resource types. If + $filter=namespace is provided, the returned list only includes all data policy manifests that + have a namespace matching the provided value. + + :param filter: The filter to apply on the operation. Valid values for $filter are: "namespace + eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq + '{value}' is provided, the returned list only includes all data policy manifests that have a + namespace matching the provided value. Default value is None. + :type filter: str + :return: An iterator like instance of either DataPolicyManifest or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.DataPolicyManifest] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) + cls: ClsType[_models.DataPolicyManifestListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_data_policy_manifests_list_request( + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DataPolicyManifestListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class PolicyDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`policy_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + policy_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, policy_definition_name: str, parameters: Union[_models.PolicyDefinition, IO[bytes]], **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition or IO[bytes] + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + _request = build_policy_definitions_create_or_update_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, policy_definition_name: str, **kwargs: Any) -> None: + """Deletes a policy definition in a subscription. + + This operation deletes the policy definition in the given subscription with the given name. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definitions_delete_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Retrieves a policy definition in a subscription. + + This operation retrieves the policy definition in the given subscription with the given name. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + _request = build_policy_definitions_get_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_built_in(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Retrieves a built-in policy definition. + + This operation retrieves the built-in policy definition with the given name. + + :param policy_definition_name: The name of the built-in policy definition to get. Required. + :type policy_definition_name: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + _request = build_policy_definitions_get_built_in_request( + policy_definition_name=policy_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a management group. + + This operation creates or updates a policy definition in the given management group with the + given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + policy_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a management group. + + This operation creates or updates a policy definition in the given management group with the + given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + management_group_id: str, + policy_definition_name: str, + parameters: Union[_models.PolicyDefinition, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a management group. + + This operation creates or updates a policy definition in the given management group with the + given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition or IO[bytes] + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + _request = build_policy_definitions_create_or_update_at_management_group_request( + management_group_id=management_group_id, + policy_definition_name=policy_definition_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_at_management_group( + self, management_group_id: str, policy_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy definition in a management group. + + This operation deletes the policy definition in the given management group with the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definitions_delete_at_management_group_request( + management_group_id=management_group_id, + policy_definition_name=policy_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_at_management_group( + self, management_group_id: str, policy_definition_name: str, **kwargs: Any + ) -> _models.PolicyDefinition: + """Retrieve a policy definition in a management group. + + This operation retrieves the policy definition in the given management group with the given + name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + _request = build_policy_definitions_get_at_management_group_request( + management_group_id=management_group_id, + policy_definition_name=policy_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyDefinition"]: + """Retrieves policy definitions in a subscription. + + This operation retrieves a list of all the policy definitions in a given subscription that + match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType + -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list + includes all policy definitions associated with the subscription, including those that apply + directly or from management groups that contain the given subscription. If + $filter=atExactScope() is provided, the returned list only includes all policy definitions that + at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list + only includes all policy definitions whose type match the {value}. Possible policyType values + are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, + the returned list only includes all policy definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy definitions whose type match + the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy + definitions whose category match the {value}. Default value is None. + :type filter: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definitions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyDefinition"]: + """Retrieve built-in policy definitions. + + This operation retrieves a list of all the built-in policy definitions that match the optional + given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes + all built-in policy definitions whose type match the {value}. Possible policyType values are + NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the + returned list only includes all built-in policy definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy definitions whose type match + the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy + definitions whose category match the {value}. Default value is None. + :type filter: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definitions_list_built_in_request( + filter=filter, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_management_group( + self, management_group_id: str, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyDefinition"]: + """Retrieve policy definitions in a management group. + + This operation retrieves a list of all the policy definitions in a given management group that + match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType + -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list + includes all policy definitions associated with the management group, including those that + apply directly or from management groups that contain the given management group. If + $filter=atExactScope() is provided, the returned list only includes all policy definitions that + at the given management group. If $filter='policyType -eq {value}' is provided, the returned + list only includes all policy definitions whose type match the {value}. Possible policyType + values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is + provided, the returned list only includes all policy definitions whose category match the + {value}. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy definitions whose type match + the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy + definitions whose category match the {value}. Default value is None. + :type filter: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definitions_list_by_management_group_request( + management_group_id=management_group_id, + filter=filter, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class PolicyDefinitionVersionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`policy_definition_versions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def list_all_builtins(self, **kwargs: Any) -> _models.PolicyDefinitionVersionListResult: + """Lists all built-in policy definition versions. + + This operation lists all the built-in policy definition versions for all built-in policy + definitions. + + :return: PolicyDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_list_all_builtins_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_all_at_management_group( + self, management_group_name: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersionListResult: + """Lists all policy definition versions at management group scope. + + This operation lists all the policy definition versions for all policy definitions at the + management group scope. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :return: PolicyDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_list_all_at_management_group_request( + management_group_name=management_group_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_all(self, **kwargs: Any) -> _models.PolicyDefinitionVersionListResult: + """Lists all policy definition versions within a subscription. + + This operation lists all the policy definition versions for all policy definitions within a + subscription. + + :return: PolicyDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + policy_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicyDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + policy_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + policy_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicyDefinitionVersion, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Is either a PolicyDefinitionVersion type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion or IO[bytes] + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinitionVersion") + + _request = build_policy_definition_versions_create_or_update_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any) -> None: + """Deletes a policy definition version in a subscription. + + This operation deletes the policy definition version in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_delete_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get( + self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Retrieves a policy definition version in a subscription. + + This operation retrieves the policy definition version in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_get_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_built_in( + self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Retrieves a built-in policy definition version. + + This operation retrieves the built-in policy definition version with the given name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_get_built_in_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update_at_management_group( + self, + management_group_name: str, + policy_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicyDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition version in a management group. + + This operation creates or updates a policy definition version in the given management group + with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + management_group_name: str, + policy_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition version in a management group. + + This operation creates or updates a policy definition version in the given management group + with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + management_group_name: str, + policy_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicyDefinitionVersion, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition version in a management group. + + This operation creates or updates a policy definition version in the given management group + with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Is either a PolicyDefinitionVersion type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion or IO[bytes] + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinitionVersion") + + _request = build_policy_definition_versions_create_or_update_at_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_at_management_group( + self, management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> None: + """Deletes a policy definition in a management group. + + This operation deletes the policy definition in the given management group with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_delete_at_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_at_management_group( + self, management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Retrieve a policy definition version in a management group. + + This operation retrieves the policy definition version in the given management group with the + given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_get_at_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyDefinitionVersion"]: + """Retrieves policy definition versions for a given policy definition in a subscription. + + This operation retrieves a list of all the policy definition versions for the given policy + definition. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definition_versions_list_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyDefinitionVersion"]: + """Retrieve built-in policy definition versions. + + This operation retrieves a list of all the built-in policy definition versions for the given + policy definition. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definition_versions_list_built_in_request( + policy_definition_name=policy_definition_name, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_management_group( + self, management_group_name: str, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyDefinitionVersion"]: + """Retrieve policy definition versions in a management group policy definition. + + This operation retrieves a list of all the policy definition versions for the given policy + definition in the given management group. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definition_versions_list_by_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class PolicySetDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`policy_set_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create_or_update( + self, + policy_set_definition_name: str, + parameters: _models.PolicySetDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given subscription with the + given name. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + policy_set_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given subscription with the + given name. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, policy_set_definition_name: str, parameters: Union[_models.PolicySetDefinition, IO[bytes]], **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given subscription with the + given name. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinition type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition or IO[bytes] + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinition") + + _request = build_policy_set_definitions_create_or_update_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, policy_set_definition_name: str, **kwargs: Any) -> None: + """Deletes a policy set definition. + + This operation deletes the policy set definition in the given subscription with the given name. + + :param policy_set_definition_name: The name of the policy set definition to delete. Required. + :type policy_set_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_delete_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get( + self, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicySetDefinition: + """Retrieves a policy set definition. + + This operation retrieves the policy set definition in the given subscription with the given + name. + + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_get_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_built_in( + self, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicySetDefinition: + """Retrieves a built in policy set definition. + + This operation retrieves the built-in policy set definition with the given name. + + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_get_built_in_request( + policy_set_definition_name=policy_set_definition_name, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicySetDefinition"]: + """Retrieves the policy set definitions for a subscription. + + This operation retrieves a list of all the policy set definitions in a given subscription that + match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType + -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list + includes all policy set definitions associated with the subscription, including those that + apply directly or from management groups that contain the given subscription. If + $filter=atExactScope() is provided, the returned list only includes all policy set definitions + that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned + list only includes all policy set definitions whose type match the {value}. Possible policyType + values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the + returned list only includes all policy set definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy set definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy set definitions whose type + match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy set + definitions whose category match the {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definitions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicySetDefinition"]: + """Retrieves built-in policy set definitions. + + This operation retrieves a list of all the built-in policy set definitions that match the + optional given $filter. If $filter='category -eq {value}' is provided, the returned list only + includes all built-in policy set definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy set definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy set definitions whose type + match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy set + definitions whose category match the {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definitions_list_built_in_request( + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + policy_set_definition_name: str, + parameters: _models.PolicySetDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given management group with + the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + policy_set_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given management group with + the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + management_group_id: str, + policy_set_definition_name: str, + parameters: Union[_models.PolicySetDefinition, IO[bytes]], + **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given management group with + the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinition type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition or IO[bytes] + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinition") + + _request = build_policy_set_definitions_create_or_update_at_management_group_request( + management_group_id=management_group_id, + policy_set_definition_name=policy_set_definition_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_at_management_group( + self, management_group_id: str, policy_set_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition. + + This operation deletes the policy set definition in the given management group with the given + name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to delete. Required. + :type policy_set_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_delete_at_management_group_request( + management_group_id=management_group_id, + policy_set_definition_name=policy_set_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_at_management_group( + self, management_group_id: str, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicySetDefinition: + """Retrieves a policy set definition. + + This operation retrieves the policy set definition in the given management group with the given + name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_get_at_management_group_request( + management_group_id=management_group_id, + policy_set_definition_name=policy_set_definition_name, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_management_group( + self, + management_group_id: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.PolicySetDefinition"]: + """Retrieves all policy set definitions in management group. + + This operation retrieves a list of all the policy set definitions in a given management group + that match the optional given $filter. Valid values for $filter are: 'atExactScope()', + 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered + list includes all policy set definitions associated with the management group, including those + that apply directly or from management groups that contain the given management group. If + $filter=atExactScope() is provided, the returned list only includes all policy set definitions + that at the given management group. If $filter='policyType -eq {value}' is provided, the + returned list only includes all policy set definitions whose type match the {value}. Possible + policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is + provided, the returned list only includes all policy set definitions whose category match the + {value}. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy set definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy set definitions whose type + match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy set + definitions whose category match the {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definitions_list_by_management_group_request( + management_group_id=management_group_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class PolicySetDefinitionVersionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`policy_set_definition_versions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def list_all_builtins(self, **kwargs: Any) -> _models.PolicySetDefinitionVersionListResult: + """Lists all built-in policy set definition versions. + + This operation lists all the built-in policy set definition versions for all built-in policy + set definitions. + + :return: PolicySetDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_list_all_builtins_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_all_at_management_group( + self, management_group_name: str, **kwargs: Any + ) -> _models.PolicySetDefinitionVersionListResult: + """Lists all policy set definition versions at management group scope. + + This operation lists all the policy set definition versions for all policy set definitions at + the management group scope. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :return: PolicySetDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_list_all_at_management_group_request( + management_group_name=management_group_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_all(self, **kwargs: Any) -> _models.PolicySetDefinitionVersionListResult: + """Lists all policy set definition versions within a subscription. + + This operation lists all the policy set definition versions for all policy set definitions + within a subscription. + + :return: PolicySetDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicySetDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given subscription + with the given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given subscription + with the given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicySetDefinitionVersion, IO[bytes]], + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given subscription + with the given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinitionVersion + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion or IO[bytes] + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinitionVersion") + + _request = build_policy_set_definition_versions_create_or_update_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any) -> None: + """Deletes a policy set definition version. + + This operation deletes the policy set definition version in the given subscription with the + given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_delete_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get( + self, + policy_set_definition_name: str, + policy_definition_version: str, + expand: Optional[str] = None, + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Retrieves a policy set definition version. + + This operation retrieves the policy set definition version in the given subscription with the + given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_get_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_built_in( + self, + policy_set_definition_name: str, + policy_definition_version: str, + expand: Optional[str] = None, + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Retrieves a built in policy set definition version. + + This operation retrieves the built-in policy set definition version with the given name and + version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_get_built_in_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, policy_set_definition_name: str, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicySetDefinitionVersion"]: + """Retrieves the policy set definition versions for a given policy set definition in a + subscription. + + This operation retrieves a list of all the policy set definition versions for the given policy + set definition. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definition_versions_list_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, policy_set_definition_name: str, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicySetDefinitionVersion"]: + """Retrieves built-in policy set definition versions. + + This operation retrieves a list of all the built-in policy set definition versions for the + given built-in policy set definition. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definition_versions_list_built_in_request( + policy_set_definition_name=policy_set_definition_name, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def create_or_update_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicySetDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given management group + with the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition version properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given management group + with the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition version properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicySetDefinitionVersion, IO[bytes]], + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given management group + with the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition version properties. Is either a + PolicySetDefinitionVersion type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion or IO[bytes] + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinitionVersion") + + _request = build_policy_set_definition_versions_create_or_update_at_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_at_management_group( + self, management_group_name: str, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition version. + + This operation deletes the policy set definition version in the given management group with the + given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_delete_at_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def get_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + expand: Optional[str] = None, + **kwargs: Any + ) -> _models.PolicySetDefinitionVersion: + """Retrieves a policy set definition version. + + This operation retrieves the policy set definition version in the given management group with + the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_get_at_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.PolicySetDefinitionVersion"]: + """Retrieves all policy set definition versions for a given policy set definition in a management + group. + + This operation retrieves a list of all the policy set definition versions for the given policy + set definition in a given management group. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definition_versions_list_by_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class PolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`policy_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete( + self, scope: str, policy_assignment_name: str, **kwargs: Any + ) -> Optional[_models.PolicyAssignment]: + """Deletes a policy assignment. + + This operation deletes a policy assignment, given its name and the scope it was created in. The + scope of a policy assignment is the part of its ID preceding + '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to delete. Required. + :type policy_assignment_name: str + :return: PolicyAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) + + _request = build_policy_assignments_delete_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates a policy assignment with the given scope and name. Policy + assignments apply to all resources contained within their scope. For example, when you assign a + policy at resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates a policy assignment with the given scope and name. Policy + assignments apply to all resources contained within their scope. For example, when you assign a + policy at resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, + scope: str, + policy_assignment_name: str, + parameters: Union[_models.PolicyAssignment, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates a policy assignment with the given scope and name. Policy + assignments apply to all resources contained within their scope. For example, when you assign a + policy at resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Is either a PolicyAssignment type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + _request = build_policy_assignments_create_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get( + self, scope: str, policy_assignment_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicyAssignment: + """Retrieves a policy assignment. + + This operation retrieves a single policy assignment, given its name and the scope it was + created at. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to get. Required. + :type policy_assignment_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + _request = build_policy_assignments_get_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignmentUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates a policy assignment with the given scope and name. Policy assignments + apply to all resources contained within their scope. For example, when you assign a policy at + resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + scope: str, + policy_assignment_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates a policy assignment with the given scope and name. Policy assignments + apply to all resources contained within their scope. For example, when you assign a policy at + resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + scope: str, + policy_assignment_name: str, + parameters: Union[_models.PolicyAssignmentUpdate, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates a policy assignment with the given scope and name. Policy assignments + apply to all resources contained within their scope. For example, when you assign a policy at + resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for policy assignment patch request. Is either a + PolicyAssignmentUpdate type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignmentUpdate") + + _request = build_policy_assignments_update_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_for_resource_group( + self, + resource_group_name: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a resource group. + + This operation retrieves the list of all policy assignments associated with the given resource + group in the given subscription that match the optional given $filter. Valid values for $filter + are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not + provided, the unfiltered list includes all policy assignments associated with the resource + group, including those that apply directly or apply from containing scopes, as well as any + applied to resources contained within the resource group. If $filter=atScope() is provided, the + returned list includes all policy assignments that apply to the resource group, which is + everything in the unfiltered list except those applied to resources contained within the + resource group. If $filter=atExactScope() is provided, the returned list only includes all + policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is + provided, the returned list includes all policy assignments of the policy definition whose id + is {value} that apply to the resource group. + + :param resource_group_name: The name of the resource group that contains policy assignments. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a resource. + + This operation retrieves the list of all policy assignments associated with the specified + resource in the given resource group and subscription that match the optional given $filter. + Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq + '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments + associated with the resource, including those that apply directly or from all containing + scopes, as well as any applied to resources contained within the resource. If $filter=atScope() + is provided, the returned list includes all policy assignments that apply to the resource, + which is everything in the unfiltered list except those applied to resources contained within + the resource. If $filter=atExactScope() is provided, the returned list only includes all policy + assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, + the returned list includes all policy assignments of the policy definition whose id is {value} + that apply to the resource. Three parameters plus the resource name are used to identify a + specific resource. If the resource is not part of a parent resource (the more common case), the + parent resource path should not be provided (or provided as ''). For example a web app could be + specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', + {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent + resource, then all parameters should be provided. For example a virtual machine DNS name could + be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == + 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == + 'MyComputerName'). A convenient alternative to providing the namespace and type name separately + is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', + {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == + 'MyWebApp'). + + :param resource_group_name: The name of the resource group containing the resource. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. For example, the + namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Use empty string if there is none. + Required. + :type parent_resource_path: str + :param resource_type: The resource type name. For example the type name of a web app is 'sites' + (from Microsoft.Web/sites). Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group( + self, + management_group_id: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a management group. + + This operation retrieves the list of all policy assignments applicable to the management group + that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or + 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes + all policy assignments that are assigned to the management group or the management group's + ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy + assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is + provided, the returned list includes all policy assignments of the policy definition whose id + is {value} that apply to the management group. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_for_management_group_request( + management_group_id=management_group_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list( + self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a subscription. + + This operation retrieves the list of all policy assignments associated with the given + subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the + unfiltered list includes all policy assignments associated with the subscription, including + those that apply directly or from management groups that contain the given subscription, as + well as any applied to objects contained within the subscription. If $filter=atScope() is + provided, the returned list includes all policy assignments that apply to the subscription, + which is everything in the unfiltered list except those applied to objects contained within the + subscription. If $filter=atExactScope() is provided, the returned list only includes all policy + assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, + the returned list includes all policy assignments of the policy definition whose id is {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def delete_by_id(self, policy_assignment_id: str, **kwargs: Any) -> Optional[_models.PolicyAssignment]: + """Deletes a policy assignment. + + This operation deletes the policy with the given ID. Policy assignment IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + formats for {scope} are: '/providers/Microsoft.Management/managementGroups/{managementGroup}' + (management group), '/subscriptions/{subscriptionId}' (subscription), + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' (resource group), or + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}' + (resource). + + :param policy_assignment_id: The ID of the policy assignment to delete. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :return: PolicyAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) + + _request = build_policy_assignments_delete_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates the policy assignment with the given ID. Policy assignments + made on a scope apply to all resources contained in that scope. For example, when you assign a + policy to a resource group that policy applies to all resources in the group. Policy assignment + IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_by_id( + self, policy_assignment_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates the policy assignment with the given ID. Policy assignments + made on a scope apply to all resources contained in that scope. For example, when you assign a + policy to a resource group that policy applies to all resources in the group. Policy assignment + IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignment, IO[bytes]], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates the policy assignment with the given ID. Policy assignments + made on a scope apply to all resources contained in that scope. For example, when you assign a + policy to a resource group that policy applies to all resources in the group. Policy assignment + IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Is either a PolicyAssignment type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + _request = build_policy_assignments_create_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_by_id( + self, policy_assignment_id: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicyAssignment: + """Retrieves the policy assignment with the given ID. + + The operation retrieves the policy assignment with the given ID. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to get. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + _request = build_policy_assignments_get_by_id_request( + policy_assignment_id=policy_assignment_id, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignmentUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates the policy assignment with the given ID. Policy assignments made on a + scope apply to all resources contained in that scope. For example, when you assign a policy to + a resource group that policy applies to all resources in the group. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to update. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_by_id( + self, policy_assignment_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates the policy assignment with the given ID. Policy assignments made on a + scope apply to all resources contained in that scope. For example, when you assign a policy to + a resource group that policy applies to all resources in the group. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to update. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignmentUpdate, IO[bytes]], **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates the policy assignment with the given ID. Policy assignments made on a + scope apply to all resources contained in that scope. For example, when you assign a policy to + a resource group that policy applies to all resources in the group. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to update. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment patch request. Is either a + PolicyAssignmentUpdate type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignmentUpdate") + + _request = build_policy_assignments_update_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class PolicyExemptionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`policy_exemptions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete(self, scope: str, policy_exemption_name: str, **kwargs: Any) -> None: + """Deletes a policy exemption. + + This operation deletes a policy exemption, given its name and the scope it was created in. The + scope of a policy exemption is the part of its ID preceding + '/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}'. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_exemptions_delete_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def create_or_update( + self, + scope: str, + policy_exemption_name: str, + parameters: _models.PolicyExemption, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyExemption: + """Creates or updates a policy exemption. + + This operation creates or updates a policy exemption with the given scope and name. Policy + exemptions apply to all resources contained within their scope. For example, when you create a + policy exemption at resource group scope for a policy assignment at the same or above level, + the exemption exempts to all applicable resources in the resource group. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for the policy exemption. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemption + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + scope: str, + policy_exemption_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyExemption: + """Creates or updates a policy exemption. + + This operation creates or updates a policy exemption with the given scope and name. Policy + exemptions apply to all resources contained within their scope. For example, when you create a + policy exemption at resource group scope for a policy assignment at the same or above level, + the exemption exempts to all applicable resources in the resource group. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for the policy exemption. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + scope: str, + policy_exemption_name: str, + parameters: Union[_models.PolicyExemption, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyExemption: + """Creates or updates a policy exemption. + + This operation creates or updates a policy exemption with the given scope and name. Policy + exemptions apply to all resources contained within their scope. For example, when you create a + policy exemption at resource group scope for a policy assignment at the same or above level, + the exemption exempts to all applicable resources in the resource group. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for the policy exemption. Is either a PolicyExemption type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemption or IO[bytes] + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyExemption") + + _request = build_policy_exemptions_create_or_update_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get(self, scope: str, policy_exemption_name: str, **kwargs: Any) -> _models.PolicyExemption: + """Retrieves a policy exemption. + + This operation retrieves a single policy exemption, given its name and the scope it was created + at. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) + + _request = build_policy_exemptions_get_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + scope: str, + policy_exemption_name: str, + parameters: _models.PolicyExemptionUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyExemption: + """Updates a policy exemption. + + This operation updates a policy exemption with the given scope and name. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for policy exemption patch request. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemptionUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + scope: str, + policy_exemption_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PolicyExemption: + """Updates a policy exemption. + + This operation updates a policy exemption with the given scope and name. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for policy exemption patch request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + scope: str, + policy_exemption_name: str, + parameters: Union[_models.PolicyExemptionUpdate, IO[bytes]], + **kwargs: Any + ) -> _models.PolicyExemption: + """Updates a policy exemption. + + This operation updates a policy exemption with the given scope and name. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for policy exemption patch request. Is either a + PolicyExemptionUpdate type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemptionUpdate or IO[bytes] + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyExemptionUpdate") + + _request = build_policy_exemptions_update_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a subscription. + + This operation retrieves the list of all policy exemptions associated with the given + subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, the unfiltered list includes all policy exemptions associated with the subscription, + including those that apply directly or from management groups that contain the given + subscription, as well as any applied to objects contained within the subscription. + + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a resource group. + + This operation retrieves the list of all policy exemptions associated with the given resource + group in the given subscription that match the optional given $filter. Valid values for $filter + are: 'atScope()', 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If + $filter is not provided, the unfiltered list includes all policy exemptions associated with the + resource group, including those that apply directly or apply from containing scopes, as well as + any applied to resources contained within the resource group. + + :param resource_group_name: The name of the resource group containing the resource. Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a resource. + + This operation retrieves the list of all policy exemptions associated with the specified + resource in the given resource group and subscription that match the optional given $filter. + Valid values for $filter are: 'atScope()', 'atExactScope()', 'excludeExpired()' or + 'policyAssignmentId eq '{value}''. If $filter is not provided, the unfiltered list includes all + policy exemptions associated with the resource, including those that apply directly or from all + containing scopes, as well as any applied to resources contained within the resource. Three + parameters plus the resource name are used to identify a specific resource. If the resource is + not part of a parent resource (the more common case), the parent resource path should not be + provided (or provided as ''). For example a web app could be specified as + ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == + 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all + parameters should be provided. For example a virtual machine DNS name could be specified as + ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == + 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == + 'MyComputerName'). A convenient alternative to providing the namespace and type name separately + is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', + {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == + 'MyWebApp'). + + :param resource_group_name: The name of the resource group containing the resource. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. For example, the + namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Use empty string if there is none. + Required. + :type parent_resource_path: str + :param resource_type: The resource type name. For example the type name of a web app is 'sites' + (from Microsoft.Web/sites). Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group( + self, management_group_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a management group. + + This operation retrieves the list of all policy exemptions applicable to the management group + that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()', + 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter=atScope() is provided, the + returned list includes all policy exemptions that are assigned to the management group or the + management group's ancestors. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_for_management_group_request( + management_group_id=management_group_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class VariablesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`variables` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete(self, variable_name: str, **kwargs: Any) -> None: + """Deletes a variable. + + This operation deletes a variable, given its name and the subscription it was created in. The + scope of a variable is the part of its ID preceding + '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variables_delete_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def create_or_update( + self, variable_name: str, parameters: _models.Variable, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given subscription and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, variable_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given subscription and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, variable_name: str, parameters: Union[_models.Variable, IO[bytes]], **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given subscription and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Is either a Variable type or a IO[bytes] type. + Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable or IO[bytes] + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Variable") + + _request = build_variables_create_or_update_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get(self, variable_name: str, **kwargs: Any) -> _models.Variable: + """Retrieves a variable. + + This operation retrieves a single variable, given its name and the subscription it was created + at. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + _request = build_variables_get_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete_at_management_group(self, management_group_id: str, variable_name: str, **kwargs: Any) -> None: + """Deletes a variable. + + This operation deletes a variable, given its name and the management group it was created in. + The scope of a variable is the part of its ID preceding + '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variables_delete_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + parameters: _models.Variable, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given management group and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given management group and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + parameters: Union[_models.Variable, IO[bytes]], + **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given management group and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Is either a Variable type or a IO[bytes] type. + Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable or IO[bytes] + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Variable") + + _request = build_variables_create_or_update_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_at_management_group( + self, management_group_id: str, variable_name: str, **kwargs: Any + ) -> _models.Variable: + """Retrieves a variable. + + This operation retrieves a single variable, given its name and the management group it was + created at. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + _request = build_variables_get_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Variable"]: + """Retrieves all variables that are at this subscription level. + + This operation retrieves the list of all variables associated with the given subscription. + + :return: An iterator like instance of either Variable or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.Variable] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variables_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("VariableListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group(self, management_group_id: str, **kwargs: Any) -> AsyncItemPaged["_models.Variable"]: + """Retrieves all variables that are at this management group level. + + This operation retrieves the list of all variables applicable to the management group. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :return: An iterator like instance of either Variable or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.Variable] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variables_list_for_management_group_request( + management_group_id=management_group_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("VariableListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class VariableValuesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.aio.PolicyClient`'s + :attr:`variable_values` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def delete(self, variable_name: str, variable_value_name: str, **kwargs: Any) -> None: + """Deletes a variable value. + + This operation deletes a variable value, given its name, the subscription it was created in, + and the variable it belongs to. The scope of a variable value is the part of its ID preceding + '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variable_values_delete_request( + variable_name=variable_name, + variable_value_name=variable_value_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def create_or_update( + self, + variable_name: str, + variable_value_name: str, + parameters: _models.VariableValue, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given subscription and name for a + given variable. Variable values are scoped to the variable for which they are created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + variable_name: str, + variable_value_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given subscription and name for a + given variable. Variable values are scoped to the variable for which they are created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + variable_name: str, + variable_value_name: str, + parameters: Union[_models.VariableValue, IO[bytes]], + **kwargs: Any + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given subscription and name for a + given variable. Variable values are scoped to the variable for which they are created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Is either a VariableValue type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue or IO[bytes] + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "VariableValue") + + _request = build_variable_values_create_or_update_request( + variable_name=variable_name, + variable_value_name=variable_value_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get(self, variable_name: str, variable_value_name: str, **kwargs: Any) -> _models.VariableValue: + """Retrieves a variable value. + + This operation retrieves a single variable value; given its name, subscription it was created + at and the variable it's created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + _request = build_variable_values_get_request( + variable_name=variable_name, + variable_value_name=variable_value_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, variable_name: str, **kwargs: Any) -> AsyncItemPaged["_models.VariableValue"]: + """List variable values for a variable. + + This operation retrieves the list of all variable values associated with the given variable + that is at a subscription level. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: An iterator like instance of either VariableValue or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.VariableValue] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValueListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variable_values_list_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("VariableValueListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group( + self, management_group_id: str, variable_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.VariableValue"]: + """List variable values at management group level. + + This operation retrieves the list of all variable values applicable the variable indicated at + the management group scope. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: An iterator like instance of either VariableValue or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.policy.models.VariableValue] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValueListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variable_values_list_for_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("VariableValueListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def delete_at_management_group( + self, management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any + ) -> None: + """Deletes a variable value. + + This operation deletes a variable value, given its name, the management group it was created + in, and the variable it belongs to. The scope of a variable value is the part of its ID + preceding '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variable_values_delete_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + variable_value_name=variable_value_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + variable_value_name: str, + parameters: _models.VariableValue, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given management group and name for + a given variable. Variable values are scoped to the variable for which they are created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + variable_value_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given management group and name for + a given variable. Variable values are scoped to the variable for which they are created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + variable_value_name: str, + parameters: Union[_models.VariableValue, IO[bytes]], + **kwargs: Any + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given management group and name for + a given variable. Variable values are scoped to the variable for which they are created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Is either a VariableValue type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue or IO[bytes] + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "VariableValue") + + _request = build_variable_values_create_or_update_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + variable_value_name=variable_value_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_at_management_group( + self, management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any + ) -> _models.VariableValue: + """Retrieves a variable value. + + This operation retrieves a single variable value; given its name, management group it was + created at and the variable it's created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + _request = build_variable_values_get_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + variable_value_name=variable_value_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_patch.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/aio/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/__init__.py new file mode 100644 index 000000000000..28b5db51f4e5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/__init__.py @@ -0,0 +1,140 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + Alias, + AliasPath, + AliasPathMetadata, + AliasPattern, + DataEffect, + DataManifestCustomResourceFunctionDefinition, + DataPolicyManifest, + DataPolicyManifestListResult, + ErrorAdditionalInfo, + ErrorResponse, + Identity, + NonComplianceMessage, + Override, + ParameterDefinitionsValue, + ParameterDefinitionsValueMetadata, + ParameterValuesValue, + PolicyAssignment, + PolicyAssignmentListResult, + PolicyAssignmentUpdate, + PolicyDefinition, + PolicyDefinitionGroup, + PolicyDefinitionListResult, + PolicyDefinitionReference, + PolicyDefinitionVersion, + PolicyDefinitionVersionListResult, + PolicyExemption, + PolicyExemptionListResult, + PolicyExemptionUpdate, + PolicySetDefinition, + PolicySetDefinitionListResult, + PolicySetDefinitionVersion, + PolicySetDefinitionVersionListResult, + PolicyVariableColumn, + PolicyVariableValueColumnValue, + ResourceSelector, + ResourceTypeAliases, + Selector, + SystemData, + UserAssignedIdentitiesValue, + Variable, + VariableListResult, + VariableValue, + VariableValueListResult, +) + +from ._policy_client_enums import ( # type: ignore + AliasPathAttributes, + AliasPathTokenType, + AliasPatternType, + AliasType, + AssignmentScopeValidation, + CreatedByType, + EnforcementMode, + ExemptionCategory, + OverrideKind, + ParameterType, + PolicyType, + ResourceIdentityType, + SelectorKind, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Alias", + "AliasPath", + "AliasPathMetadata", + "AliasPattern", + "DataEffect", + "DataManifestCustomResourceFunctionDefinition", + "DataPolicyManifest", + "DataPolicyManifestListResult", + "ErrorAdditionalInfo", + "ErrorResponse", + "Identity", + "NonComplianceMessage", + "Override", + "ParameterDefinitionsValue", + "ParameterDefinitionsValueMetadata", + "ParameterValuesValue", + "PolicyAssignment", + "PolicyAssignmentListResult", + "PolicyAssignmentUpdate", + "PolicyDefinition", + "PolicyDefinitionGroup", + "PolicyDefinitionListResult", + "PolicyDefinitionReference", + "PolicyDefinitionVersion", + "PolicyDefinitionVersionListResult", + "PolicyExemption", + "PolicyExemptionListResult", + "PolicyExemptionUpdate", + "PolicySetDefinition", + "PolicySetDefinitionListResult", + "PolicySetDefinitionVersion", + "PolicySetDefinitionVersionListResult", + "PolicyVariableColumn", + "PolicyVariableValueColumnValue", + "ResourceSelector", + "ResourceTypeAliases", + "Selector", + "SystemData", + "UserAssignedIdentitiesValue", + "Variable", + "VariableListResult", + "VariableValue", + "VariableValueListResult", + "AliasPathAttributes", + "AliasPathTokenType", + "AliasPatternType", + "AliasType", + "AssignmentScopeValidation", + "CreatedByType", + "EnforcementMode", + "ExemptionCategory", + "OverrideKind", + "ParameterType", + "PolicyType", + "ResourceIdentityType", + "SelectorKind", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_models_py3.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_models_py3.py new file mode 100644 index 000000000000..5292feea9241 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_models_py3.py @@ -0,0 +1,2333 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from collections.abc import MutableMapping +import datetime +from typing import Any, Optional, TYPE_CHECKING, Union + +from .._utils import serialization as _serialization + +if TYPE_CHECKING: + from .. import models as _models +JSON = MutableMapping[str, Any] + + +class Alias(_serialization.Model): + """The alias type. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The alias name. + :vartype name: str + :ivar paths: The paths for an alias. + :vartype paths: list[~azure.mgmt.resource.policy.models.AliasPath] + :ivar type: The type of the alias. Known values are: "NotSpecified", "PlainText", and "Mask". + :vartype type: str or ~azure.mgmt.resource.policy.models.AliasType + :ivar default_path: The default path for an alias. + :vartype default_path: str + :ivar default_pattern: The default pattern for an alias. + :vartype default_pattern: ~azure.mgmt.resource.policy.models.AliasPattern + :ivar default_metadata: The default alias path metadata. Applies to the default path and to any + alias path that doesn't have metadata. + :vartype default_metadata: ~azure.mgmt.resource.policy.models.AliasPathMetadata + """ + + _validation = { + "default_metadata": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "paths": {"key": "paths", "type": "[AliasPath]"}, + "type": {"key": "type", "type": "str"}, + "default_path": {"key": "defaultPath", "type": "str"}, + "default_pattern": {"key": "defaultPattern", "type": "AliasPattern"}, + "default_metadata": {"key": "defaultMetadata", "type": "AliasPathMetadata"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + paths: Optional[list["_models.AliasPath"]] = None, + type: Optional[Union[str, "_models.AliasType"]] = None, + default_path: Optional[str] = None, + default_pattern: Optional["_models.AliasPattern"] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The alias name. + :paramtype name: str + :keyword paths: The paths for an alias. + :paramtype paths: list[~azure.mgmt.resource.policy.models.AliasPath] + :keyword type: The type of the alias. Known values are: "NotSpecified", "PlainText", and + "Mask". + :paramtype type: str or ~azure.mgmt.resource.policy.models.AliasType + :keyword default_path: The default path for an alias. + :paramtype default_path: str + :keyword default_pattern: The default pattern for an alias. + :paramtype default_pattern: ~azure.mgmt.resource.policy.models.AliasPattern + """ + super().__init__(**kwargs) + self.name = name + self.paths = paths + self.type = type + self.default_path = default_path + self.default_pattern = default_pattern + self.default_metadata: Optional["_models.AliasPathMetadata"] = None + + +class AliasPath(_serialization.Model): + """The type of the paths for alias. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar path: The path of an alias. + :vartype path: str + :ivar api_versions: The API versions. + :vartype api_versions: list[str] + :ivar pattern: The pattern for an alias path. + :vartype pattern: ~azure.mgmt.resource.policy.models.AliasPattern + :ivar metadata: The metadata of the alias path. If missing, fall back to the default metadata + of the alias. + :vartype metadata: ~azure.mgmt.resource.policy.models.AliasPathMetadata + """ + + _validation = { + "metadata": {"readonly": True}, + } + + _attribute_map = { + "path": {"key": "path", "type": "str"}, + "api_versions": {"key": "apiVersions", "type": "[str]"}, + "pattern": {"key": "pattern", "type": "AliasPattern"}, + "metadata": {"key": "metadata", "type": "AliasPathMetadata"}, + } + + def __init__( + self, + *, + path: Optional[str] = None, + api_versions: Optional[list[str]] = None, + pattern: Optional["_models.AliasPattern"] = None, + **kwargs: Any + ) -> None: + """ + :keyword path: The path of an alias. + :paramtype path: str + :keyword api_versions: The API versions. + :paramtype api_versions: list[str] + :keyword pattern: The pattern for an alias path. + :paramtype pattern: ~azure.mgmt.resource.policy.models.AliasPattern + """ + super().__init__(**kwargs) + self.path = path + self.api_versions = api_versions + self.pattern = pattern + self.metadata: Optional["_models.AliasPathMetadata"] = None + + +class AliasPathMetadata(_serialization.Model): + """AliasPathMetadata. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The type of the token that the alias path is referring to. Known values are: + "NotSpecified", "Any", "String", "Object", "Array", "Integer", "Number", and "Boolean". + :vartype type: str or ~azure.mgmt.resource.policy.models.AliasPathTokenType + :ivar attributes: The attributes of the token that the alias path is referring to. Known values + are: "None" and "Modifiable". + :vartype attributes: str or ~azure.mgmt.resource.policy.models.AliasPathAttributes + """ + + _validation = { + "type": {"readonly": True}, + "attributes": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "attributes": {"key": "attributes", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type: Optional[Union[str, "_models.AliasPathTokenType"]] = None + self.attributes: Optional[Union[str, "_models.AliasPathAttributes"]] = None + + +class AliasPattern(_serialization.Model): + """The type of the pattern for an alias path. + + :ivar phrase: The alias pattern phrase. + :vartype phrase: str + :ivar variable: The alias pattern variable. + :vartype variable: str + :ivar type: The type of alias pattern. Known values are: "NotSpecified" and "Extract". + :vartype type: str or ~azure.mgmt.resource.policy.models.AliasPatternType + """ + + _attribute_map = { + "phrase": {"key": "phrase", "type": "str"}, + "variable": {"key": "variable", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + phrase: Optional[str] = None, + variable: Optional[str] = None, + type: Optional[Union[str, "_models.AliasPatternType"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword phrase: The alias pattern phrase. + :paramtype phrase: str + :keyword variable: The alias pattern variable. + :paramtype variable: str + :keyword type: The type of alias pattern. Known values are: "NotSpecified" and "Extract". + :paramtype type: str or ~azure.mgmt.resource.policy.models.AliasPatternType + """ + super().__init__(**kwargs) + self.phrase = phrase + self.variable = variable + self.type = type + + +class DataEffect(_serialization.Model): + """The data effect definition. + + :ivar name: The data effect name. + :vartype name: str + :ivar details_schema: The data effect details schema. + :vartype details_schema: JSON + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "details_schema": {"key": "detailsSchema", "type": "object"}, + } + + def __init__(self, *, name: Optional[str] = None, details_schema: Optional[JSON] = None, **kwargs: Any) -> None: + """ + :keyword name: The data effect name. + :paramtype name: str + :keyword details_schema: The data effect details schema. + :paramtype details_schema: JSON + """ + super().__init__(**kwargs) + self.name = name + self.details_schema = details_schema + + +class DataManifestCustomResourceFunctionDefinition(_serialization.Model): # pylint: disable=name-too-long + """The custom resource function definition. + + :ivar name: The function name as it will appear in the policy rule. eg - 'vault'. + :vartype name: str + :ivar fully_qualified_resource_type: The fully qualified control plane resource type that this + function represents. eg - 'Microsoft.KeyVault/vaults'. + :vartype fully_qualified_resource_type: str + :ivar default_properties: The top-level properties that can be selected on the function's + output. eg - [ "name", "location" ] if vault().name and vault().location are supported. + :vartype default_properties: list[str] + :ivar allow_custom_properties: A value indicating whether the custom properties within the + property bag are allowed. Needs api-version to be specified in the policy rule eg - + vault('2019-06-01'). + :vartype allow_custom_properties: bool + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "fully_qualified_resource_type": {"key": "fullyQualifiedResourceType", "type": "str"}, + "default_properties": {"key": "defaultProperties", "type": "[str]"}, + "allow_custom_properties": {"key": "allowCustomProperties", "type": "bool"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + fully_qualified_resource_type: Optional[str] = None, + default_properties: Optional[list[str]] = None, + allow_custom_properties: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The function name as it will appear in the policy rule. eg - 'vault'. + :paramtype name: str + :keyword fully_qualified_resource_type: The fully qualified control plane resource type that + this function represents. eg - 'Microsoft.KeyVault/vaults'. + :paramtype fully_qualified_resource_type: str + :keyword default_properties: The top-level properties that can be selected on the function's + output. eg - [ "name", "location" ] if vault().name and vault().location are supported. + :paramtype default_properties: list[str] + :keyword allow_custom_properties: A value indicating whether the custom properties within the + property bag are allowed. Needs api-version to be specified in the policy rule eg - + vault('2019-06-01'). + :paramtype allow_custom_properties: bool + """ + super().__init__(**kwargs) + self.name = name + self.fully_qualified_resource_type = fully_qualified_resource_type + self.default_properties = default_properties + self.allow_custom_properties = allow_custom_properties + + +class DataPolicyManifest(_serialization.Model): + """The data policy manifest. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the data policy manifest. + :vartype id: str + :ivar name: The name of the data policy manifest (it's the same as the Policy Mode). + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/dataPolicyManifests). + :vartype type: str + :ivar namespaces: The list of namespaces for the data policy manifest. + :vartype namespaces: list[str] + :ivar policy_mode: The policy mode of the data policy manifest. + :vartype policy_mode: str + :ivar is_built_in_only: A value indicating whether policy mode is allowed only in built-in + definitions. + :vartype is_built_in_only: bool + :ivar resource_type_aliases: An array of resource type aliases. + :vartype resource_type_aliases: list[~azure.mgmt.resource.policy.models.ResourceTypeAliases] + :ivar effects: The effect definition. + :vartype effects: list[~azure.mgmt.resource.policy.models.DataEffect] + :ivar field_values: The non-alias field accessor values that can be used in the policy rule. + :vartype field_values: list[str] + :ivar standard: The standard resource functions (subscription and/or resourceGroup). + :vartype standard: list[str] + :ivar custom: An array of data manifest custom resource definition. + :vartype custom: + list[~azure.mgmt.resource.policy.models.DataManifestCustomResourceFunctionDefinition] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "namespaces": {"key": "properties.namespaces", "type": "[str]"}, + "policy_mode": {"key": "properties.policyMode", "type": "str"}, + "is_built_in_only": {"key": "properties.isBuiltInOnly", "type": "bool"}, + "resource_type_aliases": {"key": "properties.resourceTypeAliases", "type": "[ResourceTypeAliases]"}, + "effects": {"key": "properties.effects", "type": "[DataEffect]"}, + "field_values": {"key": "properties.fieldValues", "type": "[str]"}, + "standard": {"key": "properties.resourceFunctions.standard", "type": "[str]"}, + "custom": { + "key": "properties.resourceFunctions.custom", + "type": "[DataManifestCustomResourceFunctionDefinition]", + }, + } + + def __init__( + self, + *, + namespaces: Optional[list[str]] = None, + policy_mode: Optional[str] = None, + is_built_in_only: Optional[bool] = None, + resource_type_aliases: Optional[list["_models.ResourceTypeAliases"]] = None, + effects: Optional[list["_models.DataEffect"]] = None, + field_values: Optional[list[str]] = None, + standard: Optional[list[str]] = None, + custom: Optional[list["_models.DataManifestCustomResourceFunctionDefinition"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword namespaces: The list of namespaces for the data policy manifest. + :paramtype namespaces: list[str] + :keyword policy_mode: The policy mode of the data policy manifest. + :paramtype policy_mode: str + :keyword is_built_in_only: A value indicating whether policy mode is allowed only in built-in + definitions. + :paramtype is_built_in_only: bool + :keyword resource_type_aliases: An array of resource type aliases. + :paramtype resource_type_aliases: list[~azure.mgmt.resource.policy.models.ResourceTypeAliases] + :keyword effects: The effect definition. + :paramtype effects: list[~azure.mgmt.resource.policy.models.DataEffect] + :keyword field_values: The non-alias field accessor values that can be used in the policy rule. + :paramtype field_values: list[str] + :keyword standard: The standard resource functions (subscription and/or resourceGroup). + :paramtype standard: list[str] + :keyword custom: An array of data manifest custom resource definition. + :paramtype custom: + list[~azure.mgmt.resource.policy.models.DataManifestCustomResourceFunctionDefinition] + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.namespaces = namespaces + self.policy_mode = policy_mode + self.is_built_in_only = is_built_in_only + self.resource_type_aliases = resource_type_aliases + self.effects = effects + self.field_values = field_values + self.standard = standard + self.custom = custom + + +class DataPolicyManifestListResult(_serialization.Model): + """List of data policy manifests. + + :ivar value: An array of data policy manifests. + :vartype value: list[~azure.mgmt.resource.policy.models.DataPolicyManifest] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[DataPolicyManifest]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.DataPolicyManifest"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of data policy manifests. + :paramtype value: list[~azure.mgmt.resource.policy.models.DataPolicyManifest] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type: Optional[str] = None + self.info: Optional[JSON] = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.resource.policy.models.ErrorResponse] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.resource.policy.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorResponse]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code: Optional[str] = None + self.message: Optional[str] = None + self.target: Optional[str] = None + self.details: Optional[list["_models.ErrorResponse"]] = None + self.additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = None + + +class Identity(_serialization.Model): + """Identity for the resource. Policy assignments support a maximum of one identity. That is + either a system assigned identity or a single user assigned identity. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal ID of the resource identity. This property will only be + provided for a system assigned identity. + :vartype principal_id: str + :ivar tenant_id: The tenant ID of the resource identity. This property will only be provided + for a system assigned identity. + :vartype tenant_id: str + :ivar type: The identity type. This is the only required field when adding a system or user + assigned identity to a resource. Known values are: "SystemAssigned", "UserAssigned", and + "None". + :vartype type: str or ~azure.mgmt.resource.policy.models.ResourceIdentityType + :ivar user_assigned_identities: The user identity associated with the policy. The user identity + dictionary key references will be ARM resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + :vartype user_assigned_identities: dict[str, + ~azure.mgmt.resource.policy.models.UserAssignedIdentitiesValue] + """ + + _validation = { + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentitiesValue}"}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "_models.ResourceIdentityType"]] = None, + user_assigned_identities: Optional[dict[str, "_models.UserAssignedIdentitiesValue"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword type: The identity type. This is the only required field when adding a system or user + assigned identity to a resource. Known values are: "SystemAssigned", "UserAssigned", and + "None". + :paramtype type: str or ~azure.mgmt.resource.policy.models.ResourceIdentityType + :keyword user_assigned_identities: The user identity associated with the policy. The user + identity dictionary key references will be ARM resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + :paramtype user_assigned_identities: dict[str, + ~azure.mgmt.resource.policy.models.UserAssignedIdentitiesValue] + """ + super().__init__(**kwargs) + self.principal_id: Optional[str] = None + self.tenant_id: Optional[str] = None + self.type = type + self.user_assigned_identities = user_assigned_identities + + +class NonComplianceMessage(_serialization.Model): + """A message that describes why a resource is non-compliant with the policy. This is shown in + 'deny' error messages and on resource's non-compliant compliance results. + + All required parameters must be populated in order to send to server. + + :ivar message: A message that describes why a resource is non-compliant with the policy. This + is shown in 'deny' error messages and on resource's non-compliant compliance results. Required. + :vartype message: str + :ivar policy_definition_reference_id: The policy definition reference ID within a policy set + definition the message is intended for. This is only applicable if the policy assignment + assigns a policy set definition. If this is not provided the message applies to all policies + assigned by this policy assignment. + :vartype policy_definition_reference_id: str + """ + + _validation = { + "message": {"required": True}, + } + + _attribute_map = { + "message": {"key": "message", "type": "str"}, + "policy_definition_reference_id": {"key": "policyDefinitionReferenceId", "type": "str"}, + } + + def __init__(self, *, message: str, policy_definition_reference_id: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword message: A message that describes why a resource is non-compliant with the policy. + This is shown in 'deny' error messages and on resource's non-compliant compliance results. + Required. + :paramtype message: str + :keyword policy_definition_reference_id: The policy definition reference ID within a policy set + definition the message is intended for. This is only applicable if the policy assignment + assigns a policy set definition. If this is not provided the message applies to all policies + assigned by this policy assignment. + :paramtype policy_definition_reference_id: str + """ + super().__init__(**kwargs) + self.message = message + self.policy_definition_reference_id = policy_definition_reference_id + + +class Override(_serialization.Model): + """The policy property value override. + + :ivar kind: The override kind. "policyEffect" + :vartype kind: str or ~azure.mgmt.resource.policy.models.OverrideKind + :ivar value: The value to override the policy property. + :vartype value: str + :ivar selectors: The list of the selector expressions. + :vartype selectors: list[~azure.mgmt.resource.policy.models.Selector] + """ + + _attribute_map = { + "kind": {"key": "kind", "type": "str"}, + "value": {"key": "value", "type": "str"}, + "selectors": {"key": "selectors", "type": "[Selector]"}, + } + + def __init__( + self, + *, + kind: Optional[Union[str, "_models.OverrideKind"]] = None, + value: Optional[str] = None, + selectors: Optional[list["_models.Selector"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword kind: The override kind. "policyEffect" + :paramtype kind: str or ~azure.mgmt.resource.policy.models.OverrideKind + :keyword value: The value to override the policy property. + :paramtype value: str + :keyword selectors: The list of the selector expressions. + :paramtype selectors: list[~azure.mgmt.resource.policy.models.Selector] + """ + super().__init__(**kwargs) + self.kind = kind + self.value = value + self.selectors = selectors + + +class ParameterDefinitionsValue(_serialization.Model): + """The definition of a parameter that can be provided to the policy. + + :ivar type: The data type of the parameter. Known values are: "String", "Array", "Object", + "Boolean", "Integer", "Float", and "DateTime". + :vartype type: str or ~azure.mgmt.resource.policy.models.ParameterType + :ivar allowed_values: The allowed values for the parameter. + :vartype allowed_values: list[JSON] + :ivar default_value: The default value for the parameter if no value is provided. + :vartype default_value: JSON + :ivar schema: Provides validation of parameter inputs during assignment using a self-defined + JSON schema. This property is only supported for object-type parameters and follows the + Json.NET Schema 2019-09 implementation. You can learn more about using schemas at + https://json-schema.org/ and test draft schemas at https://www.jsonschemavalidator.net/. + :vartype schema: JSON + :ivar metadata: General metadata for the parameter. + :vartype metadata: ~azure.mgmt.resource.policy.models.ParameterDefinitionsValueMetadata + """ + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "allowed_values": {"key": "allowedValues", "type": "[object]"}, + "default_value": {"key": "defaultValue", "type": "object"}, + "schema": {"key": "schema", "type": "object"}, + "metadata": {"key": "metadata", "type": "ParameterDefinitionsValueMetadata"}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "_models.ParameterType"]] = None, + allowed_values: Optional[list[JSON]] = None, + default_value: Optional[JSON] = None, + schema: Optional[JSON] = None, + metadata: Optional["_models.ParameterDefinitionsValueMetadata"] = None, + **kwargs: Any + ) -> None: + """ + :keyword type: The data type of the parameter. Known values are: "String", "Array", "Object", + "Boolean", "Integer", "Float", and "DateTime". + :paramtype type: str or ~azure.mgmt.resource.policy.models.ParameterType + :keyword allowed_values: The allowed values for the parameter. + :paramtype allowed_values: list[JSON] + :keyword default_value: The default value for the parameter if no value is provided. + :paramtype default_value: JSON + :keyword schema: Provides validation of parameter inputs during assignment using a self-defined + JSON schema. This property is only supported for object-type parameters and follows the + Json.NET Schema 2019-09 implementation. You can learn more about using schemas at + https://json-schema.org/ and test draft schemas at https://www.jsonschemavalidator.net/. + :paramtype schema: JSON + :keyword metadata: General metadata for the parameter. + :paramtype metadata: ~azure.mgmt.resource.policy.models.ParameterDefinitionsValueMetadata + """ + super().__init__(**kwargs) + self.type = type + self.allowed_values = allowed_values + self.default_value = default_value + self.schema = schema + self.metadata = metadata + + +class ParameterDefinitionsValueMetadata(_serialization.Model): + """General metadata for the parameter. + + :ivar additional_properties: Unmatched properties from the message are deserialized to this + collection. + :vartype additional_properties: dict[str, JSON] + :ivar display_name: The display name for the parameter. + :vartype display_name: str + :ivar description: The description of the parameter. + :vartype description: str + :ivar strong_type: Used when assigning the policy definition through the portal. Provides a + context aware list of values for the user to choose from. + :vartype strong_type: str + :ivar assign_permissions: Set to true to have Azure portal create role assignments on the + resource ID or resource scope value of this parameter during policy assignment. This property + is useful in case you wish to assign permissions outside the assignment scope. + :vartype assign_permissions: bool + """ + + _attribute_map = { + "additional_properties": {"key": "", "type": "{object}"}, + "display_name": {"key": "displayName", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "strong_type": {"key": "strongType", "type": "str"}, + "assign_permissions": {"key": "assignPermissions", "type": "bool"}, + } + + def __init__( + self, + *, + additional_properties: Optional[dict[str, JSON]] = None, + display_name: Optional[str] = None, + description: Optional[str] = None, + strong_type: Optional[str] = None, + assign_permissions: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword additional_properties: Unmatched properties from the message are deserialized to this + collection. + :paramtype additional_properties: dict[str, JSON] + :keyword display_name: The display name for the parameter. + :paramtype display_name: str + :keyword description: The description of the parameter. + :paramtype description: str + :keyword strong_type: Used when assigning the policy definition through the portal. Provides a + context aware list of values for the user to choose from. + :paramtype strong_type: str + :keyword assign_permissions: Set to true to have Azure portal create role assignments on the + resource ID or resource scope value of this parameter during policy assignment. This property + is useful in case you wish to assign permissions outside the assignment scope. + :paramtype assign_permissions: bool + """ + super().__init__(**kwargs) + self.additional_properties = additional_properties + self.display_name = display_name + self.description = description + self.strong_type = strong_type + self.assign_permissions = assign_permissions + + +class ParameterValuesValue(_serialization.Model): + """The value of a parameter. + + :ivar value: The value of the parameter. + :vartype value: JSON + """ + + _attribute_map = { + "value": {"key": "value", "type": "object"}, + } + + def __init__(self, *, value: Optional[JSON] = None, **kwargs: Any) -> None: + """ + :keyword value: The value of the parameter. + :paramtype value: JSON + """ + super().__init__(**kwargs) + self.value = value + + +class PolicyAssignment(_serialization.Model): + """The policy assignment. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy assignment. + :vartype id: str + :ivar type: The type of the policy assignment. + :vartype type: str + :ivar name: The name of the policy assignment. + :vartype name: str + :ivar location: The location of the policy assignment. Only required when utilizing managed + identity. + :vartype location: str + :ivar identity: The managed identity associated with the policy assignment. + :vartype identity: ~azure.mgmt.resource.policy.models.Identity + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar display_name: The display name of the policy assignment. + :vartype display_name: str + :ivar policy_definition_id: The ID of the policy definition or policy set definition being + assigned. + :vartype policy_definition_id: str + :ivar definition_version: The version of the policy definition to use. + :vartype definition_version: str + :ivar latest_definition_version: The latest version of the policy definition available. This is + only present if requested via the $expand query parameter. + :vartype latest_definition_version: str + :ivar effective_definition_version: The effective version of the policy definition in use. This + is only present if requested via the $expand query parameter. + :vartype effective_definition_version: str + :ivar scope: The scope for the policy assignment. + :vartype scope: str + :ivar not_scopes: The policy's excluded scopes. + :vartype not_scopes: list[str] + :ivar parameters: The parameter values for the assigned policy rule. The keys are the parameter + names. + :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterValuesValue] + :ivar description: This message will be part of response in case of policy violation. + :vartype description: str + :ivar metadata: The policy assignment metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :vartype metadata: JSON + :ivar enforcement_mode: The policy assignment enforcement mode. Possible values are Default and + DoNotEnforce. Known values are: "Default" and "DoNotEnforce". + :vartype enforcement_mode: str or ~azure.mgmt.resource.policy.models.EnforcementMode + :ivar non_compliance_messages: The messages that describe why a resource is non-compliant with + the policy. + :vartype non_compliance_messages: list[~azure.mgmt.resource.policy.models.NonComplianceMessage] + :ivar resource_selectors: The resource selector list to filter policies by resource properties. + :vartype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :ivar overrides: The policy property value override. + :vartype overrides: list[~azure.mgmt.resource.policy.models.Override] + """ + + _validation = { + "id": {"readonly": True}, + "type": {"readonly": True}, + "name": {"readonly": True}, + "system_data": {"readonly": True}, + "latest_definition_version": {"readonly": True}, + "effective_definition_version": {"readonly": True}, + "scope": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "identity": {"key": "identity", "type": "Identity"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "policy_definition_id": {"key": "properties.policyDefinitionId", "type": "str"}, + "definition_version": {"key": "properties.definitionVersion", "type": "str"}, + "latest_definition_version": {"key": "properties.latestDefinitionVersion", "type": "str"}, + "effective_definition_version": {"key": "properties.effectiveDefinitionVersion", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "not_scopes": {"key": "properties.notScopes", "type": "[str]"}, + "parameters": {"key": "properties.parameters", "type": "{ParameterValuesValue}"}, + "description": {"key": "properties.description", "type": "str"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "enforcement_mode": {"key": "properties.enforcementMode", "type": "str"}, + "non_compliance_messages": {"key": "properties.nonComplianceMessages", "type": "[NonComplianceMessage]"}, + "resource_selectors": {"key": "properties.resourceSelectors", "type": "[ResourceSelector]"}, + "overrides": {"key": "properties.overrides", "type": "[Override]"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + identity: Optional["_models.Identity"] = None, + display_name: Optional[str] = None, + policy_definition_id: Optional[str] = None, + definition_version: Optional[str] = None, + not_scopes: Optional[list[str]] = None, + parameters: Optional[dict[str, "_models.ParameterValuesValue"]] = None, + description: Optional[str] = None, + metadata: Optional[JSON] = None, + enforcement_mode: Union[str, "_models.EnforcementMode"] = "Default", + non_compliance_messages: Optional[list["_models.NonComplianceMessage"]] = None, + resource_selectors: Optional[list["_models.ResourceSelector"]] = None, + overrides: Optional[list["_models.Override"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the policy assignment. Only required when utilizing managed + identity. + :paramtype location: str + :keyword identity: The managed identity associated with the policy assignment. + :paramtype identity: ~azure.mgmt.resource.policy.models.Identity + :keyword display_name: The display name of the policy assignment. + :paramtype display_name: str + :keyword policy_definition_id: The ID of the policy definition or policy set definition being + assigned. + :paramtype policy_definition_id: str + :keyword definition_version: The version of the policy definition to use. + :paramtype definition_version: str + :keyword not_scopes: The policy's excluded scopes. + :paramtype not_scopes: list[str] + :keyword parameters: The parameter values for the assigned policy rule. The keys are the + parameter names. + :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterValuesValue] + :keyword description: This message will be part of response in case of policy violation. + :paramtype description: str + :keyword metadata: The policy assignment metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :paramtype metadata: JSON + :keyword enforcement_mode: The policy assignment enforcement mode. Possible values are Default + and DoNotEnforce. Known values are: "Default" and "DoNotEnforce". + :paramtype enforcement_mode: str or ~azure.mgmt.resource.policy.models.EnforcementMode + :keyword non_compliance_messages: The messages that describe why a resource is non-compliant + with the policy. + :paramtype non_compliance_messages: + list[~azure.mgmt.resource.policy.models.NonComplianceMessage] + :keyword resource_selectors: The resource selector list to filter policies by resource + properties. + :paramtype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :keyword overrides: The policy property value override. + :paramtype overrides: list[~azure.mgmt.resource.policy.models.Override] + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.type: Optional[str] = None + self.name: Optional[str] = None + self.location = location + self.identity = identity + self.system_data: Optional["_models.SystemData"] = None + self.display_name = display_name + self.policy_definition_id = policy_definition_id + self.definition_version = definition_version + self.latest_definition_version: Optional[str] = None + self.effective_definition_version: Optional[str] = None + self.scope: Optional[str] = None + self.not_scopes = not_scopes + self.parameters = parameters + self.description = description + self.metadata = metadata + self.enforcement_mode = enforcement_mode + self.non_compliance_messages = non_compliance_messages + self.resource_selectors = resource_selectors + self.overrides = overrides + + +class PolicyAssignmentListResult(_serialization.Model): + """List of policy assignments. + + :ivar value: An array of policy assignments. + :vartype value: list[~azure.mgmt.resource.policy.models.PolicyAssignment] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.PolicyAssignment"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy assignments. + :paramtype value: list[~azure.mgmt.resource.policy.models.PolicyAssignment] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PolicyAssignmentUpdate(_serialization.Model): + """The policy assignment for Patch request. + + :ivar location: The location of the policy assignment. Only required when utilizing managed + identity. + :vartype location: str + :ivar identity: The managed identity associated with the policy assignment. + :vartype identity: ~azure.mgmt.resource.policy.models.Identity + :ivar resource_selectors: The resource selector list to filter policies by resource properties. + :vartype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :ivar overrides: The policy property value override. + :vartype overrides: list[~azure.mgmt.resource.policy.models.Override] + """ + + _attribute_map = { + "location": {"key": "location", "type": "str"}, + "identity": {"key": "identity", "type": "Identity"}, + "resource_selectors": {"key": "properties.resourceSelectors", "type": "[ResourceSelector]"}, + "overrides": {"key": "properties.overrides", "type": "[Override]"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + identity: Optional["_models.Identity"] = None, + resource_selectors: Optional[list["_models.ResourceSelector"]] = None, + overrides: Optional[list["_models.Override"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the policy assignment. Only required when utilizing managed + identity. + :paramtype location: str + :keyword identity: The managed identity associated with the policy assignment. + :paramtype identity: ~azure.mgmt.resource.policy.models.Identity + :keyword resource_selectors: The resource selector list to filter policies by resource + properties. + :paramtype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :keyword overrides: The policy property value override. + :paramtype overrides: list[~azure.mgmt.resource.policy.models.Override] + """ + super().__init__(**kwargs) + self.location = location + self.identity = identity + self.resource_selectors = resource_selectors + self.overrides = overrides + + +class PolicyDefinition(_serialization.Model): + """The policy definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy definition. + :vartype id: str + :ivar name: The name of the policy definition. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/policyDefinitions). + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". + :vartype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :ivar mode: The policy definition mode. Some examples are All, Indexed, + Microsoft.KeyVault.Data. + :vartype mode: str + :ivar display_name: The display name of the policy definition. + :vartype display_name: str + :ivar description: The policy definition description. + :vartype description: str + :ivar policy_rule: The policy rule. + :vartype policy_rule: JSON + :ivar metadata: The policy definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :vartype metadata: JSON + :ivar parameters: The parameter definitions for parameters used in the policy rule. The keys + are the parameter names. + :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :ivar version: The policy definition version in #.#.# format. + :vartype version: str + :ivar versions: A list of available versions for this policy definition. + :vartype versions: list[str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "policy_type": {"key": "properties.policyType", "type": "str"}, + "mode": {"key": "properties.mode", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "policy_rule": {"key": "properties.policyRule", "type": "object"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "parameters": {"key": "properties.parameters", "type": "{ParameterDefinitionsValue}"}, + "version": {"key": "properties.version", "type": "str"}, + "versions": {"key": "properties.versions", "type": "[str]"}, + } + + def __init__( + self, + *, + policy_type: Optional[Union[str, "_models.PolicyType"]] = None, + mode: str = "Indexed", + display_name: Optional[str] = None, + description: Optional[str] = None, + policy_rule: Optional[JSON] = None, + metadata: Optional[JSON] = None, + parameters: Optional[dict[str, "_models.ParameterDefinitionsValue"]] = None, + version: Optional[str] = None, + versions: Optional[list[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". + :paramtype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :keyword mode: The policy definition mode. Some examples are All, Indexed, + Microsoft.KeyVault.Data. + :paramtype mode: str + :keyword display_name: The display name of the policy definition. + :paramtype display_name: str + :keyword description: The policy definition description. + :paramtype description: str + :keyword policy_rule: The policy rule. + :paramtype policy_rule: JSON + :keyword metadata: The policy definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :paramtype metadata: JSON + :keyword parameters: The parameter definitions for parameters used in the policy rule. The keys + are the parameter names. + :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :keyword version: The policy definition version in #.#.# format. + :paramtype version: str + :keyword versions: A list of available versions for this policy definition. + :paramtype versions: list[str] + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + self.policy_type = policy_type + self.mode = mode + self.display_name = display_name + self.description = description + self.policy_rule = policy_rule + self.metadata = metadata + self.parameters = parameters + self.version = version + self.versions = versions + + +class PolicyDefinitionGroup(_serialization.Model): + """The policy definition group. + + All required parameters must be populated in order to send to server. + + :ivar name: The name of the group. Required. + :vartype name: str + :ivar display_name: The group's display name. + :vartype display_name: str + :ivar category: The group's category. + :vartype category: str + :ivar description: The group's description. + :vartype description: str + :ivar additional_metadata_id: A resource ID of a resource that contains additional metadata + about the group. + :vartype additional_metadata_id: str + """ + + _validation = { + "name": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "additional_metadata_id": {"key": "additionalMetadataId", "type": "str"}, + } + + def __init__( + self, + *, + name: str, + display_name: Optional[str] = None, + category: Optional[str] = None, + description: Optional[str] = None, + additional_metadata_id: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The name of the group. Required. + :paramtype name: str + :keyword display_name: The group's display name. + :paramtype display_name: str + :keyword category: The group's category. + :paramtype category: str + :keyword description: The group's description. + :paramtype description: str + :keyword additional_metadata_id: A resource ID of a resource that contains additional metadata + about the group. + :paramtype additional_metadata_id: str + """ + super().__init__(**kwargs) + self.name = name + self.display_name = display_name + self.category = category + self.description = description + self.additional_metadata_id = additional_metadata_id + + +class PolicyDefinitionListResult(_serialization.Model): + """List of policy definitions. + + :ivar value: An array of policy definitions. + :vartype value: list[~azure.mgmt.resource.policy.models.PolicyDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.PolicyDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy definitions. + :paramtype value: list[~azure.mgmt.resource.policy.models.PolicyDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PolicyDefinitionReference(_serialization.Model): + """The policy definition reference. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar policy_definition_id: The ID of the policy definition or policy set definition. Required. + :vartype policy_definition_id: str + :ivar definition_version: The version of the policy definition to use. + :vartype definition_version: str + :ivar latest_definition_version: The latest version of the policy definition available. This is + only present if requested via the $expand query parameter. + :vartype latest_definition_version: str + :ivar effective_definition_version: The effective version of the policy definition in use. This + is only present if requested via the $expand query parameter. + :vartype effective_definition_version: str + :ivar parameters: The parameter values for the referenced policy rule. The keys are the + parameter names. + :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterValuesValue] + :ivar policy_definition_reference_id: A unique id (within the policy set definition) for this + policy definition reference. + :vartype policy_definition_reference_id: str + :ivar group_names: The name of the groups that this policy definition reference belongs to. + :vartype group_names: list[str] + """ + + _validation = { + "policy_definition_id": {"required": True}, + "latest_definition_version": {"readonly": True}, + "effective_definition_version": {"readonly": True}, + } + + _attribute_map = { + "policy_definition_id": {"key": "policyDefinitionId", "type": "str"}, + "definition_version": {"key": "definitionVersion", "type": "str"}, + "latest_definition_version": {"key": "latestDefinitionVersion", "type": "str"}, + "effective_definition_version": {"key": "effectiveDefinitionVersion", "type": "str"}, + "parameters": {"key": "parameters", "type": "{ParameterValuesValue}"}, + "policy_definition_reference_id": {"key": "policyDefinitionReferenceId", "type": "str"}, + "group_names": {"key": "groupNames", "type": "[str]"}, + } + + def __init__( + self, + *, + policy_definition_id: str, + definition_version: Optional[str] = None, + parameters: Optional[dict[str, "_models.ParameterValuesValue"]] = None, + policy_definition_reference_id: Optional[str] = None, + group_names: Optional[list[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword policy_definition_id: The ID of the policy definition or policy set definition. + Required. + :paramtype policy_definition_id: str + :keyword definition_version: The version of the policy definition to use. + :paramtype definition_version: str + :keyword parameters: The parameter values for the referenced policy rule. The keys are the + parameter names. + :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterValuesValue] + :keyword policy_definition_reference_id: A unique id (within the policy set definition) for + this policy definition reference. + :paramtype policy_definition_reference_id: str + :keyword group_names: The name of the groups that this policy definition reference belongs to. + :paramtype group_names: list[str] + """ + super().__init__(**kwargs) + self.policy_definition_id = policy_definition_id + self.definition_version = definition_version + self.latest_definition_version: Optional[str] = None + self.effective_definition_version: Optional[str] = None + self.parameters = parameters + self.policy_definition_reference_id = policy_definition_reference_id + self.group_names = group_names + + +class PolicyDefinitionVersion(_serialization.Model): + """The ID of the policy definition version. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy definition version. + :vartype id: str + :ivar name: The name of the policy definition version. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/policyDefinitions/versions). + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". + :vartype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :ivar mode: The policy definition mode. Some examples are All, Indexed, + Microsoft.KeyVault.Data. + :vartype mode: str + :ivar display_name: The display name of the policy definition. + :vartype display_name: str + :ivar description: The policy definition description. + :vartype description: str + :ivar policy_rule: The policy rule. + :vartype policy_rule: JSON + :ivar metadata: The policy definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :vartype metadata: JSON + :ivar parameters: The parameter definitions for parameters used in the policy rule. The keys + are the parameter names. + :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :ivar version: The policy definition version in #.#.# format. + :vartype version: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "policy_type": {"key": "properties.policyType", "type": "str"}, + "mode": {"key": "properties.mode", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "policy_rule": {"key": "properties.policyRule", "type": "object"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "parameters": {"key": "properties.parameters", "type": "{ParameterDefinitionsValue}"}, + "version": {"key": "properties.version", "type": "str"}, + } + + def __init__( + self, + *, + policy_type: Optional[Union[str, "_models.PolicyType"]] = None, + mode: str = "Indexed", + display_name: Optional[str] = None, + description: Optional[str] = None, + policy_rule: Optional[JSON] = None, + metadata: Optional[JSON] = None, + parameters: Optional[dict[str, "_models.ParameterDefinitionsValue"]] = None, + version: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". + :paramtype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :keyword mode: The policy definition mode. Some examples are All, Indexed, + Microsoft.KeyVault.Data. + :paramtype mode: str + :keyword display_name: The display name of the policy definition. + :paramtype display_name: str + :keyword description: The policy definition description. + :paramtype description: str + :keyword policy_rule: The policy rule. + :paramtype policy_rule: JSON + :keyword metadata: The policy definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :paramtype metadata: JSON + :keyword parameters: The parameter definitions for parameters used in the policy rule. The keys + are the parameter names. + :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :keyword version: The policy definition version in #.#.# format. + :paramtype version: str + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + self.policy_type = policy_type + self.mode = mode + self.display_name = display_name + self.description = description + self.policy_rule = policy_rule + self.metadata = metadata + self.parameters = parameters + self.version = version + + +class PolicyDefinitionVersionListResult(_serialization.Model): + """List of policy definition versions. + + :ivar value: An array of policy definitions versions. + :vartype value: list[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyDefinitionVersion]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.PolicyDefinitionVersion"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy definitions versions. + :paramtype value: list[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PolicyExemption(_serialization.Model): + """The policy exemption. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar id: The ID of the policy exemption. + :vartype id: str + :ivar name: The name of the policy exemption. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/policyExemptions). + :vartype type: str + :ivar policy_assignment_id: The ID of the policy assignment that is being exempted. Required. + :vartype policy_assignment_id: str + :ivar policy_definition_reference_ids: The policy definition reference ID list when the + associated policy assignment is an assignment of a policy set definition. + :vartype policy_definition_reference_ids: list[str] + :ivar exemption_category: The policy exemption category. Possible values are Waiver and + Mitigated. Required. Known values are: "Waiver" and "Mitigated". + :vartype exemption_category: str or ~azure.mgmt.resource.policy.models.ExemptionCategory + :ivar expires_on: The expiration date and time (in UTC ISO 8601 format yyyy-MM-ddTHH:mm:ssZ) of + the policy exemption. + :vartype expires_on: ~datetime.datetime + :ivar display_name: The display name of the policy exemption. + :vartype display_name: str + :ivar description: The description of the policy exemption. + :vartype description: str + :ivar metadata: The policy exemption metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :vartype metadata: JSON + :ivar resource_selectors: The resource selector list to filter policies by resource properties. + :vartype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :ivar assignment_scope_validation: The option whether validate the exemption is at or under the + assignment scope. Known values are: "Default" and "DoNotValidate". + :vartype assignment_scope_validation: str or + ~azure.mgmt.resource.policy.models.AssignmentScopeValidation + """ + + _validation = { + "system_data": {"readonly": True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "policy_assignment_id": {"required": True}, + "exemption_category": {"required": True}, + } + + _attribute_map = { + "system_data": {"key": "systemData", "type": "SystemData"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "policy_assignment_id": {"key": "properties.policyAssignmentId", "type": "str"}, + "policy_definition_reference_ids": {"key": "properties.policyDefinitionReferenceIds", "type": "[str]"}, + "exemption_category": {"key": "properties.exemptionCategory", "type": "str"}, + "expires_on": {"key": "properties.expiresOn", "type": "iso-8601"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "resource_selectors": {"key": "properties.resourceSelectors", "type": "[ResourceSelector]"}, + "assignment_scope_validation": {"key": "properties.assignmentScopeValidation", "type": "str"}, + } + + def __init__( + self, + *, + policy_assignment_id: str, + exemption_category: Union[str, "_models.ExemptionCategory"], + policy_definition_reference_ids: Optional[list[str]] = None, + expires_on: Optional[datetime.datetime] = None, + display_name: Optional[str] = None, + description: Optional[str] = None, + metadata: Optional[JSON] = None, + resource_selectors: Optional[list["_models.ResourceSelector"]] = None, + assignment_scope_validation: Optional[Union[str, "_models.AssignmentScopeValidation"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword policy_assignment_id: The ID of the policy assignment that is being exempted. + Required. + :paramtype policy_assignment_id: str + :keyword policy_definition_reference_ids: The policy definition reference ID list when the + associated policy assignment is an assignment of a policy set definition. + :paramtype policy_definition_reference_ids: list[str] + :keyword exemption_category: The policy exemption category. Possible values are Waiver and + Mitigated. Required. Known values are: "Waiver" and "Mitigated". + :paramtype exemption_category: str or ~azure.mgmt.resource.policy.models.ExemptionCategory + :keyword expires_on: The expiration date and time (in UTC ISO 8601 format yyyy-MM-ddTHH:mm:ssZ) + of the policy exemption. + :paramtype expires_on: ~datetime.datetime + :keyword display_name: The display name of the policy exemption. + :paramtype display_name: str + :keyword description: The description of the policy exemption. + :paramtype description: str + :keyword metadata: The policy exemption metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :paramtype metadata: JSON + :keyword resource_selectors: The resource selector list to filter policies by resource + properties. + :paramtype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :keyword assignment_scope_validation: The option whether validate the exemption is at or under + the assignment scope. Known values are: "Default" and "DoNotValidate". + :paramtype assignment_scope_validation: str or + ~azure.mgmt.resource.policy.models.AssignmentScopeValidation + """ + super().__init__(**kwargs) + self.system_data: Optional["_models.SystemData"] = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.policy_assignment_id = policy_assignment_id + self.policy_definition_reference_ids = policy_definition_reference_ids + self.exemption_category = exemption_category + self.expires_on = expires_on + self.display_name = display_name + self.description = description + self.metadata = metadata + self.resource_selectors = resource_selectors + self.assignment_scope_validation = assignment_scope_validation + + +class PolicyExemptionListResult(_serialization.Model): + """List of policy exemptions. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: An array of policy exemptions. + :vartype value: list[~azure.mgmt.resource.policy.models.PolicyExemption] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _validation = { + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[PolicyExemption]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: Optional[list["_models.PolicyExemption"]] = None, **kwargs: Any) -> None: + """ + :keyword value: An array of policy exemptions. + :paramtype value: list[~azure.mgmt.resource.policy.models.PolicyExemption] + """ + super().__init__(**kwargs) + self.value = value + self.next_link: Optional[str] = None + + +class PolicyExemptionUpdate(_serialization.Model): + """The policy exemption for Patch request. + + :ivar resource_selectors: The resource selector list to filter policies by resource properties. + :vartype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :ivar assignment_scope_validation: The option whether validate the exemption is at or under the + assignment scope. Known values are: "Default" and "DoNotValidate". + :vartype assignment_scope_validation: str or + ~azure.mgmt.resource.policy.models.AssignmentScopeValidation + """ + + _attribute_map = { + "resource_selectors": {"key": "properties.resourceSelectors", "type": "[ResourceSelector]"}, + "assignment_scope_validation": {"key": "properties.assignmentScopeValidation", "type": "str"}, + } + + def __init__( + self, + *, + resource_selectors: Optional[list["_models.ResourceSelector"]] = None, + assignment_scope_validation: Optional[Union[str, "_models.AssignmentScopeValidation"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword resource_selectors: The resource selector list to filter policies by resource + properties. + :paramtype resource_selectors: list[~azure.mgmt.resource.policy.models.ResourceSelector] + :keyword assignment_scope_validation: The option whether validate the exemption is at or under + the assignment scope. Known values are: "Default" and "DoNotValidate". + :paramtype assignment_scope_validation: str or + ~azure.mgmt.resource.policy.models.AssignmentScopeValidation + """ + super().__init__(**kwargs) + self.resource_selectors = resource_selectors + self.assignment_scope_validation = assignment_scope_validation + + +class PolicySetDefinition(_serialization.Model): + """The policy set definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy set definition. + :vartype id: str + :ivar name: The name of the policy set definition. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/policySetDefinitions). + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar policy_type: The type of policy set definition. Possible values are NotSpecified, + BuiltIn, Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and + "Static". + :vartype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :ivar display_name: The display name of the policy set definition. + :vartype display_name: str + :ivar description: The policy set definition description. + :vartype description: str + :ivar metadata: The policy set definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :vartype metadata: JSON + :ivar parameters: The policy set definition parameters that can be used in policy definition + references. + :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :ivar policy_definitions: An array of policy definition references. + :vartype policy_definitions: list[~azure.mgmt.resource.policy.models.PolicyDefinitionReference] + :ivar policy_definition_groups: The metadata describing groups of policy definition references + within the policy set definition. + :vartype policy_definition_groups: + list[~azure.mgmt.resource.policy.models.PolicyDefinitionGroup] + :ivar version: The policy set definition version in #.#.# format. + :vartype version: str + :ivar versions: A list of available versions for this policy set definition. + :vartype versions: list[str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "policy_type": {"key": "properties.policyType", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "parameters": {"key": "properties.parameters", "type": "{ParameterDefinitionsValue}"}, + "policy_definitions": {"key": "properties.policyDefinitions", "type": "[PolicyDefinitionReference]"}, + "policy_definition_groups": {"key": "properties.policyDefinitionGroups", "type": "[PolicyDefinitionGroup]"}, + "version": {"key": "properties.version", "type": "str"}, + "versions": {"key": "properties.versions", "type": "[str]"}, + } + + def __init__( + self, + *, + policy_type: Optional[Union[str, "_models.PolicyType"]] = None, + display_name: Optional[str] = None, + description: Optional[str] = None, + metadata: Optional[JSON] = None, + parameters: Optional[dict[str, "_models.ParameterDefinitionsValue"]] = None, + policy_definitions: Optional[list["_models.PolicyDefinitionReference"]] = None, + policy_definition_groups: Optional[list["_models.PolicyDefinitionGroup"]] = None, + version: Optional[str] = None, + versions: Optional[list[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword policy_type: The type of policy set definition. Possible values are NotSpecified, + BuiltIn, Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and + "Static". + :paramtype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :keyword display_name: The display name of the policy set definition. + :paramtype display_name: str + :keyword description: The policy set definition description. + :paramtype description: str + :keyword metadata: The policy set definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :paramtype metadata: JSON + :keyword parameters: The policy set definition parameters that can be used in policy definition + references. + :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :keyword policy_definitions: An array of policy definition references. + :paramtype policy_definitions: + list[~azure.mgmt.resource.policy.models.PolicyDefinitionReference] + :keyword policy_definition_groups: The metadata describing groups of policy definition + references within the policy set definition. + :paramtype policy_definition_groups: + list[~azure.mgmt.resource.policy.models.PolicyDefinitionGroup] + :keyword version: The policy set definition version in #.#.# format. + :paramtype version: str + :keyword versions: A list of available versions for this policy set definition. + :paramtype versions: list[str] + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + self.policy_type = policy_type + self.display_name = display_name + self.description = description + self.metadata = metadata + self.parameters = parameters + self.policy_definitions = policy_definitions + self.policy_definition_groups = policy_definition_groups + self.version = version + self.versions = versions + + +class PolicySetDefinitionListResult(_serialization.Model): + """List of policy set definitions. + + :ivar value: An array of policy set definitions. + :vartype value: list[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicySetDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.PolicySetDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy set definitions. + :paramtype value: list[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PolicySetDefinitionVersion(_serialization.Model): + """The policy set definition version. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ID of the policy set definition version. + :vartype id: str + :ivar name: The name of the policy set definition version. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/policySetDefinitions/versions). + :vartype type: str + :ivar system_data: The system metadata relating to this resource. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". + :vartype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :ivar display_name: The display name of the policy set definition. + :vartype display_name: str + :ivar description: The policy set definition description. + :vartype description: str + :ivar metadata: The policy set definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :vartype metadata: JSON + :ivar parameters: The policy set definition parameters that can be used in policy definition + references. + :vartype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :ivar policy_definitions: An array of policy definition references. + :vartype policy_definitions: list[~azure.mgmt.resource.policy.models.PolicyDefinitionReference] + :ivar policy_definition_groups: The metadata describing groups of policy definition references + within the policy set definition. + :vartype policy_definition_groups: + list[~azure.mgmt.resource.policy.models.PolicyDefinitionGroup] + :ivar version: The policy set definition version in #.#.# format. + :vartype version: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "policy_type": {"key": "properties.policyType", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "parameters": {"key": "properties.parameters", "type": "{ParameterDefinitionsValue}"}, + "policy_definitions": {"key": "properties.policyDefinitions", "type": "[PolicyDefinitionReference]"}, + "policy_definition_groups": {"key": "properties.policyDefinitionGroups", "type": "[PolicyDefinitionGroup]"}, + "version": {"key": "properties.version", "type": "str"}, + } + + def __init__( + self, + *, + policy_type: Optional[Union[str, "_models.PolicyType"]] = None, + display_name: Optional[str] = None, + description: Optional[str] = None, + metadata: Optional[JSON] = None, + parameters: Optional[dict[str, "_models.ParameterDefinitionsValue"]] = None, + policy_definitions: Optional[list["_models.PolicyDefinitionReference"]] = None, + policy_definition_groups: Optional[list["_models.PolicyDefinitionGroup"]] = None, + version: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn, + Custom, and Static. Known values are: "NotSpecified", "BuiltIn", "Custom", and "Static". + :paramtype policy_type: str or ~azure.mgmt.resource.policy.models.PolicyType + :keyword display_name: The display name of the policy set definition. + :paramtype display_name: str + :keyword description: The policy set definition description. + :paramtype description: str + :keyword metadata: The policy set definition metadata. Metadata is an open ended object and is + typically a collection of key value pairs. + :paramtype metadata: JSON + :keyword parameters: The policy set definition parameters that can be used in policy definition + references. + :paramtype parameters: dict[str, ~azure.mgmt.resource.policy.models.ParameterDefinitionsValue] + :keyword policy_definitions: An array of policy definition references. + :paramtype policy_definitions: + list[~azure.mgmt.resource.policy.models.PolicyDefinitionReference] + :keyword policy_definition_groups: The metadata describing groups of policy definition + references within the policy set definition. + :paramtype policy_definition_groups: + list[~azure.mgmt.resource.policy.models.PolicyDefinitionGroup] + :keyword version: The policy set definition version in #.#.# format. + :paramtype version: str + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + self.policy_type = policy_type + self.display_name = display_name + self.description = description + self.metadata = metadata + self.parameters = parameters + self.policy_definitions = policy_definitions + self.policy_definition_groups = policy_definition_groups + self.version = version + + +class PolicySetDefinitionVersionListResult(_serialization.Model): + """List of policy set definition versions. + + :ivar value: An array of policy set definition versions. + :vartype value: list[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PolicySetDefinitionVersion]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[list["_models.PolicySetDefinitionVersion"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: An array of policy set definition versions. + :paramtype value: list[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :keyword next_link: The URL to use for getting the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PolicyVariableColumn(_serialization.Model): + """The variable column. + + All required parameters must be populated in order to send to server. + + :ivar column_name: The name of this policy variable column. Required. + :vartype column_name: str + """ + + _validation = { + "column_name": {"required": True}, + } + + _attribute_map = { + "column_name": {"key": "columnName", "type": "str"}, + } + + def __init__(self, *, column_name: str, **kwargs: Any) -> None: + """ + :keyword column_name: The name of this policy variable column. Required. + :paramtype column_name: str + """ + super().__init__(**kwargs) + self.column_name = column_name + + +class PolicyVariableValueColumnValue(_serialization.Model): + """The name value tuple for this variable value column. + + All required parameters must be populated in order to send to server. + + :ivar column_name: Column name for the variable value. Required. + :vartype column_name: str + :ivar column_value: Column value for the variable value; this can be an integer, double, + boolean, null or a string. Required. + :vartype column_value: JSON + """ + + _validation = { + "column_name": {"required": True}, + "column_value": {"required": True}, + } + + _attribute_map = { + "column_name": {"key": "columnName", "type": "str"}, + "column_value": {"key": "columnValue", "type": "object"}, + } + + def __init__(self, *, column_name: str, column_value: JSON, **kwargs: Any) -> None: + """ + :keyword column_name: Column name for the variable value. Required. + :paramtype column_name: str + :keyword column_value: Column value for the variable value; this can be an integer, double, + boolean, null or a string. Required. + :paramtype column_value: JSON + """ + super().__init__(**kwargs) + self.column_name = column_name + self.column_value = column_value + + +class ResourceSelector(_serialization.Model): + """The resource selector to filter policies by resource properties. + + :ivar name: The name of the resource selector. + :vartype name: str + :ivar selectors: The list of the selector expressions. + :vartype selectors: list[~azure.mgmt.resource.policy.models.Selector] + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "selectors": {"key": "selectors", "type": "[Selector]"}, + } + + def __init__( + self, *, name: Optional[str] = None, selectors: Optional[list["_models.Selector"]] = None, **kwargs: Any + ) -> None: + """ + :keyword name: The name of the resource selector. + :paramtype name: str + :keyword selectors: The list of the selector expressions. + :paramtype selectors: list[~azure.mgmt.resource.policy.models.Selector] + """ + super().__init__(**kwargs) + self.name = name + self.selectors = selectors + + +class ResourceTypeAliases(_serialization.Model): + """The resource type aliases definition. + + :ivar resource_type: The resource type name. + :vartype resource_type: str + :ivar aliases: The aliases for property names. + :vartype aliases: list[~azure.mgmt.resource.policy.models.Alias] + """ + + _attribute_map = { + "resource_type": {"key": "resourceType", "type": "str"}, + "aliases": {"key": "aliases", "type": "[Alias]"}, + } + + def __init__( + self, *, resource_type: Optional[str] = None, aliases: Optional[list["_models.Alias"]] = None, **kwargs: Any + ) -> None: + """ + :keyword resource_type: The resource type name. + :paramtype resource_type: str + :keyword aliases: The aliases for property names. + :paramtype aliases: list[~azure.mgmt.resource.policy.models.Alias] + """ + super().__init__(**kwargs) + self.resource_type = resource_type + self.aliases = aliases + + +class Selector(_serialization.Model): + """The selector expression. + + :ivar kind: The selector kind. Known values are: "resourceLocation", "resourceType", + "resourceWithoutLocation", and "policyDefinitionReferenceId". + :vartype kind: str or ~azure.mgmt.resource.policy.models.SelectorKind + :ivar in_property: The list of values to filter in. + :vartype in_property: list[str] + :ivar not_in: The list of values to filter out. + :vartype not_in: list[str] + """ + + _attribute_map = { + "kind": {"key": "kind", "type": "str"}, + "in_property": {"key": "in", "type": "[str]"}, + "not_in": {"key": "notIn", "type": "[str]"}, + } + + def __init__( + self, + *, + kind: Optional[Union[str, "_models.SelectorKind"]] = None, + in_property: Optional[list[str]] = None, + not_in: Optional[list[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword kind: The selector kind. Known values are: "resourceLocation", "resourceType", + "resourceWithoutLocation", and "policyDefinitionReferenceId". + :paramtype kind: str or ~azure.mgmt.resource.policy.models.SelectorKind + :keyword in_property: The list of values to filter in. + :paramtype in_property: list[str] + :keyword not_in: The list of values to filter out. + :paramtype not_in: list[str] + """ + super().__init__(**kwargs) + self.kind = kind + self.in_property = in_property + self.not_in = not_in + + +class SystemData(_serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: str or ~azure.mgmt.resource.policy.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or ~azure.mgmt.resource.policy.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _attribute_map = { + "created_by": {"key": "createdBy", "type": "str"}, + "created_by_type": {"key": "createdByType", "type": "str"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, + "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, + } + + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword created_by: The identity that created the resource. + :paramtype created_by: str + :keyword created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :paramtype created_by_type: str or ~azure.mgmt.resource.policy.models.CreatedByType + :keyword created_at: The timestamp of resource creation (UTC). + :paramtype created_at: ~datetime.datetime + :keyword last_modified_by: The identity that last modified the resource. + :paramtype last_modified_by: str + :keyword last_modified_by_type: The type of identity that last modified the resource. Known + values are: "User", "Application", "ManagedIdentity", and "Key". + :paramtype last_modified_by_type: str or ~azure.mgmt.resource.policy.models.CreatedByType + :keyword last_modified_at: The timestamp of resource last modification (UTC). + :paramtype last_modified_at: ~datetime.datetime + """ + super().__init__(**kwargs) + self.created_by = created_by + self.created_by_type = created_by_type + self.created_at = created_at + self.last_modified_by = last_modified_by + self.last_modified_by_type = last_modified_by_type + self.last_modified_at = last_modified_at + + +class UserAssignedIdentitiesValue(_serialization.Model): + """UserAssignedIdentitiesValue. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal id of user assigned identity. + :vartype principal_id: str + :ivar client_id: The client id of user assigned identity. + :vartype client_id: str + """ + + _validation = { + "principal_id": {"readonly": True}, + "client_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.principal_id: Optional[str] = None + self.client_id: Optional[str] = None + + +class Variable(_serialization.Model): + """The variable. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar id: The ID of the variable. + :vartype id: str + :ivar name: The name of the variable. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/variables). + :vartype type: str + :ivar columns: Variable column definitions. Required. + :vartype columns: list[~azure.mgmt.resource.policy.models.PolicyVariableColumn] + """ + + _validation = { + "system_data": {"readonly": True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "columns": {"required": True}, + } + + _attribute_map = { + "system_data": {"key": "systemData", "type": "SystemData"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "columns": {"key": "properties.columns", "type": "[PolicyVariableColumn]"}, + } + + def __init__(self, *, columns: list["_models.PolicyVariableColumn"], **kwargs: Any) -> None: + """ + :keyword columns: Variable column definitions. Required. + :paramtype columns: list[~azure.mgmt.resource.policy.models.PolicyVariableColumn] + """ + super().__init__(**kwargs) + self.system_data: Optional["_models.SystemData"] = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.columns = columns + + +class VariableListResult(_serialization.Model): + """List of variables. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: An array of variables. + :vartype value: list[~azure.mgmt.resource.policy.models.Variable] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _validation = { + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Variable]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: Optional[list["_models.Variable"]] = None, **kwargs: Any) -> None: + """ + :keyword value: An array of variables. + :paramtype value: list[~azure.mgmt.resource.policy.models.Variable] + """ + super().__init__(**kwargs) + self.value = value + self.next_link: Optional[str] = None + + +class VariableValue(_serialization.Model): + """The variable value. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.resource.policy.models.SystemData + :ivar id: The ID of the variable. + :vartype id: str + :ivar name: The name of the variable. + :vartype name: str + :ivar type: The type of the resource (Microsoft.Authorization/variables/values). + :vartype type: str + :ivar values: Variable value column value array. Required. + :vartype values: list[~azure.mgmt.resource.policy.models.PolicyVariableValueColumnValue] + """ + + _validation = { + "system_data": {"readonly": True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "values": {"required": True}, + } + + _attribute_map = { + "system_data": {"key": "systemData", "type": "SystemData"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "values": {"key": "properties.values", "type": "[PolicyVariableValueColumnValue]"}, + } + + def __init__(self, *, values: list["_models.PolicyVariableValueColumnValue"], **kwargs: Any) -> None: + """ + :keyword values: Variable value column value array. Required. + :paramtype values: list[~azure.mgmt.resource.policy.models.PolicyVariableValueColumnValue] + """ + super().__init__(**kwargs) + self.system_data: Optional["_models.SystemData"] = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.values = values + + +class VariableValueListResult(_serialization.Model): + """List of variable values. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: An array of variable values. + :vartype value: list[~azure.mgmt.resource.policy.models.VariableValue] + :ivar next_link: The URL to use for getting the next set of results. + :vartype next_link: str + """ + + _validation = { + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[VariableValue]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: Optional[list["_models.VariableValue"]] = None, **kwargs: Any) -> None: + """ + :keyword value: An array of variable values. + :paramtype value: list[~azure.mgmt.resource.policy.models.VariableValue] + """ + super().__init__(**kwargs) + self.value = value + self.next_link: Optional[str] = None diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_patch.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_policy_client_enums.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_policy_client_enums.py new file mode 100644 index 000000000000..72647fa2a336 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/models/_policy_client_enums.py @@ -0,0 +1,153 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AliasPathAttributes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The attributes of the token that the alias path is referring to.""" + + NONE = "None" + """The token that the alias path is referring to has no attributes.""" + MODIFIABLE = "Modifiable" + """The token that the alias path is referring to is modifiable by policies with 'modify' effect.""" + + +class AliasPathTokenType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the token that the alias path is referring to.""" + + NOT_SPECIFIED = "NotSpecified" + """The token type is not specified.""" + ANY = "Any" + """The token type can be anything.""" + STRING = "String" + """The token type is string.""" + OBJECT = "Object" + """The token type is object.""" + ARRAY = "Array" + """The token type is array.""" + INTEGER = "Integer" + """The token type is integer.""" + NUMBER = "Number" + """The token type is number.""" + BOOLEAN = "Boolean" + """The token type is boolean.""" + + +class AliasPatternType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of alias pattern.""" + + NOT_SPECIFIED = "NotSpecified" + """NotSpecified is not allowed.""" + EXTRACT = "Extract" + """Extract is the only allowed value.""" + + +class AliasType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the alias.""" + + NOT_SPECIFIED = "NotSpecified" + """Alias type is unknown (same as not providing alias type).""" + PLAIN_TEXT = "PlainText" + """Alias value is not secret.""" + MASK = "Mask" + """Alias value is secret.""" + + +class AssignmentScopeValidation(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The option whether validate the exemption is at or under the assignment scope.""" + + DEFAULT = "Default" + """This option will validate the exemption is at or under the assignment scope.""" + DO_NOT_VALIDATE = "DoNotValidate" + """This option will bypass the validation the exemption scope is at or under the policy assignment + scope.""" + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + + +class EnforcementMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The policy assignment enforcement mode. Possible values are Default and DoNotEnforce.""" + + DEFAULT = "Default" + """The policy effect is enforced during resource creation or update.""" + DO_NOT_ENFORCE = "DoNotEnforce" + """The policy effect is not enforced during resource creation or update.""" + + +class ExemptionCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The policy exemption category. Possible values are Waiver and Mitigated.""" + + WAIVER = "Waiver" + """This category of exemptions usually means the scope is not applicable for the policy.""" + MITIGATED = "Mitigated" + """This category of exemptions usually means the mitigation actions have been applied to the + scope.""" + + +class OverrideKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The override kind.""" + + POLICY_EFFECT = "policyEffect" + """It will override the policy effect type.""" + + +class ParameterType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The data type of the parameter.""" + + STRING = "String" + ARRAY = "Array" + OBJECT = "Object" + BOOLEAN = "Boolean" + INTEGER = "Integer" + FLOAT = "Float" + DATE_TIME = "DateTime" + + +class PolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static.""" + + NOT_SPECIFIED = "NotSpecified" + BUILT_IN = "BuiltIn" + CUSTOM = "Custom" + STATIC = "Static" + + +class ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The identity type. This is the only required field when adding a system or user assigned + identity to a resource. + """ + + SYSTEM_ASSIGNED = "SystemAssigned" + """Indicates that a system assigned identity is associated with the resource.""" + USER_ASSIGNED = "UserAssigned" + """Indicates that a system assigned identity is associated with the resource.""" + NONE = "None" + """Indicates that no identity is associated with the resource or that the existing identity should + be removed.""" + + +class SelectorKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The selector kind.""" + + RESOURCE_LOCATION = "resourceLocation" + """The selector kind to filter policies by the resource location.""" + RESOURCE_TYPE = "resourceType" + """The selector kind to filter policies by the resource type.""" + RESOURCE_WITHOUT_LOCATION = "resourceWithoutLocation" + """The selector kind to filter policies by the resource without location.""" + POLICY_DEFINITION_REFERENCE_ID = "policyDefinitionReferenceId" + """The selector kind to filter policies by the policy definition reference ID.""" diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/__init__.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/__init__.py new file mode 100644 index 000000000000..f302859689f6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/__init__.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import DataPolicyManifestsOperations # type: ignore +from ._operations import PolicyDefinitionsOperations # type: ignore +from ._operations import PolicyDefinitionVersionsOperations # type: ignore +from ._operations import PolicySetDefinitionsOperations # type: ignore +from ._operations import PolicySetDefinitionVersionsOperations # type: ignore +from ._operations import PolicyAssignmentsOperations # type: ignore +from ._operations import PolicyExemptionsOperations # type: ignore +from ._operations import VariablesOperations # type: ignore +from ._operations import VariableValuesOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DataPolicyManifestsOperations", + "PolicyDefinitionsOperations", + "PolicyDefinitionVersionsOperations", + "PolicySetDefinitionsOperations", + "PolicySetDefinitionVersionsOperations", + "PolicyAssignmentsOperations", + "PolicyExemptionsOperations", + "VariablesOperations", + "VariableValuesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_operations.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_operations.py new file mode 100644 index 000000000000..29e62121956e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_operations.py @@ -0,0 +1,10155 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import PolicyClientConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_data_policy_manifests_get_by_policy_mode_request( # pylint: disable=name-too-long + policy_mode: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/dataPolicyManifests/{policyMode}") + path_format_arguments = { + "policyMode": _SERIALIZER.url("policy_mode", policy_mode, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_data_policy_manifests_list_request(*, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/dataPolicyManifests") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_create_or_update_request( # pylint: disable=name-too-long + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_delete_request( + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_get_request( + policy_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_get_built_in_request( # pylint: disable=name-too-long + policy_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}") + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_create_or_update_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, policy_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_delete_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, policy_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_get_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, policy_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_list_request( + subscription_id: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_list_built_in_request( # pylint: disable=name-too-long + *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/policyDefinitions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definitions_list_by_management_group_request( # pylint: disable=name-too-long + management_group_id: str, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_list_all_builtins_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/listPolicyDefinitionVersions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_list_all_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/listPolicyDefinitionVersions", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_list_all_request( # pylint: disable=name-too-long + subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/listPolicyDefinitionVersions" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_create_or_update_request( # pylint: disable=name-too-long + policy_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_delete_request( # pylint: disable=name-too-long + policy_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_get_request( # pylint: disable=name-too-long + policy_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_get_built_in_request( # pylint: disable=name-too-long + policy_definition_name: str, policy_definition_version: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_create_or_update_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_delete_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_get_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_list_request( # pylint: disable=name-too-long + policy_definition_name: str, subscription_id: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_list_built_in_request( # pylint: disable=name-too-long + policy_definition_name: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions" + ) + path_format_arguments = { + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_definition_versions_list_by_management_group_request( # pylint: disable=name-too-long + management_group_name: str, policy_definition_name: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policyDefinitionName": _SERIALIZER.url( + "policy_definition_name", policy_definition_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_create_or_update_request( # pylint: disable=name-too-long + policy_set_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_delete_request( # pylint: disable=name-too-long + policy_set_definition_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_get_request( + policy_set_definition_name: str, subscription_id: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_get_built_in_request( # pylint: disable=name-too-long + policy_set_definition_name: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}" + ) + path_format_arguments = { + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_list_request( # pylint: disable=name-too-long + subscription_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_list_built_in_request( # pylint: disable=name-too-long + *, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/policySetDefinitions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_create_or_update_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, policy_set_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_delete_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, policy_set_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_get_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, policy_set_definition_name: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definitions_list_by_management_group_request( # pylint: disable=name-too-long + management_group_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_list_all_builtins_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Authorization/listPolicySetDefinitionVersions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_list_all_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/listPolicySetDefinitionVersions", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_list_all_request( # pylint: disable=name-too-long + subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/listPolicySetDefinitionVersions", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_create_or_update_request( # pylint: disable=name-too-long + policy_set_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_delete_request( # pylint: disable=name-too-long + policy_set_definition_name: str, policy_definition_version: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_get_request( # pylint: disable=name-too-long + policy_set_definition_name: str, + policy_definition_version: str, + subscription_id: str, + *, + expand: Optional[str] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_get_built_in_request( # pylint: disable=name-too-long + policy_set_definition_name: str, policy_definition_version: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_list_request( # pylint: disable=name-too-long + policy_set_definition_name: str, + subscription_id: str, + *, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_list_built_in_request( # pylint: disable=name-too-long + policy_set_definition_name: str, *, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions" + ) + path_format_arguments = { + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_create_or_update_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_delete_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_get_at_management_group_request( # pylint: disable=name-too-long + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + *, + expand: Optional[str] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions/{policyDefinitionVersion}", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + "policyDefinitionVersion": _SERIALIZER.url( + "policy_definition_version", policy_definition_version, "str", pattern=r"^\d+\.\d+\.\d+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_set_definition_versions_list_by_management_group_request( # pylint: disable=name-too-long + management_group_name: str, + policy_set_definition_name: str, + *, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}/versions", + ) + path_format_arguments = { + "managementGroupName": _SERIALIZER.url( + "management_group_name", management_group_name, "str", max_length=90, min_length=1 + ), + "policySetDefinitionName": _SERIALIZER.url( + "policy_set_definition_name", + policy_set_definition_name, + "str", + pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_delete_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url( + "policy_assignment_name", policy_assignment_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_create_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url( + "policy_assignment_name", policy_assignment_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_get_request( + scope: str, policy_assignment_name: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url( + "policy_assignment_name", policy_assignment_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_update_request(scope: str, policy_assignment_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyAssignmentName": _SERIALIZER.url( + "policy_assignment_name", policy_assignment_name, "str", pattern=r"^[^<>*%&:\?.+/]*[^<>*%&:\?.+/ ]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_for_resource_group_request( # pylint: disable=name-too-long + resource_group_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_for_resource_request( # pylint: disable=name-too-long + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", pattern=r"^.+$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_for_management_group_request( # pylint: disable=name-too-long + management_group_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyAssignments", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_list_request( + subscription_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_delete_by_id_request( # pylint: disable=name-too-long + policy_assignment_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_create_by_id_request( # pylint: disable=name-too-long + policy_assignment_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_get_by_id_request( # pylint: disable=name-too-long + policy_assignment_id: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_assignments_update_by_id_request( # pylint: disable=name-too-long + policy_assignment_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{policyAssignmentId}") + path_format_arguments = { + "policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_delete_request(scope: str, policy_exemption_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyExemptionName": _SERIALIZER.url("policy_exemption_name", policy_exemption_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_create_or_update_request( # pylint: disable=name-too-long + scope: str, policy_exemption_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyExemptionName": _SERIALIZER.url("policy_exemption_name", policy_exemption_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_get_request(scope: str, policy_exemption_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyExemptionName": _SERIALIZER.url("policy_exemption_name", policy_exemption_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_update_request(scope: str, policy_exemption_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "policyExemptionName": _SERIALIZER.url("policy_exemption_name", policy_exemption_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_list_request( + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyExemptions" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_list_for_resource_group_request( # pylint: disable=name-too-long + resource_group_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyExemptions", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_list_for_resource_request( # pylint: disable=name-too-long + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + subscription_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyExemptions", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$" + ), + "resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, "str"), + "parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, "str", skip_quote=True), + "resourceType": _SERIALIZER.url("resource_type", resource_type, "str", skip_quote=True), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_policy_exemptions_list_for_management_group_request( # pylint: disable=name-too-long + management_group_id: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyExemptions", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str", skip_quote=True) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_delete_request(variable_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_create_or_update_request(variable_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_get_request(variable_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_delete_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_create_or_update_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_get_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variables_list_for_management_group_request( # pylint: disable=name-too-long + management_group_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_delete_request( + variable_name: str, variable_value_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_create_or_update_request( # pylint: disable=name-too-long + variable_name: str, variable_value_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_get_request( + variable_name: str, variable_value_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_list_request(variable_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/variables/{variableName}/values", + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_list_for_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}/values", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_delete_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_create_or_update_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_variable_values_get_at_management_group_request( # pylint: disable=name-too-long + management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/variables/{variableName}/values/{variableValueName}", + ) + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "variableName": _SERIALIZER.url("variable_name", variable_name, "str"), + "variableValueName": _SERIALIZER.url("variable_value_name", variable_value_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DataPolicyManifestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`data_policy_manifests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get_by_policy_mode(self, policy_mode: str, **kwargs: Any) -> _models.DataPolicyManifest: + """Retrieves a data policy manifest. + + This operation retrieves the data policy manifest with the given policy mode. + + :param policy_mode: The policy mode of the data policy manifest to get. Required. + :type policy_mode: str + :return: DataPolicyManifest or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.DataPolicyManifest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) + cls: ClsType[_models.DataPolicyManifest] = kwargs.pop("cls", None) + + _request = build_data_policy_manifests_get_by_policy_mode_request( + policy_mode=policy_mode, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DataPolicyManifest", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models.DataPolicyManifest"]: + """Retrieves data policy manifests. + + This operation retrieves a list of all the data policy manifests that match the optional given + $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not + provided, the unfiltered list includes all data policy manifests for data resource types. If + $filter=namespace is provided, the returned list only includes all data policy manifests that + have a namespace matching the provided value. + + :param filter: The filter to apply on the operation. Valid values for $filter are: "namespace + eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq + '{value}' is provided, the returned list only includes all data policy manifests that have a + namespace matching the provided value. Default value is None. + :type filter: str + :return: An iterator like instance of either DataPolicyManifest or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.DataPolicyManifest] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-09-01")) + cls: ClsType[_models.DataPolicyManifestListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_data_policy_manifests_list_request( + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DataPolicyManifestListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class PolicyDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`policy_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + policy_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, policy_definition_name: str, parameters: Union[_models.PolicyDefinition, IO[bytes]], **kwargs: Any + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition or IO[bytes] + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + _request = build_policy_definitions_create_or_update_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy definition in a subscription. + + This operation deletes the policy definition in the given subscription with the given name. + + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definitions_delete_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Retrieves a policy definition in a subscription. + + This operation retrieves the policy definition in the given subscription with the given name. + + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + _request = build_policy_definitions_get_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_built_in(self, policy_definition_name: str, **kwargs: Any) -> _models.PolicyDefinition: + """Retrieves a built-in policy definition. + + This operation retrieves the built-in policy definition with the given name. + + :param policy_definition_name: The name of the built-in policy definition to get. Required. + :type policy_definition_name: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + _request = build_policy_definitions_get_built_in_request( + policy_definition_name=policy_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + policy_definition_name: str, + parameters: _models.PolicyDefinition, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a management group. + + This operation creates or updates a policy definition in the given management group with the + given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + policy_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a management group. + + This operation creates or updates a policy definition in the given management group with the + given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, + management_group_id: str, + policy_definition_name: str, + parameters: Union[_models.PolicyDefinition, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyDefinition: + """Creates or updates a policy definition in a management group. + + This operation creates or updates a policy definition in the given management group with the + given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to create. Required. + :type policy_definition_name: str + :param parameters: The policy definition properties. Is either a PolicyDefinition type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinition or IO[bytes] + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinition") + + _request = build_policy_definitions_create_or_update_at_management_group_request( + management_group_id=management_group_id, + policy_definition_name=policy_definition_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, management_group_id: str, policy_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy definition in a management group. + + This operation deletes the policy definition in the given management group with the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to delete. Required. + :type policy_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definitions_delete_at_management_group_request( + management_group_id=management_group_id, + policy_definition_name=policy_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_at_management_group( + self, management_group_id: str, policy_definition_name: str, **kwargs: Any + ) -> _models.PolicyDefinition: + """Retrieve a policy definition in a management group. + + This operation retrieves the policy definition in the given management group with the given + name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_definition_name: The name of the policy definition to get. Required. + :type policy_definition_name: str + :return: PolicyDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinition] = kwargs.pop("cls", None) + + _request = build_policy_definitions_get_at_management_group_request( + management_group_id=management_group_id, + policy_definition_name=policy_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyDefinition"]: + """Retrieves policy definitions in a subscription. + + This operation retrieves a list of all the policy definitions in a given subscription that + match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType + -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list + includes all policy definitions associated with the subscription, including those that apply + directly or from management groups that contain the given subscription. If + $filter=atExactScope() is provided, the returned list only includes all policy definitions that + at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list + only includes all policy definitions whose type match the {value}. Possible policyType values + are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, + the returned list only includes all policy definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy definitions whose type match + the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy + definitions whose category match the {value}. Default value is None. + :type filter: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definitions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyDefinition"]: + """Retrieve built-in policy definitions. + + This operation retrieves a list of all the built-in policy definitions that match the optional + given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes + all built-in policy definitions whose type match the {value}. Possible policyType values are + NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the + returned list only includes all built-in policy definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy definitions whose type match + the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy + definitions whose category match the {value}. Default value is None. + :type filter: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definitions_list_built_in_request( + filter=filter, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_management_group( + self, management_group_id: str, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyDefinition"]: + """Retrieve policy definitions in a management group. + + This operation retrieves a list of all the policy definitions in a given management group that + match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType + -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list + includes all policy definitions associated with the management group, including those that + apply directly or from management groups that contain the given management group. If + $filter=atExactScope() is provided, the returned list only includes all policy definitions that + at the given management group. If $filter='policyType -eq {value}' is provided, the returned + list only includes all policy definitions whose type match the {value}. Possible policyType + values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is + provided, the returned list only includes all policy definitions whose category match the + {value}. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy definitions whose type match + the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy + definitions whose category match the {value}. Default value is None. + :type filter: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definitions_list_by_management_group_request( + management_group_id=management_group_id, + filter=filter, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class PolicyDefinitionVersionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`policy_definition_versions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_all_builtins(self, **kwargs: Any) -> _models.PolicyDefinitionVersionListResult: + """Lists all built-in policy definition versions. + + This operation lists all the built-in policy definition versions for all built-in policy + definitions. + + :return: PolicyDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_list_all_builtins_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_all_at_management_group( + self, management_group_name: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersionListResult: + """Lists all policy definition versions at management group scope. + + This operation lists all the policy definition versions for all policy definitions at the + management group scope. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :return: PolicyDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_list_all_at_management_group_request( + management_group_name=management_group_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_all(self, **kwargs: Any) -> _models.PolicyDefinitionVersionListResult: + """Lists all policy definition versions within a subscription. + + This operation lists all the policy definition versions for all policy definitions within a + subscription. + + :return: PolicyDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + policy_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicyDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + policy_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + policy_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicyDefinitionVersion, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition in a subscription. + + This operation creates or updates a policy definition in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Is either a PolicyDefinitionVersion type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion or IO[bytes] + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinitionVersion") + + _request = build_policy_definition_versions_create_or_update_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> None: + """Deletes a policy definition version in a subscription. + + This operation deletes the policy definition version in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_delete_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get( + self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Retrieves a policy definition version in a subscription. + + This operation retrieves the policy definition version in the given subscription with the given + name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_get_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_built_in( + self, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Retrieves a built-in policy definition version. + + This operation retrieves the built-in policy definition version with the given name. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_get_built_in_request( + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update_at_management_group( + self, + management_group_name: str, + policy_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicyDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition version in a management group. + + This operation creates or updates a policy definition version in the given management group + with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + management_group_name: str, + policy_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition version in a management group. + + This operation creates or updates a policy definition version in the given management group + with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, + management_group_name: str, + policy_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicyDefinitionVersion, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyDefinitionVersion: + """Creates or updates a policy definition version in a management group. + + This operation creates or updates a policy definition version in the given management group + with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy definition properties. Is either a PolicyDefinitionVersion type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion or IO[bytes] + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyDefinitionVersion") + + _request = build_policy_definition_versions_create_or_update_at_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> None: + """Deletes a policy definition in a management group. + + This operation deletes the policy definition in the given management group with the given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_delete_at_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_at_management_group( + self, management_group_name: str, policy_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> _models.PolicyDefinitionVersion: + """Retrieve a policy definition version in a management group. + + This operation retrieves the policy definition version in the given management group with the + given name. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param policy_definition_version: The policy definition version. The format is x.y.z where x + is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: PolicyDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_definition_versions_get_at_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyDefinitionVersion"]: + """Retrieves policy definition versions for a given policy definition in a subscription. + + This operation retrieves a list of all the policy definition versions for the given policy + definition. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definition_versions_list_request( + policy_definition_name=policy_definition_name, + subscription_id=self._config.subscription_id, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyDefinitionVersion"]: + """Retrieve built-in policy definition versions. + + This operation retrieves a list of all the built-in policy definition versions for the given + policy definition. + + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definition_versions_list_built_in_request( + policy_definition_name=policy_definition_name, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_management_group( + self, management_group_name: str, policy_definition_name: str, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyDefinitionVersion"]: + """Retrieve policy definition versions in a management group policy definition. + + This operation retrieves a list of all the policy definition versions for the given policy + definition in the given management group. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_definition_name: The name of the policy definition. Required. + :type policy_definition_name: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_definition_versions_list_by_management_group_request( + management_group_name=management_group_name, + policy_definition_name=policy_definition_name, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class PolicySetDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`policy_set_definitions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create_or_update( + self, + policy_set_definition_name: str, + parameters: _models.PolicySetDefinition, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given subscription with the + given name. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + policy_set_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given subscription with the + given name. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, policy_set_definition_name: str, parameters: Union[_models.PolicySetDefinition, IO[bytes]], **kwargs: Any + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given subscription with the + given name. + + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinition type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition or IO[bytes] + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinition") + + _request = build_policy_set_definitions_create_or_update_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, policy_set_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition. + + This operation deletes the policy set definition in the given subscription with the given name. + + :param policy_set_definition_name: The name of the policy set definition to delete. Required. + :type policy_set_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_delete_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get( + self, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicySetDefinition: + """Retrieves a policy set definition. + + This operation retrieves the policy set definition in the given subscription with the given + name. + + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_get_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_built_in( + self, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicySetDefinition: + """Retrieves a built in policy set definition. + + This operation retrieves the built-in policy set definition with the given name. + + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_get_built_in_request( + policy_set_definition_name=policy_set_definition_name, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicySetDefinition"]: + """Retrieves the policy set definitions for a subscription. + + This operation retrieves a list of all the policy set definitions in a given subscription that + match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType + -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list + includes all policy set definitions associated with the subscription, including those that + apply directly or from management groups that contain the given subscription. If + $filter=atExactScope() is provided, the returned list only includes all policy set definitions + that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned + list only includes all policy set definitions whose type match the {value}. Possible policyType + values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the + returned list only includes all policy set definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy set definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy set definitions whose type + match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy set + definitions whose category match the {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definitions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicySetDefinition"]: + """Retrieves built-in policy set definitions. + + This operation retrieves a list of all the built-in policy set definitions that match the + optional given $filter. If $filter='category -eq {value}' is provided, the returned list only + includes all built-in policy set definitions whose category match the {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy set definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy set definitions whose type + match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy set + definitions whose category match the {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definitions_list_built_in_request( + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + policy_set_definition_name: str, + parameters: _models.PolicySetDefinition, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given management group with + the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + policy_set_definition_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given management group with + the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, + management_group_id: str, + policy_set_definition_name: str, + parameters: Union[_models.PolicySetDefinition, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicySetDefinition: + """Creates or updates a policy set definition. + + This operation creates or updates a policy set definition in the given management group with + the given name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to create. Required. + :type policy_set_definition_name: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinition type + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinition or IO[bytes] + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinition") + + _request = build_policy_set_definitions_create_or_update_at_management_group_request( + management_group_id=management_group_id, + policy_set_definition_name=policy_set_definition_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, management_group_id: str, policy_set_definition_name: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition. + + This operation deletes the policy set definition in the given management group with the given + name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to delete. Required. + :type policy_set_definition_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_delete_at_management_group_request( + management_group_id=management_group_id, + policy_set_definition_name=policy_set_definition_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_at_management_group( + self, management_group_id: str, policy_set_definition_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicySetDefinition: + """Retrieves a policy set definition. + + This operation retrieves the policy set definition in the given management group with the given + name. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param policy_set_definition_name: The name of the policy set definition to get. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinition or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinition + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinition] = kwargs.pop("cls", None) + + _request = build_policy_set_definitions_get_at_management_group_request( + management_group_id=management_group_id, + policy_set_definition_name=policy_set_definition_name, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinition", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_management_group( + self, + management_group_id: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> ItemPaged["_models.PolicySetDefinition"]: + """Retrieves all policy set definitions in management group. + + This operation retrieves a list of all the policy set definitions in a given management group + that match the optional given $filter. Valid values for $filter are: 'atExactScope()', + 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered + list includes all policy set definitions associated with the management group, including those + that apply directly or from management groups that contain the given management group. If + $filter=atExactScope() is provided, the returned list only includes all policy set definitions + that at the given management group. If $filter='policyType -eq {value}' is provided, the + returned list only includes all policy set definitions whose type match the {value}. Possible + policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is + provided, the returned list only includes all policy set definitions whose category match the + {value}. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: + 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list + only includes all policy set definitions that at the given scope. If $filter='policyType -eq + {value}' is provided, the returned list only includes all policy set definitions whose type + match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If + $filter='category -eq {value}' is provided, the returned list only includes all policy set + definitions whose category match the {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinition or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinition] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definitions_list_by_management_group_request( + management_group_id=management_group_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class PolicySetDefinitionVersionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`policy_set_definition_versions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_all_builtins(self, **kwargs: Any) -> _models.PolicySetDefinitionVersionListResult: + """Lists all built-in policy set definition versions. + + This operation lists all the built-in policy set definition versions for all built-in policy + set definitions. + + :return: PolicySetDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_list_all_builtins_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_all_at_management_group( + self, management_group_name: str, **kwargs: Any + ) -> _models.PolicySetDefinitionVersionListResult: + """Lists all policy set definition versions at management group scope. + + This operation lists all the policy set definition versions for all policy set definitions at + the management group scope. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :return: PolicySetDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_list_all_at_management_group_request( + management_group_name=management_group_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_all(self, **kwargs: Any) -> _models.PolicySetDefinitionVersionListResult: + """Lists all policy set definition versions within a subscription. + + This operation lists all the policy set definition versions for all policy set definitions + within a subscription. + + :return: PolicySetDefinitionVersionListResult or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersionListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_list_all_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicySetDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given subscription + with the given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given subscription + with the given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicySetDefinitionVersion, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given subscription + with the given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition properties. Is either a PolicySetDefinitionVersion + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion or IO[bytes] + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinitionVersion") + + _request = build_policy_set_definition_versions_create_or_update_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition version. + + This operation deletes the policy set definition version in the given subscription with the + given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_delete_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get( + self, + policy_set_definition_name: str, + policy_definition_version: str, + expand: Optional[str] = None, + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Retrieves a policy set definition version. + + This operation retrieves the policy set definition version in the given subscription with the + given name and version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_get_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + subscription_id=self._config.subscription_id, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_built_in( + self, + policy_set_definition_name: str, + policy_definition_version: str, + expand: Optional[str] = None, + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Retrieves a built in policy set definition version. + + This operation retrieves the built-in policy set definition version with the given name and + version. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_get_built_in_request( + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, policy_set_definition_name: str, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicySetDefinitionVersion"]: + """Retrieves the policy set definition versions for a given policy set definition in a + subscription. + + This operation retrieves a list of all the policy set definition versions for the given policy + set definition. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definition_versions_list_request( + policy_set_definition_name=policy_set_definition_name, + subscription_id=self._config.subscription_id, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_built_in( + self, policy_set_definition_name: str, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicySetDefinitionVersion"]: + """Retrieves built-in policy set definition versions. + + This operation retrieves a list of all the built-in policy set definition versions for the + given built-in policy set definition. + + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definition_versions_list_built_in_request( + policy_set_definition_name=policy_set_definition_name, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create_or_update_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: _models.PolicySetDefinitionVersion, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given management group + with the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition version properties. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given management group + with the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition version properties. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + parameters: Union[_models.PolicySetDefinitionVersion, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Creates or updates a policy set definition version. + + This operation creates or updates a policy set definition version in the given management group + with the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param parameters: The policy set definition version properties. Is either a + PolicySetDefinitionVersion type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion or IO[bytes] + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicySetDefinitionVersion") + + _request = build_policy_set_definition_versions_create_or_update_at_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, management_group_name: str, policy_set_definition_name: str, policy_definition_version: str, **kwargs: Any + ) -> None: + """Deletes a policy set definition version. + + This operation deletes the policy set definition version in the given management group with the + given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_delete_at_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def get_at_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + policy_definition_version: str, + expand: Optional[str] = None, + **kwargs: Any, + ) -> _models.PolicySetDefinitionVersion: + """Retrieves a policy set definition version. + + This operation retrieves the policy set definition version in the given management group with + the given name and version. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param policy_definition_version: The policy set definition version. The format is x.y.z where + x is the major version number, y is the minor version number, and z is the patch number. + Required. + :type policy_definition_version: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicySetDefinitionVersion or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersion] = kwargs.pop("cls", None) + + _request = build_policy_set_definition_versions_get_at_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + policy_definition_version=policy_definition_version, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicySetDefinitionVersion", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_by_management_group( + self, + management_group_name: str, + policy_set_definition_name: str, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> ItemPaged["_models.PolicySetDefinitionVersion"]: + """Retrieves all policy set definition versions for a given policy set definition in a management + group. + + This operation retrieves a list of all the policy set definition versions for the given policy + set definition in a given management group. + + :param management_group_name: The name of the management group. The name is case insensitive. + Required. + :type management_group_name: str + :param policy_set_definition_name: The name of the policy set definition. Required. + :type policy_set_definition_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicySetDefinitionVersion or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicySetDefinitionVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicySetDefinitionVersionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_set_definition_versions_list_by_management_group_request( + management_group_name=management_group_name, + policy_set_definition_name=policy_set_definition_name, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicySetDefinitionVersionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class PolicyAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`policy_assignments` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete(self, scope: str, policy_assignment_name: str, **kwargs: Any) -> Optional[_models.PolicyAssignment]: + """Deletes a policy assignment. + + This operation deletes a policy assignment, given its name and the scope it was created in. The + scope of a policy assignment is the part of its ID preceding + '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to delete. Required. + :type policy_assignment_name: str + :return: PolicyAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) + + _request = build_policy_assignments_delete_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates a policy assignment with the given scope and name. Policy + assignments apply to all resources contained within their scope. For example, when you assign a + policy at resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + scope: str, + policy_assignment_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates a policy assignment with the given scope and name. Policy + assignments apply to all resources contained within their scope. For example, when you assign a + policy at resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, + scope: str, + policy_assignment_name: str, + parameters: Union[_models.PolicyAssignment, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates a policy assignment with the given scope and name. Policy + assignments apply to all resources contained within their scope. For example, when you assign a + policy at resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for the policy assignment. Is either a PolicyAssignment type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + _request = build_policy_assignments_create_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get( + self, scope: str, policy_assignment_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicyAssignment: + """Retrieves a policy assignment. + + This operation retrieves a single policy assignment, given its name and the scope it was + created at. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment to get. Required. + :type policy_assignment_name: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + _request = build_policy_assignments_get_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + scope: str, + policy_assignment_name: str, + parameters: _models.PolicyAssignmentUpdate, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates a policy assignment with the given scope and name. Policy assignments + apply to all resources contained within their scope. For example, when you assign a policy at + resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + scope: str, + policy_assignment_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates a policy assignment with the given scope and name. Policy assignments + apply to all resources contained within their scope. For example, when you assign a policy at + resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + scope: str, + policy_assignment_name: str, + parameters: Union[_models.PolicyAssignmentUpdate, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates a policy assignment with the given scope and name. Policy assignments + apply to all resources contained within their scope. For example, when you assign a policy at + resource group scope, that policy applies to all resources in the group. + + :param scope: The scope of the policy assignment. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_assignment_name: The name of the policy assignment. Required. + :type policy_assignment_name: str + :param parameters: Parameters for policy assignment patch request. Is either a + PolicyAssignmentUpdate type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignmentUpdate") + + _request = build_policy_assignments_update_request( + scope=scope, + policy_assignment_name=policy_assignment_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_for_resource_group( + self, + resource_group_name: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> ItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a resource group. + + This operation retrieves the list of all policy assignments associated with the given resource + group in the given subscription that match the optional given $filter. Valid values for $filter + are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not + provided, the unfiltered list includes all policy assignments associated with the resource + group, including those that apply directly or apply from containing scopes, as well as any + applied to resources contained within the resource group. If $filter=atScope() is provided, the + returned list includes all policy assignments that apply to the resource group, which is + everything in the unfiltered list except those applied to resources contained within the + resource group. If $filter=atExactScope() is provided, the returned list only includes all + policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is + provided, the returned list includes all policy assignments of the policy definition whose id + is {value} that apply to the resource group. + + :param resource_group_name: The name of the resource group that contains policy assignments. + Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> ItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a resource. + + This operation retrieves the list of all policy assignments associated with the specified + resource in the given resource group and subscription that match the optional given $filter. + Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq + '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments + associated with the resource, including those that apply directly or from all containing + scopes, as well as any applied to resources contained within the resource. If $filter=atScope() + is provided, the returned list includes all policy assignments that apply to the resource, + which is everything in the unfiltered list except those applied to resources contained within + the resource. If $filter=atExactScope() is provided, the returned list only includes all policy + assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, + the returned list includes all policy assignments of the policy definition whose id is {value} + that apply to the resource. Three parameters plus the resource name are used to identify a + specific resource. If the resource is not part of a parent resource (the more common case), the + parent resource path should not be provided (or provided as ''). For example a web app could be + specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', + {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent + resource, then all parameters should be provided. For example a virtual machine DNS name could + be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == + 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == + 'MyComputerName'). A convenient alternative to providing the namespace and type name separately + is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', + {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == + 'MyWebApp'). + + :param resource_group_name: The name of the resource group containing the resource. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. For example, the + namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Use empty string if there is none. + Required. + :type parent_resource_path: str + :param resource_type: The resource type name. For example the type name of a web app is 'sites' + (from Microsoft.Web/sites). Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group( + self, + management_group_id: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any, + ) -> ItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a management group. + + This operation retrieves the list of all policy assignments applicable to the management group + that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or + 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes + all policy assignments that are assigned to the management group or the management group's + ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy + assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is + provided, the returned list includes all policy assignments of the policy definition whose id + is {value} that apply to the management group. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_for_management_group_request( + management_group_id=management_group_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list( + self, filter: Optional[str] = None, expand: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyAssignment"]: + """Retrieves all policy assignments that apply to a subscription. + + This operation retrieves the list of all policy assignments associated with the given + subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the + unfiltered list includes all policy assignments associated with the subscription, including + those that apply directly or from management groups that contain the given subscription, as + well as any applied to objects contained within the subscription. If $filter=atScope() is + provided, the returned list includes all policy assignments that apply to the subscription, + which is everything in the unfiltered list except those applied to objects contained within the + subscription. If $filter=atExactScope() is provided, the returned list only includes all policy + assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, + the returned list includes all policy assignments of the policy definition whose id is {value}. + + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering + is performed. If $filter=atScope() is provided, the returned list only includes all policy + assignments that apply to the scope, which is everything in the unfiltered list except those + applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, + the returned list only includes all policy assignments that at the given scope. If + $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy + assignments of the policy definition whose id is {value}. Default value is None. + :type filter: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :param top: Maximum number of records to return. When the $top filter is not provided, it will + return 500 records. Default value is None. + :type top: int + :return: An iterator like instance of either PolicyAssignment or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignmentListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_assignments_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + expand=expand, + top=top, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def delete_by_id(self, policy_assignment_id: str, **kwargs: Any) -> Optional[_models.PolicyAssignment]: + """Deletes a policy assignment. + + This operation deletes the policy with the given ID. Policy assignment IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + formats for {scope} are: '/providers/Microsoft.Management/managementGroups/{managementGroup}' + (management group), '/subscriptions/{subscriptionId}' (subscription), + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' (resource group), or + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}' + (resource). + + :param policy_assignment_id: The ID of the policy assignment to delete. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :return: PolicyAssignment or None or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[Optional[_models.PolicyAssignment]] = kwargs.pop("cls", None) + + _request = build_policy_assignments_delete_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates the policy assignment with the given ID. Policy assignments + made on a scope apply to all resources contained in that scope. For example, when you assign a + policy to a resource group that policy applies to all resources in the group. Policy assignment + IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_by_id( + self, policy_assignment_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates the policy assignment with the given ID. Policy assignments + made on a scope apply to all resources contained in that scope. For example, when you assign a + policy to a resource group that policy applies to all resources in the group. Policy assignment + IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignment, IO[bytes]], **kwargs: Any + ) -> _models.PolicyAssignment: + """Creates or updates a policy assignment. + + This operation creates or updates the policy assignment with the given ID. Policy assignments + made on a scope apply to all resources contained in that scope. For example, when you assign a + policy to a resource group that policy applies to all resources in the group. Policy assignment + IDs have this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to create. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment. Is either a PolicyAssignment type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignment or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignment") + + _request = build_policy_assignments_create_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_by_id( + self, policy_assignment_id: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.PolicyAssignment: + """Retrieves the policy assignment with the given ID. + + The operation retrieves the policy assignment with the given ID. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to get. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param expand: Comma-separated list of additional properties to be included in the response. + Supported values are 'LatestDefinitionVersion, EffectiveDefinitionVersion'. Default value is + None. + :type expand: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + _request = build_policy_assignments_get_by_id_request( + policy_assignment_id=policy_assignment_id, + expand=expand, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update_by_id( + self, + policy_assignment_id: str, + parameters: _models.PolicyAssignmentUpdate, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates the policy assignment with the given ID. Policy assignments made on a + scope apply to all resources contained in that scope. For example, when you assign a policy to + a resource group that policy applies to all resources in the group. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to update. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update_by_id( + self, policy_assignment_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates the policy assignment with the given ID. Policy assignments made on a + scope apply to all resources contained in that scope. For example, when you assign a policy to + a resource group that policy applies to all resources in the group. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to update. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment patch request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update_by_id( + self, policy_assignment_id: str, parameters: Union[_models.PolicyAssignmentUpdate, IO[bytes]], **kwargs: Any + ) -> _models.PolicyAssignment: + """Updates a policy assignment. + + This operation updates the policy assignment with the given ID. Policy assignments made on a + scope apply to all resources contained in that scope. For example, when you assign a policy to + a resource group that policy applies to all resources in the group. Policy assignment IDs have + this format: + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Valid + scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + + :param policy_assignment_id: The ID of the policy assignment to update. Use the format + '{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. Required. + :type policy_assignment_id: str + :param parameters: Parameters for policy assignment patch request. Is either a + PolicyAssignmentUpdate type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyAssignmentUpdate or IO[bytes] + :return: PolicyAssignment or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyAssignment] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyAssignmentUpdate") + + _request = build_policy_assignments_update_by_id_request( + policy_assignment_id=policy_assignment_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyAssignment", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class PolicyExemptionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`policy_exemptions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, policy_exemption_name: str, **kwargs: Any + ) -> None: + """Deletes a policy exemption. + + This operation deletes a policy exemption, given its name and the scope it was created in. The + scope of a policy exemption is the part of its ID preceding + '/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}'. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_policy_exemptions_delete_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update( + self, + scope: str, + policy_exemption_name: str, + parameters: _models.PolicyExemption, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyExemption: + """Creates or updates a policy exemption. + + This operation creates or updates a policy exemption with the given scope and name. Policy + exemptions apply to all resources contained within their scope. For example, when you create a + policy exemption at resource group scope for a policy assignment at the same or above level, + the exemption exempts to all applicable resources in the resource group. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for the policy exemption. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemption + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + scope: str, + policy_exemption_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyExemption: + """Creates or updates a policy exemption. + + This operation creates or updates a policy exemption with the given scope and name. Policy + exemptions apply to all resources contained within their scope. For example, when you create a + policy exemption at resource group scope for a policy assignment at the same or above level, + the exemption exempts to all applicable resources in the resource group. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for the policy exemption. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + scope: str, + policy_exemption_name: str, + parameters: Union[_models.PolicyExemption, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyExemption: + """Creates or updates a policy exemption. + + This operation creates or updates a policy exemption with the given scope and name. Policy + exemptions apply to all resources contained within their scope. For example, when you create a + policy exemption at resource group scope for a policy assignment at the same or above level, + the exemption exempts to all applicable resources in the resource group. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for the policy exemption. Is either a PolicyExemption type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemption or IO[bytes] + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyExemption") + + _request = build_policy_exemptions_create_or_update_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get(self, scope: str, policy_exemption_name: str, **kwargs: Any) -> _models.PolicyExemption: + """Retrieves a policy exemption. + + This operation retrieves a single policy exemption, given its name and the scope it was created + at. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) + + _request = build_policy_exemptions_get_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + scope: str, + policy_exemption_name: str, + parameters: _models.PolicyExemptionUpdate, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyExemption: + """Updates a policy exemption. + + This operation updates a policy exemption with the given scope and name. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for policy exemption patch request. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemptionUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + scope: str, + policy_exemption_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.PolicyExemption: + """Updates a policy exemption. + + This operation updates a policy exemption with the given scope and name. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for policy exemption patch request. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + scope: str, + policy_exemption_name: str, + parameters: Union[_models.PolicyExemptionUpdate, IO[bytes]], + **kwargs: Any, + ) -> _models.PolicyExemption: + """Updates a policy exemption. + + This operation updates a policy exemption with the given scope and name. + + :param scope: The scope of the policy exemption. Valid scopes are: management group (format: + '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: + '/subscriptions/{subscriptionId}'), resource group (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. + Required. + :type scope: str + :param policy_exemption_name: The name of the policy exemption to delete. Required. + :type policy_exemption_name: str + :param parameters: Parameters for policy exemption patch request. Is either a + PolicyExemptionUpdate type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.PolicyExemptionUpdate or IO[bytes] + :return: PolicyExemption or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.PolicyExemption + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PolicyExemption] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PolicyExemptionUpdate") + + _request = build_policy_exemptions_update_request( + scope=scope, + policy_exemption_name=policy_exemption_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PolicyExemption", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> ItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a subscription. + + This operation retrieves the list of all policy exemptions associated with the given + subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, the unfiltered list includes all policy exemptions associated with the subscription, + including those that apply directly or from management groups that contain the given + subscription, as well as any applied to objects contained within the subscription. + + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_resource_group( + self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a resource group. + + This operation retrieves the list of all policy exemptions associated with the given resource + group in the given subscription that match the optional given $filter. Valid values for $filter + are: 'atScope()', 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If + $filter is not provided, the unfiltered list includes all policy exemptions associated with the + resource group, including those that apply directly or apply from containing scopes, as well as + any applied to resources contained within the resource group. + + :param resource_group_name: The name of the resource group containing the resource. Required. + :type resource_group_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_resource( + self, + resource_group_name: str, + resource_provider_namespace: str, + parent_resource_path: str, + resource_type: str, + resource_name: str, + filter: Optional[str] = None, + **kwargs: Any, + ) -> ItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a resource. + + This operation retrieves the list of all policy exemptions associated with the specified + resource in the given resource group and subscription that match the optional given $filter. + Valid values for $filter are: 'atScope()', 'atExactScope()', 'excludeExpired()' or + 'policyAssignmentId eq '{value}''. If $filter is not provided, the unfiltered list includes all + policy exemptions associated with the resource, including those that apply directly or from all + containing scopes, as well as any applied to resources contained within the resource. Three + parameters plus the resource name are used to identify a specific resource. If the resource is + not part of a parent resource (the more common case), the parent resource path should not be + provided (or provided as ''). For example a web app could be specified as + ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == + 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all + parameters should be provided. For example a virtual machine DNS name could be specified as + ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == + 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == + 'MyComputerName'). A convenient alternative to providing the namespace and type name separately + is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', + {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == + 'MyWebApp'). + + :param resource_group_name: The name of the resource group containing the resource. Required. + :type resource_group_name: str + :param resource_provider_namespace: The namespace of the resource provider. For example, the + namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). + Required. + :type resource_provider_namespace: str + :param parent_resource_path: The parent resource path. Use empty string if there is none. + Required. + :type parent_resource_path: str + :param resource_type: The resource type name. For example the type name of a web app is 'sites' + (from Microsoft.Web/sites). Required. + :type resource_type: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_for_resource_request( + resource_group_name=resource_group_name, + resource_provider_namespace=resource_provider_namespace, + parent_resource_path=parent_resource_path, + resource_type=resource_type, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group( + self, management_group_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> ItemPaged["_models.PolicyExemption"]: + """Retrieves all policy exemptions that apply to a management group. + + This operation retrieves the list of all policy exemptions applicable to the management group + that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()', + 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter=atScope() is provided, the + returned list includes all policy exemptions that are assigned to the management group or the + management group's ancestors. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param filter: The filter to apply on the operation. Valid values for $filter are: 'atScope()', + 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}''. If $filter is not + provided, no filtering is performed. If $filter is not provided, the unfiltered list includes + all policy exemptions associated with the scope, including those that apply directly or apply + from containing scopes. If $filter=atScope() is provided, the returned list only includes all + policy exemptions that apply to the scope, which is everything in the unfiltered list except + those applied to sub scopes contained within the given scope. If $filter=atExactScope() is + provided, the returned list only includes all policy exemptions that at the given scope. If + $filter=excludeExpired() is provided, the returned list only includes all policy exemptions + that either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq + '{value}' is provided. the returned list only includes all policy exemptions that are + associated with the give policyAssignmentId. Default value is None. + :type filter: str + :return: An iterator like instance of either PolicyExemption or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.PolicyExemption] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-07-01-preview")) + cls: ClsType[_models.PolicyExemptionListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_policy_exemptions_list_for_management_group_request( + management_group_id=management_group_id, + filter=filter, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PolicyExemptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class VariablesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`variables` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete(self, variable_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Deletes a variable. + + This operation deletes a variable, given its name and the subscription it was created in. The + scope of a variable is the part of its ID preceding + '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variables_delete_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update( + self, variable_name: str, parameters: _models.Variable, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given subscription and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, variable_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given subscription and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, variable_name: str, parameters: Union[_models.Variable, IO[bytes]], **kwargs: Any + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given subscription and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Is either a Variable type or a IO[bytes] type. + Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable or IO[bytes] + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Variable") + + _request = build_variables_create_or_update_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get(self, variable_name: str, **kwargs: Any) -> _models.Variable: + """Retrieves a variable. + + This operation retrieves a single variable, given its name and the subscription it was created + at. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + _request = build_variables_get_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, management_group_id: str, variable_name: str, **kwargs: Any + ) -> None: + """Deletes a variable. + + This operation deletes a variable, given its name and the management group it was created in. + The scope of a variable is the part of its ID preceding + '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variables_delete_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + parameters: _models.Variable, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given management group and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given management group and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + parameters: Union[_models.Variable, IO[bytes]], + **kwargs: Any, + ) -> _models.Variable: + """Creates or updates a variable. + + This operation creates or updates a variable with the given management group and name. Policy + variables can only be used by a policy definition at the scope they are created or below. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param parameters: Parameters for the variable. Is either a Variable type or a IO[bytes] type. + Required. + :type parameters: ~azure.mgmt.resource.policy.models.Variable or IO[bytes] + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Variable") + + _request = build_variables_create_or_update_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_at_management_group(self, management_group_id: str, variable_name: str, **kwargs: Any) -> _models.Variable: + """Retrieves a variable. + + This operation retrieves a single variable, given its name and the management group it was + created at. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: Variable or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.Variable + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.Variable] = kwargs.pop("cls", None) + + _request = build_variables_get_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Variable", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.Variable"]: + """Retrieves all variables that are at this subscription level. + + This operation retrieves the list of all variables associated with the given subscription. + + :return: An iterator like instance of either Variable or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.Variable] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variables_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("VariableListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group(self, management_group_id: str, **kwargs: Any) -> ItemPaged["_models.Variable"]: + """Retrieves all variables that are at this management group level. + + This operation retrieves the list of all variables applicable to the management group. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :return: An iterator like instance of either Variable or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.Variable] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variables_list_for_management_group_request( + management_group_id=management_group_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("VariableListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class VariableValuesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.resource.policy.PolicyClient`'s + :attr:`variable_values` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: PolicyClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, variable_name: str, variable_value_name: str, **kwargs: Any + ) -> None: + """Deletes a variable value. + + This operation deletes a variable value, given its name, the subscription it was created in, + and the variable it belongs to. The scope of a variable value is the part of its ID preceding + '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variable_values_delete_request( + variable_name=variable_name, + variable_value_name=variable_value_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update( + self, + variable_name: str, + variable_value_name: str, + parameters: _models.VariableValue, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given subscription and name for a + given variable. Variable values are scoped to the variable for which they are created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + variable_name: str, + variable_value_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given subscription and name for a + given variable. Variable values are scoped to the variable for which they are created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + variable_name: str, + variable_value_name: str, + parameters: Union[_models.VariableValue, IO[bytes]], + **kwargs: Any, + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given subscription and name for a + given variable. Variable values are scoped to the variable for which they are created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Is either a VariableValue type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue or IO[bytes] + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "VariableValue") + + _request = build_variable_values_create_or_update_request( + variable_name=variable_name, + variable_value_name=variable_value_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get(self, variable_name: str, variable_value_name: str, **kwargs: Any) -> _models.VariableValue: + """Retrieves a variable value. + + This operation retrieves a single variable value; given its name, subscription it was created + at and the variable it's created for. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + _request = build_variable_values_get_request( + variable_name=variable_name, + variable_value_name=variable_value_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, variable_name: str, **kwargs: Any) -> ItemPaged["_models.VariableValue"]: + """List variable values for a variable. + + This operation retrieves the list of all variable values associated with the given variable + that is at a subscription level. + + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: An iterator like instance of either VariableValue or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.VariableValue] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValueListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variable_values_list_request( + variable_name=variable_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("VariableValueListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_for_management_group( + self, management_group_id: str, variable_name: str, **kwargs: Any + ) -> ItemPaged["_models.VariableValue"]: + """List variable values at management group level. + + This operation retrieves the list of all variable values applicable the variable indicated at + the management group scope. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :return: An iterator like instance of either VariableValue or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.models.VariableValue] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValueListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_variable_values_list_for_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("VariableValueListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def delete_at_management_group( # pylint: disable=inconsistent-return-statements + self, management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any + ) -> None: + """Deletes a variable value. + + This operation deletes a variable value, given its name, the management group it was created + in, and the variable it belongs to. The scope of a variable value is the part of its ID + preceding '/providers/Microsoft.Authorization/variables/{variableName}'. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_variable_values_delete_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + variable_value_name=variable_value_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + variable_value_name: str, + parameters: _models.VariableValue, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given management group and name for + a given variable. Variable values are scoped to the variable for which they are created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + variable_value_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given management group and name for + a given variable. Variable values are scoped to the variable for which they are created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, + management_group_id: str, + variable_name: str, + variable_value_name: str, + parameters: Union[_models.VariableValue, IO[bytes]], + **kwargs: Any, + ) -> _models.VariableValue: + """Creates or updates a variable value. + + This operation creates or updates a variable value with the given management group and name for + a given variable. Variable values are scoped to the variable for which they are created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :param parameters: Parameters for the variable value. Is either a VariableValue type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.resource.policy.models.VariableValue or IO[bytes] + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "VariableValue") + + _request = build_variable_values_create_or_update_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + variable_value_name=variable_value_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_at_management_group( + self, management_group_id: str, variable_name: str, variable_value_name: str, **kwargs: Any + ) -> _models.VariableValue: + """Retrieves a variable value. + + This operation retrieves a single variable value; given its name, management group it was + created at and the variable it's created for. + + :param management_group_id: The ID of the management group. Required. + :type management_group_id: str + :param variable_name: The name of the variable to operate on. Required. + :type variable_name: str + :param variable_value_name: The name of the variable value to operate on. Required. + :type variable_value_name: str + :return: VariableValue or the result of cls(response) + :rtype: ~azure.mgmt.resource.policy.models.VariableValue + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + cls: ClsType[_models.VariableValue] = kwargs.pop("cls", None) + + _request = build_variable_values_get_at_management_group_request( + management_group_id=management_group_id, + variable_name=variable_name, + variable_value_name=variable_value_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + deserialized = self._deserialize("VariableValue", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_patch.py b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/operations/_patch.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/py.typed b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/azure/mgmt/resource/policy/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-policy/dev_requirements.txt b/sdk/resources/azure-mgmt-resource-policy/dev_requirements.txt new file mode 100644 index 000000000000..ece056fe0984 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/dev_requirements.txt @@ -0,0 +1,5 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +../../core/azure-mgmt-core +aiohttp \ No newline at end of file diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition.py new file mode 100644 index 000000000000..f65eaafdf6ac --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition.py @@ -0,0 +1,66 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definitions.create_or_update( + policy_definition_name="ResourceNaming", + parameters={ + "properties": { + "description": "Force resource names to begin with given 'prefix' and/or end with given 'suffix'", + "displayName": "Enforce resource naming convention", + "metadata": {"category": "Naming"}, + "mode": "All", + "parameters": { + "prefix": { + "metadata": {"description": "Resource name prefix", "displayName": "Prefix"}, + "type": "String", + }, + "suffix": { + "metadata": {"description": "Resource name suffix", "displayName": "Suffix"}, + "type": "String", + }, + }, + "policyRule": { + "if": { + "not": {"field": "name", "like": "[concat(parameters('prefix'), '*', parameters('suffix'))]"} + }, + "then": {"effect": "deny"}, + }, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicyDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_advanced_params.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_advanced_params.py new file mode 100644 index 000000000000..f55fd0ac68c4 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_advanced_params.py @@ -0,0 +1,82 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_definition_advanced_params.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definitions.create_or_update( + policy_definition_name="EventHubDiagnosticLogs", + parameters={ + "properties": { + "description": "Audit enabling of logs and retain them up to a year. This enables recreation of activity trails for investigation purposes when a security incident occurs or your network is compromised", + "displayName": "Event Hubs should have diagnostic logging enabled", + "metadata": {"category": "Event Hub"}, + "mode": "Indexed", + "parameters": { + "requiredRetentionDays": { + "allowedValues": [0, 30, 90, 180, 365], + "defaultValue": 365, + "metadata": { + "description": "The required diagnostic logs retention in days", + "displayName": "Required retention (days)", + }, + "type": "Integer", + } + }, + "policyRule": { + "if": {"equals": "Microsoft.EventHub/namespaces", "field": "type"}, + "then": { + "details": { + "existenceCondition": { + "allOf": [ + { + "equals": "true", + "field": "Microsoft.Insights/diagnosticSettings/logs[*].retentionPolicy.enabled", + }, + { + "equals": "[parameters('requiredRetentionDays')]", + "field": "Microsoft.Insights/diagnosticSettings/logs[*].retentionPolicy.days", + }, + ] + }, + "type": "Microsoft.Insights/diagnosticSettings", + }, + "effect": "AuditIfNotExists", + }, + }, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicyDefinitionAdvancedParams.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_at_management_group.py new file mode 100644 index 000000000000..4f224ca49f83 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_at_management_group.py @@ -0,0 +1,67 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_definition_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definitions.create_or_update_at_management_group( + management_group_id="MyManagementGroup", + policy_definition_name="ResourceNaming", + parameters={ + "properties": { + "description": "Force resource names to begin with given 'prefix' and/or end with given 'suffix'", + "displayName": "Enforce resource naming convention", + "metadata": {"category": "Naming"}, + "mode": "All", + "parameters": { + "prefix": { + "metadata": {"description": "Resource name prefix", "displayName": "Prefix"}, + "type": "String", + }, + "suffix": { + "metadata": {"description": "Resource name suffix", "displayName": "Suffix"}, + "type": "String", + }, + }, + "policyRule": { + "if": { + "not": {"field": "name", "like": "[concat(parameters('prefix'), '*', parameters('suffix'))]"} + }, + "then": {"effect": "deny"}, + }, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicyDefinitionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version.py new file mode 100644 index 000000000000..36cc0d983bd5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version.py @@ -0,0 +1,68 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definition_versions.create_or_update( + policy_definition_name="ResourceNaming", + policy_definition_version="1.2.1", + parameters={ + "properties": { + "description": "Force resource names to begin with given 'prefix' and/or end with given 'suffix'", + "displayName": "Enforce resource naming convention", + "metadata": {"category": "Naming"}, + "mode": "All", + "parameters": { + "prefix": { + "metadata": {"description": "Resource name prefix", "displayName": "Prefix"}, + "type": "String", + }, + "suffix": { + "metadata": {"description": "Resource name suffix", "displayName": "Suffix"}, + "type": "String", + }, + }, + "policyRule": { + "if": { + "not": {"field": "name", "like": "[concat(parameters('prefix'), '*', parameters('suffix'))]"} + }, + "then": {"effect": "deny"}, + }, + "version": "1.2.1", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicyDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version_at_management_group.py new file mode 100644 index 000000000000..80c3c9d59f06 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_definition_version_at_management_group.py @@ -0,0 +1,69 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_definition_version_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definition_versions.create_or_update_at_management_group( + management_group_name="MyManagementGroup", + policy_definition_name="ResourceNaming", + policy_definition_version="1.2.1", + parameters={ + "properties": { + "description": "Force resource names to begin with given 'prefix' and/or end with given 'suffix'", + "displayName": "Enforce resource naming convention", + "metadata": {"category": "Naming"}, + "mode": "All", + "parameters": { + "prefix": { + "metadata": {"description": "Resource name prefix", "displayName": "Prefix"}, + "type": "String", + }, + "suffix": { + "metadata": {"description": "Resource name suffix", "displayName": "Suffix"}, + "type": "String", + }, + }, + "policyRule": { + "if": { + "not": {"field": "name", "like": "[concat(parameters('prefix'), '*', parameters('suffix'))]"} + }, + "then": {"effect": "deny"}, + }, + "version": "1.2.1", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicyDefinitionVersionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption.py new file mode 100644 index 000000000000..d866ff95c75a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption.py @@ -0,0 +1,53 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_exemption.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_exemptions.create_or_update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", + policy_exemption_name="DemoExpensiveVM", + parameters={ + "properties": { + "description": "Exempt demo cluster from limit sku", + "displayName": "Exempt demo cluster", + "exemptionCategory": "Waiver", + "metadata": {"reason": "Temporary exemption for a expensive VM demo"}, + "policyAssignmentId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/CostManagement", + "policyDefinitionReferenceIds": ["Limit_Skus"], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/createOrUpdatePolicyExemption.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption_with_resource_selectors.py new file mode 100644 index 000000000000..bbb5324203b5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_exemption_with_resource_selectors.py @@ -0,0 +1,60 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_exemption_with_resource_selectors.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_exemptions.create_or_update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", + policy_exemption_name="DemoExpensiveVM", + parameters={ + "properties": { + "assignmentScopeValidation": "Default", + "description": "Exempt demo cluster from limit sku", + "displayName": "Exempt demo cluster", + "exemptionCategory": "Waiver", + "metadata": {"reason": "Temporary exemption for a expensive VM demo"}, + "policyAssignmentId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyAssignments/CostManagement", + "policyDefinitionReferenceIds": ["Limit_Skus"], + "resourceSelectors": [ + { + "name": "SDPRegions", + "selectors": [{"in": ["eastus2euap", "centraluseuap"], "kind": "resourceLocation"}], + } + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/createOrUpdatePolicyExemptionWithResourceSelectors.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition.py new file mode 100644 index 000000000000..b2c3fe5d6ce6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition.py @@ -0,0 +1,68 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_set_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definitions.create_or_update( + policy_set_definition_name="CostManagement", + parameters={ + "properties": { + "description": "Policies to enforce low cost storage SKUs", + "displayName": "Cost Management", + "metadata": {"category": "Cost Management"}, + "parameters": { + "namePrefix": { + "defaultValue": "myPrefix", + "metadata": {"displayName": "Prefix to enforce on resource names"}, + "type": "String", + } + }, + "policyDefinitions": [ + { + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + "policyDefinitionReferenceId": "Limit_Skus", + }, + { + "parameters": {"prefix": {"value": "[parameters('namePrefix')]"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + "policyDefinitionReferenceId": "Resource_Naming", + }, + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicySetDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_at_management_group.py new file mode 100644 index 000000000000..c4c885842014 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_at_management_group.py @@ -0,0 +1,62 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_set_definition_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definitions.create_or_update_at_management_group( + management_group_id="MyManagementGroup", + policy_set_definition_name="CostManagement", + parameters={ + "properties": { + "description": "Policies to enforce low cost storage SKUs", + "displayName": "Cost Management", + "metadata": {"category": "Cost Management"}, + "policyDefinitions": [ + { + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/providers/Microsoft.Management/managementgroups/MyManagementGroup/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + "policyDefinitionReferenceId": "Limit_Skus", + }, + { + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/providers/Microsoft.Management/managementgroups/MyManagementGroup/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + "policyDefinitionReferenceId": "Resource_Naming", + }, + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version.py new file mode 100644 index 000000000000..031cbf732061 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version.py @@ -0,0 +1,70 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_set_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definition_versions.create_or_update( + policy_set_definition_name="CostManagement", + policy_definition_version="1.2.1", + parameters={ + "properties": { + "description": "Policies to enforce low cost storage SKUs", + "displayName": "Cost Management", + "metadata": {"category": "Cost Management"}, + "parameters": { + "namePrefix": { + "defaultValue": "myPrefix", + "metadata": {"displayName": "Prefix to enforce on resource names"}, + "type": "String", + } + }, + "policyDefinitions": [ + { + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + "policyDefinitionReferenceId": "Limit_Skus", + }, + { + "parameters": {"prefix": {"value": "[parameters('namePrefix')]"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + "policyDefinitionReferenceId": "Resource_Naming", + }, + ], + "version": "1.2.1", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version_at_management_group.py new file mode 100644 index 000000000000..2e03544efa6e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_version_at_management_group.py @@ -0,0 +1,64 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_set_definition_version_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.create_or_update_at_management_group( + management_group_name="MyManagementGroup", + policy_set_definition_name="CostManagement", + policy_definition_version="1.2.1", + parameters={ + "properties": { + "description": "Policies to enforce low cost storage SKUs", + "displayName": "Cost Management", + "metadata": {"category": "Cost Management"}, + "policyDefinitions": [ + { + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/providers/Microsoft.Management/managementgroups/MyManagementGroup/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + "policyDefinitionReferenceId": "Limit_Skus", + }, + { + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/providers/Microsoft.Management/managementgroups/MyManagementGroup/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + "policyDefinitionReferenceId": "Resource_Naming", + }, + ], + "version": "1.2.1", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionVersionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups.py new file mode 100644 index 000000000000..7cb82d92e353 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups.py @@ -0,0 +1,77 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_set_definition_with_groups.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definitions.create_or_update( + policy_set_definition_name="CostManagement", + parameters={ + "properties": { + "description": "Policies to enforce low cost storage SKUs", + "displayName": "Cost Management", + "metadata": {"category": "Cost Management"}, + "policyDefinitionGroups": [ + { + "description": "Policies designed to control spend within a subscription.", + "displayName": "Cost Management Policies", + "name": "CostSaving", + }, + { + "description": "Policies that help enforce resource organization standards within a subscription.", + "displayName": "Organizational Policies", + "name": "Organizational", + }, + ], + "policyDefinitions": [ + { + "definitionVersion": "1.*.*", + "groupNames": ["CostSaving"], + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + "policyDefinitionReferenceId": "Limit_Skus", + }, + { + "definitionVersion": "1.*.*", + "groupNames": ["Organizational"], + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + "policyDefinitionReferenceId": "Resource_Naming", + }, + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionWithGroups.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups_at_management_group.py new file mode 100644 index 000000000000..de0a96816915 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_policy_set_definition_with_groups_at_management_group.py @@ -0,0 +1,76 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_policy_set_definition_with_groups_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definitions.create_or_update_at_management_group( + management_group_id="MyManagementGroup", + policy_set_definition_name="CostManagement", + parameters={ + "properties": { + "description": "Policies to enforce low cost storage SKUs", + "displayName": "Cost Management", + "metadata": {"category": "Cost Management"}, + "policyDefinitionGroups": [ + { + "description": "Policies designed to control spend within a subscription.", + "displayName": "Cost Management Policies", + "name": "CostSaving", + }, + { + "description": "Policies that help enforce resource organization standards within a subscription.", + "displayName": "Organizational Policies", + "name": "Organizational", + }, + ], + "policyDefinitions": [ + { + "groupNames": ["CostSaving"], + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + "policyDefinitionReferenceId": "Limit_Skus", + }, + { + "groupNames": ["Organizational"], + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + "policyDefinitionReferenceId": "Resource_Naming", + }, + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createOrUpdatePolicySetDefinitionWithGroupsAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable.py new file mode 100644 index 000000000000..89cbf2505824 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_variable.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.variables.create_or_update( + variable_name="DemoTestVariable", + parameters={"properties": {"columns": [{"columnName": "TestColumn"}]}}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/createOrUpdateVariable.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_at_management_group.py new file mode 100644 index 000000000000..a075f0dbc3b5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_at_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_variable_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.variables.create_or_update_at_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + parameters={"properties": {"columns": [{"columnName": "TestColumn"}]}}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/createOrUpdateVariableAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value.py new file mode 100644 index 000000000000..825d5a80e2ad --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value.py @@ -0,0 +1,51 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_variable_value.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.variable_values.create_or_update( + variable_name="DemoTestVariable", + variable_value_name="TestValue", + parameters={ + "properties": { + "values": [ + {"columnName": "StringColumn", "columnValue": "SampleValue"}, + {"columnName": "IntegerColumn", "columnValue": 10}, + ] + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/createOrUpdateVariableValue.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value_at_management_group.py new file mode 100644 index 000000000000..2d97c14eea1f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_or_update_variable_value_at_management_group.py @@ -0,0 +1,52 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_or_update_variable_value_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.variable_values.create_or_update_at_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + variable_value_name="TestValue", + parameters={ + "properties": { + "values": [ + {"columnName": "StringColumn", "columnValue": "SampleValue"}, + {"columnName": "IntegerColumn", "columnValue": 10}, + ] + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/createOrUpdateVariableValueAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment.py new file mode 100644 index 000000000000..aa0bc1951369 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment.py @@ -0,0 +1,53 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + parameters={ + "properties": { + "description": "Force resource names to begin with given DeptA and end with -LC", + "displayName": "Enforce resource naming rules", + "metadata": {"assignedBy": "Special Someone"}, + "nonComplianceMessages": [{"message": "Resource names must start with 'DeptA' and end with '-LC'."}], + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignment.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_by_id.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_by_id.py new file mode 100644 index 000000000000..94e796f90136 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_by_id.py @@ -0,0 +1,53 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_by_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create_by_id( + policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", + parameters={ + "properties": { + "definitionVersion": "1.*.*", + "description": "Allow only storage accounts of SKU Standard_GRS or Standard_LRS to be created", + "displayName": "Enforce storage account SKU", + "enforcementMode": "Default", + "metadata": {"assignedBy": "Cheapskate Boss"}, + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentById.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_non_compliance_messages.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_non_compliance_messages.py new file mode 100644 index 000000000000..a359570f354f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_non_compliance_messages.py @@ -0,0 +1,62 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_non_compliance_messages.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="securityInitAssignment", + parameters={ + "properties": { + "displayName": "Enforce security policies", + "nonComplianceMessages": [ + { + "message": "Resources must comply with all internal security policies. See for more info." + }, + { + "message": "Resource names must start with 'DeptA' and end with '-LC'.", + "policyDefinitionReferenceId": "10420126870854049575", + }, + { + "message": "Storage accounts must have firewall rules configured.", + "policyDefinitionReferenceId": "8572513655450389710", + }, + ], + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/securityInitiative", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentNonComplianceMessages.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity.py new file mode 100644 index 000000000000..a76ddf832052 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity.py @@ -0,0 +1,55 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_with_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + parameters={ + "identity": {"type": "SystemAssigned"}, + "location": "eastus", + "properties": { + "description": "Force resource names to begin with given DeptA and end with -LC", + "displayName": "Enforce resource naming rules", + "enforcementMode": "Default", + "metadata": {"assignedBy": "Foo Bar"}, + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentWithIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity_by_id.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity_by_id.py new file mode 100644 index 000000000000..1909f06ca22a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_identity_by_id.py @@ -0,0 +1,55 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_with_identity_by_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create_by_id( + policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", + parameters={ + "identity": {"type": "SystemAssigned"}, + "location": "eastus", + "properties": { + "definitionVersion": "1.*.*", + "description": "Allow only storage accounts of SKU Standard_GRS or Standard_LRS to be created", + "displayName": "Enforce storage account SKU", + "enforcementMode": "Default", + "metadata": {"assignedBy": "Cheapskate Boss"}, + "parameters": {"listOfAllowedSKUs": {"value": ["Standard_GRS", "Standard_LRS"]}}, + "policyDefinitionId": "/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentWithIdentityById.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_overrides.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_overrides.py new file mode 100644 index 000000000000..8624ed97d9c0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_overrides.py @@ -0,0 +1,58 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_with_overrides.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="CostManagement", + parameters={ + "properties": { + "description": "Limit the resource location and resource SKU", + "displayName": "Limit the resource location and resource SKU", + "metadata": {"assignedBy": "Special Someone"}, + "overrides": [ + { + "kind": "policyEffect", + "selectors": [{"in": ["Limit_Skus", "Limit_Locations"], "kind": "policyDefinitionReferenceId"}], + "value": "Audit", + } + ], + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentWithOverrides.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_resource_selectors.py new file mode 100644 index 000000000000..bf192cdef215 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_resource_selectors.py @@ -0,0 +1,57 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_with_resource_selectors.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="CostManagement", + parameters={ + "properties": { + "description": "Limit the resource location and resource SKU", + "displayName": "Limit the resource location and resource SKU", + "metadata": {"assignedBy": "Special Someone"}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policySetDefinitions/CostManagement", + "resourceSelectors": [ + { + "name": "SDPRegions", + "selectors": [{"in": ["eastus2euap", "centraluseuap"], "kind": "resourceLocation"}], + } + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentWithResourceSelectors.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_user_assigned_identity.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_user_assigned_identity.py new file mode 100644 index 000000000000..6a61c49b9bdd --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_with_user_assigned_identity.py @@ -0,0 +1,60 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_with_user_assigned_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + parameters={ + "identity": { + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/testResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-identity": {} + }, + }, + "location": "eastus", + "properties": { + "description": "Force resource names to begin with given DeptA and end with -LC", + "displayName": "Enforce resource naming rules", + "enforcementMode": "Default", + "metadata": {"assignedBy": "Foo Bar"}, + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentWithUserAssignedIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_without_enforcement.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_without_enforcement.py new file mode 100644 index 000000000000..832f7c603611 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/create_policy_assignment_without_enforcement.py @@ -0,0 +1,53 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python create_policy_assignment_without_enforcement.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.create( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + parameters={ + "properties": { + "description": "Force resource names to begin with given DeptA and end with -LC", + "displayName": "Enforce resource naming rules", + "enforcementMode": "DoNotEnforce", + "metadata": {"assignedBy": "Special Someone"}, + "parameters": {"prefix": {"value": "DeptA"}, "suffix": {"value": "-LC"}}, + "policyDefinitionId": "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/providers/Microsoft.Authorization/policyDefinitions/ResourceNaming", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/createPolicyAssignmentWithoutEnforcement.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment.py new file mode 100644 index 000000000000..c748e634c9d3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_assignment.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.delete( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicyAssignment.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment_by_id.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment_by_id.py new file mode 100644 index 000000000000..f0d7b17c75f3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_assignment_by_id.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_assignment_by_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.delete_by_id( + policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicyAssignmentById.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition.py new file mode 100644 index 000000000000..b2cecb119bf3 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + client.policy_definitions.delete( + policy_definition_name="ResourceNaming", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicyDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_at_management_group.py new file mode 100644 index 000000000000..aa2e5e3137b9 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_at_management_group.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_definition_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.policy_definitions.delete_at_management_group( + management_group_id="MyManagementGroup", + policy_definition_name="ResourceNaming", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicyDefinitionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version.py new file mode 100644 index 000000000000..0e2c938ec759 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + client.policy_definition_versions.delete( + policy_definition_name="ResourceNaming", + policy_definition_version="1.2.1", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicyDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version_at_management_group.py new file mode 100644 index 000000000000..16268fe9a212 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_definition_version_at_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_definition_version_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.policy_definition_versions.delete_at_management_group( + management_group_name="MyManagementGroup", + policy_definition_name="ResourceNaming", + policy_definition_version="1.2.1", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicyDefinitionVersionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_exemption.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_exemption.py new file mode 100644 index 000000000000..6d232dfe8c25 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_exemption.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_exemption.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.policy_exemptions.delete( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", + policy_exemption_name="DemoExpensiveVM", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/deletePolicyExemption.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition.py new file mode 100644 index 000000000000..3c96c8c9e3a6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_set_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + client.policy_set_definitions.delete( + policy_set_definition_name="CostManagement", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicySetDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_at_management_group.py new file mode 100644 index 000000000000..6b1e72fb0f5c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_at_management_group.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_set_definition_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.policy_set_definitions.delete_at_management_group( + management_group_id="MyManagementGroup", + policy_set_definition_name="CostManagement", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicySetDefinitionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version.py new file mode 100644 index 000000000000..51bf0707e2c7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_set_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + client.policy_set_definition_versions.delete( + policy_set_definition_name="CostManagement", + policy_definition_version="1.2.1", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicySetDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version_at_management_group.py new file mode 100644 index 000000000000..d6cfec176671 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_policy_set_definition_version_at_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_policy_set_definition_version_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.policy_set_definition_versions.delete_at_management_group( + management_group_name="MyManagementGroup", + policy_set_definition_name="CostManagement", + policy_definition_version="1.2.1", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/deletePolicySetDefinitionVersionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable.py new file mode 100644 index 000000000000..0cd87280bc4d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_variable.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + client.variables.delete( + variable_name="DemoTestVariable", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/deleteVariable.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_at_management_group.py new file mode 100644 index 000000000000..5a7459323877 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_at_management_group.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_variable_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.variables.delete_at_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/deleteVariableAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value.py new file mode 100644 index 000000000000..bcf9ecab1c46 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_variable_value.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + client.variable_values.delete( + variable_name="DemoTestVariable", + variable_value_name="TestValue", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/deleteVariableValue.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value_at_management_group.py new file mode 100644 index 000000000000..1bfaf14fdce7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/delete_variable_value_at_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python delete_variable_value_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + client.variable_values.delete_at_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + variable_value_name="TestValue", + ) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/deleteVariableValueAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition.py new file mode 100644 index 000000000000..95af387b1ee5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_built_in_policy_set_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definitions.get_built_in( + policy_set_definition_name="1f3afdf9-d0c9-4c3d-847f-89da613e70a8", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getBuiltInPolicySetDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition_version.py new file mode 100644 index 000000000000..5c7b4fe5f760 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_built_in_policy_set_definition_version.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_built_in_policy_set_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.get_built_in( + policy_set_definition_name="1f3afdf9-d0c9-4c3d-847f-89da613e70a8", + policy_definition_version="1.2.1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getBuiltInPolicySetDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition.py new file mode 100644 index 000000000000..438e7e01b788 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_builtin_policy_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definitions.get_built_in( + policy_definition_name="7433c107-6db4-4ad1-b57a-a76dce0154a1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getBuiltinPolicyDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition_version.py new file mode 100644 index 000000000000..a384f86096eb --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_builtin_policy_definition_version.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_builtin_policy_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definition_versions.get_built_in( + policy_definition_name="7433c107-6db4-4ad1-b57a-a76dce0154a1", + policy_definition_version="1.2.1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getBuiltinPolicyDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_data_policy_manifest.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_data_policy_manifest.py new file mode 100644 index 000000000000..1a79eb31fd05 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_data_policy_manifest.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_data_policy_manifest.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.data_policy_manifests.get_by_policy_mode( + policy_mode="Microsoft.KeyVault.Data", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2020-09-01/examples/getDataPolicyManifest.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment.py new file mode 100644 index 000000000000..190c5389fc5b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignment.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_by_id.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_by_id.py new file mode 100644 index 000000000000..5f00fa2e9f29 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_by_id.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment_by_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get_by_id( + policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignmentById.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity.py new file mode 100644 index 000000000000..2bdaa63dd312 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment_with_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignmentWithIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity_by_id.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity_by_id.py new file mode 100644 index 000000000000..0ffcba7ede4e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_identity_by_id.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment_with_identity_by_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get_by_id( + policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignmentWithIdentityById.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_overrides.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_overrides.py new file mode 100644 index 000000000000..b24ae0f2bebc --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_overrides.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment_with_overrides.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="CostManagement", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignmentWithOverrides.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_resource_selectors.py new file mode 100644 index 000000000000..434e44b7f811 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_resource_selectors.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment_with_resource_selectors.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="CostManagement", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignmentWithResourceSelectors.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_user_assigned_identity.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_user_assigned_identity.py new file mode 100644 index 000000000000..070db7d59fc7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_assignment_with_user_assigned_identity.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_assignment_with_user_assigned_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyAssignmentWithUserAssignedIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition.py new file mode 100644 index 000000000000..dd5ea749063f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definitions.get( + policy_definition_name="ResourceNaming", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_at_management_group.py new file mode 100644 index 000000000000..ab5a9b98371c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_at_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_definition_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definitions.get_at_management_group( + management_group_id="MyManagementGroup", + policy_definition_name="ResourceNaming", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyDefinitionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version.py new file mode 100644 index 000000000000..9863b1360530 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definition_versions.get( + policy_definition_name="ResourceNaming", + policy_definition_version="1.2.1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version_at_management_group.py new file mode 100644 index 000000000000..e7f872f16e23 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_definition_version_at_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_definition_version_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definition_versions.get_at_management_group( + management_group_name="MyManagementGroup", + policy_definition_name="ResourceNaming", + policy_definition_version="1.2.1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicyDefinitionVersionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption.py new file mode 100644 index 000000000000..d9eae16f8384 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_exemption.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_exemptions.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", + policy_exemption_name="DemoExpensiveVM", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/getPolicyExemption.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption_with_resource_selectors.py new file mode 100644 index 000000000000..7d75b672778b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_exemption_with_resource_selectors.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_exemption_with_resource_selectors.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_exemptions.get( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", + policy_exemption_name="DemoExpensiveVM", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/getPolicyExemptionWithResourceSelectors.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition.py new file mode 100644 index 000000000000..a7446c1726ca --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_set_definition.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definitions.get( + policy_set_definition_name="CostManagement", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicySetDefinition.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_at_management_group.py new file mode 100644 index 000000000000..54d50c033243 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_at_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_set_definition_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definitions.get_at_management_group( + management_group_id="MyManagementGroup", + policy_set_definition_name="CostManagement", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicySetDefinitionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version.py new file mode 100644 index 000000000000..4446c6afc50a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_set_definition_version.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definition_versions.get( + policy_set_definition_name="CostManagement", + policy_definition_version="1.2.1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicySetDefinitionVersion.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version_at_management_group.py new file mode 100644 index 000000000000..0360da53741c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_policy_set_definition_version_at_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_policy_set_definition_version_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.get_at_management_group( + management_group_name="MyManagementGroup", + policy_set_definition_name="CostManagement", + policy_definition_version="1.2.1", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/getPolicySetDefinitionVersionAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable.py new file mode 100644 index 000000000000..a5c344300f51 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_variable.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.variables.get( + variable_name="DemoTestVariable", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/getVariable.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_at_management_group.py new file mode 100644 index 000000000000..fb8ba6ad8112 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_at_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_variable_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.variables.get_at_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/getVariableAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value.py new file mode 100644 index 000000000000..8717e590786e --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_variable_value.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.variable_values.get( + variable_name="DemoTestVariable", + variable_value_name="TestValue", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/getVariableValue.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value_at_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value_at_management_group.py new file mode 100644 index 000000000000..3e3ebaad39f0 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/get_variable_value_at_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python get_variable_value_at_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.variable_values.get_at_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + variable_value_name="TestValue", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/getVariableValueAtManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_definition_versions.py new file mode 100644 index 000000000000..c2cc14995a1d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_definition_versions.py @@ -0,0 +1,40 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_all_built_in_policy_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definition_versions.list_all_builtins() + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listAllBuiltInPolicyDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_set_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_set_definition_versions.py new file mode 100644 index 000000000000..570ea95e8229 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_built_in_policy_set_definition_versions.py @@ -0,0 +1,40 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_all_built_in_policy_set_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.list_all_builtins() + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listAllBuiltInPolicySetDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions.py new file mode 100644 index 000000000000..753966d70c72 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions.py @@ -0,0 +1,40 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_all_policy_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definition_versions.list_all() + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listAllPolicyDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions_by_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions_by_management_group.py new file mode 100644 index 000000000000..f0c37614e70a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_definition_versions_by_management_group.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_all_policy_definition_versions_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definition_versions.list_all_at_management_group( + management_group_name="MyManagementGroup", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listAllPolicyDefinitionVersionsByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions.py new file mode 100644 index 000000000000..a7dcddd6e26d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions.py @@ -0,0 +1,40 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_all_policy_set_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definition_versions.list_all() + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listAllPolicySetDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions_by_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions_by_management_group.py new file mode 100644 index 000000000000..2a7dd0b58a56 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_all_policy_set_definition_versions_by_management_group.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_all_policy_set_definition_versions_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.list_all_at_management_group( + management_group_name="MyManagementGroup", + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listAllPolicySetDefinitionVersionsByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definition_versions.py new file mode 100644 index 000000000000..dec4b4ba6314 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definition_versions.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_built_in_policy_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definition_versions.list_built_in( + policy_definition_name="06a78e20-9358-41c9-923c-fb736d382a12", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listBuiltInPolicyDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definitions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definitions.py new file mode 100644 index 000000000000..382439ab8e77 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_definitions.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_built_in_policy_definitions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definitions.list_built_in() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listBuiltInPolicyDefinitions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definition_versions.py new file mode 100644 index 000000000000..b6b3e257e496 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definition_versions.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_built_in_policy_set_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.list_built_in( + policy_set_definition_name="1f3afdf9-d0c9-4c3d-847f-89da613e70a8", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listBuiltInPolicySetDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definitions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definitions.py new file mode 100644 index 000000000000..039c1d302864 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_built_in_policy_set_definitions.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_built_in_policy_set_definitions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definitions.list_built_in() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listBuiltInPolicySetDefinitions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests.py new file mode 100644 index 000000000000..72fa51318efa --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_data_policy_manifests.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.data_policy_manifests.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2020-09-01/examples/listDataPolicyManifests.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests_namespace_filter.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests_namespace_filter.py new file mode 100644 index 000000000000..c4b8c81de645 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_data_policy_manifests_namespace_filter.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_data_policy_manifests_namespace_filter.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.data_policy_manifests.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2020-09-01/examples/listDataPolicyManifestsNamespaceFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments.py new file mode 100644 index 000000000000..bb41649763fd --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_assignments.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_assignments.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyAssignments.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_management_group.py new file mode 100644 index 000000000000..905dbd340aa4 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_assignments_for_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.list_for_management_group( + management_group_id="TestManagementGroup", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyAssignmentsForManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource.py new file mode 100644 index 000000000000..d466fd6f688c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource.py @@ -0,0 +1,47 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_assignments_for_resource.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_assignments.list_for_resource( + resource_group_name="TestResourceGroup", + resource_provider_namespace="Microsoft.Compute", + parent_resource_path="virtualMachines/MyTestVm", + resource_type="domainNames", + resource_name="MyTestComputer.cloudapp.net", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyAssignmentsForResource.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource_group.py new file mode 100644 index 000000000000..0ba2def195ac --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_assignments_for_resource_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_assignments_for_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_assignments.list_for_resource_group( + resource_group_name="TestResourceGroup", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyAssignmentsForResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions.py new file mode 100644 index 000000000000..1516a56dfd53 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definition_versions.list( + policy_definition_name="ResourceNaming", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions_by_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions_by_management_group.py new file mode 100644 index 000000000000..ed6f7b4025e5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definition_versions_by_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_definition_versions_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definition_versions.list_by_management_group( + management_group_name="MyManagementGroup", + policy_definition_name="ResourceNaming", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyDefinitionVersionsByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions.py new file mode 100644 index 000000000000..998a00be3403 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_definitions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_definitions.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyDefinitions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions_by_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions_by_management_group.py new file mode 100644 index 000000000000..e7575f9876b1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_definitions_by_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_definitions_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_definitions.list_by_management_group( + management_group_id="MyManagementGroup", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicyDefinitionsByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_management_group.py new file mode 100644 index 000000000000..873b7eed1370 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_exemptions_for_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_exemptions.list_for_management_group( + management_group_id="DevOrg", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/listPolicyExemptionsForManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource.py new file mode 100644 index 000000000000..8315c35c4114 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource.py @@ -0,0 +1,47 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_exemptions_for_resource.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_exemptions.list_for_resource( + resource_group_name="TestResourceGroup", + resource_provider_namespace="Microsoft.Compute", + parent_resource_path="virtualMachines/MyTestVm", + resource_type="domainNames", + resource_name="MyTestComputer.cloudapp.net", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/listPolicyExemptionsForResource.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource_group.py new file mode 100644 index 000000000000..787aea63be6d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_resource_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_exemptions_for_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_exemptions.list_for_resource_group( + resource_group_name="TestResourceGroup", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/listPolicyExemptionsForResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_subscription.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_subscription.py new file mode 100644 index 000000000000..1cf11b5e582c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_exemptions_for_subscription.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_exemptions_for_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_exemptions.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/listPolicyExemptionsForSubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions.py new file mode 100644 index 000000000000..7741de50dc73 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_set_definition_versions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definition_versions.list( + policy_set_definition_name="CostManagement", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicySetDefinitionVersions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions_by_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions_by_management_group.py new file mode 100644 index 000000000000..21269baede20 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definition_versions_by_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_set_definition_versions_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definition_versions.list_by_management_group( + management_group_name="MyManagementGroup", + policy_set_definition_name="CostManagement", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicySetDefinitionVersionsByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions.py new file mode 100644 index 000000000000..708600c70528 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_set_definitions.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.policy_set_definitions.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicySetDefinitions.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions_by_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions_by_management_group.py new file mode 100644 index 000000000000..b7160f81cb8d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_policy_set_definitions_by_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_policy_set_definitions_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_set_definitions.list_by_management_group( + management_group_id="MyManagementGroup", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/listPolicySetDefinitionsByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_management_group.py new file mode 100644 index 000000000000..00f9d01c0e9c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_management_group.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_variable_values_for_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.variable_values.list_for_management_group( + management_group_id="DevOrg", + variable_name="DemoTestVariable", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/listVariableValuesForManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_subscription.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_subscription.py new file mode 100644 index 000000000000..b6cbe7624322 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variable_values_for_subscription.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_variable_values_for_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.variable_values.list( + variable_name="DemoTestVariable", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/listVariableValuesForSubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_management_group.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_management_group.py new file mode 100644 index 000000000000..e57dbb4f5283 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_management_group.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_variables_for_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.variables.list_for_management_group( + management_group_id="DevOrg", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/listVariablesForManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_subscription.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_subscription.py new file mode 100644 index 000000000000..ef937a8c21ee --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/list_variables_for_subscription.py @@ -0,0 +1,41 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python list_variables_for_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + ) + + response = client.variables.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-08-01-preview/examples/listVariablesForSubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity.py new file mode 100644 index 000000000000..976fddd0b378 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python update_policy_assignment_with_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + parameters={"identity": {"type": "SystemAssigned"}, "location": "eastus"}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/updatePolicyAssignmentWithIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity_by_id.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity_by_id.py new file mode 100644 index 000000000000..e2a6827f7227 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_identity_by_id.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python update_policy_assignment_with_identity_by_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.update_by_id( + policy_assignment_id="providers/Microsoft.Management/managementGroups/MyManagementGroup/providers/Microsoft.Authorization/policyAssignments/LowCostStorage", + parameters={"identity": {"type": "SystemAssigned"}, "location": "eastus"}, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/updatePolicyAssignmentWithIdentityById.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_overrides.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_overrides.py new file mode 100644 index 000000000000..5d194a7b03f6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_overrides.py @@ -0,0 +1,54 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python update_policy_assignment_with_overrides.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="CostManagement", + parameters={ + "properties": { + "overrides": [ + { + "kind": "policyEffect", + "selectors": [{"in": ["Limit_Skus", "Limit_Locations"], "kind": "policyDefinitionReferenceId"}], + "value": "Audit", + } + ] + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/updatePolicyAssignmentWithOverrides.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_resource_selectors.py new file mode 100644 index 000000000000..2cbbbb2310ce --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_resource_selectors.py @@ -0,0 +1,53 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python update_policy_assignment_with_resource_selectors.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="CostManagement", + parameters={ + "properties": { + "resourceSelectors": [ + { + "name": "SDPRegions", + "selectors": [{"in": ["eastus2euap", "centraluseuap"], "kind": "resourceLocation"}], + } + ] + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/updatePolicyAssignmentWithResourceSelectors.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_user_assigned_identity.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_user_assigned_identity.py new file mode 100644 index 000000000000..05ce73c9e30f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_assignment_with_user_assigned_identity.py @@ -0,0 +1,52 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python update_policy_assignment_with_user_assigned_identity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_assignments.update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2", + policy_assignment_name="EnforceNaming", + parameters={ + "identity": { + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/testResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-identity": {} + }, + }, + "location": "eastus", + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/stable/2023-04-01/examples/updatePolicyAssignmentWithUserAssignedIdentity.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_exemption_with_resource_selectors.py b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_exemption_with_resource_selectors.py new file mode 100644 index 000000000000..88445a05426f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_samples/update_policy_exemption_with_resource_selectors.py @@ -0,0 +1,54 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.resource.policy import PolicyClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-resource-policy +# USAGE + python update_policy_exemption_with_resource_selectors.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PolicyClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.policy_exemptions.update( + scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2/resourceGroups/demoCluster", + policy_exemption_name="DemoExpensiveVM", + parameters={ + "properties": { + "assignmentScopeValidation": "Default", + "resourceSelectors": [ + { + "name": "SDPRegions", + "selectors": [{"in": ["eastus2euap", "centraluseuap"], "kind": "resourceLocation"}], + } + ], + } + }, + ) + print(response) + + +# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/policy/preview/2022-07-01-preview/examples/updatePolicyExemptionWithResourceSelectors.json +if __name__ == "__main__": + main() diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/conftest.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/conftest.py new file mode 100644 index 000000000000..e95ee7df4d34 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + policy_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + policy_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + policy_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + policy_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations.py new file mode 100644 index 000000000000..43e4371bb1ae --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyDataPolicyManifestsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_data_policy_manifests_get_by_policy_mode(self, resource_group): + response = self.client.data_policy_manifests.get_by_policy_mode( + policy_mode="str", + api_version="2020-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_data_policy_manifests_list(self, resource_group): + response = self.client.data_policy_manifests.list( + api_version="2020-09-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations_async.py new file mode 100644 index 000000000000..d6bebc8340f6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_data_policy_manifests_operations_async.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyDataPolicyManifestsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_data_policy_manifests_get_by_policy_mode(self, resource_group): + response = await self.client.data_policy_manifests.get_by_policy_mode( + policy_mode="str", + api_version="2020-09-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_data_policy_manifests_list(self, resource_group): + response = self.client.data_policy_manifests.list( + api_version="2020-09-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations.py new file mode 100644 index 000000000000..57b128e19c3b --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations.py @@ -0,0 +1,256 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyAssignmentsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_delete(self, resource_group): + response = self.client.policy_assignments.delete( + scope="str", + policy_assignment_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_create(self, resource_group): + response = self.client.policy_assignments.create( + scope="str", + policy_assignment_name="str", + parameters={ + "definitionVersion": "str", + "description": "str", + "displayName": "str", + "effectiveDefinitionVersion": "str", + "enforcementMode": "Default", + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "latestDefinitionVersion": "str", + "location": "str", + "metadata": {}, + "name": "str", + "nonComplianceMessages": [{"message": "str", "policyDefinitionReferenceId": "str"}], + "notScopes": ["str"], + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "parameters": {"str": {"value": {}}}, + "policyDefinitionId": "str", + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + "scope": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_get(self, resource_group): + response = self.client.policy_assignments.get( + scope="str", + policy_assignment_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_update(self, resource_group): + response = self.client.policy_assignments.update( + scope="str", + policy_assignment_name="str", + parameters={ + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "location": "str", + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_list_for_resource_group(self, resource_group): + response = self.client.policy_assignments.list_for_resource_group( + resource_group_name=resource_group.name, + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_list_for_resource(self, resource_group): + response = self.client.policy_assignments.list_for_resource( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_list_for_management_group(self, resource_group): + response = self.client.policy_assignments.list_for_management_group( + management_group_id="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_list(self, resource_group): + response = self.client.policy_assignments.list( + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_delete_by_id(self, resource_group): + response = self.client.policy_assignments.delete_by_id( + policy_assignment_id="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_create_by_id(self, resource_group): + response = self.client.policy_assignments.create_by_id( + policy_assignment_id="str", + parameters={ + "definitionVersion": "str", + "description": "str", + "displayName": "str", + "effectiveDefinitionVersion": "str", + "enforcementMode": "Default", + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "latestDefinitionVersion": "str", + "location": "str", + "metadata": {}, + "name": "str", + "nonComplianceMessages": [{"message": "str", "policyDefinitionReferenceId": "str"}], + "notScopes": ["str"], + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "parameters": {"str": {"value": {}}}, + "policyDefinitionId": "str", + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + "scope": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_get_by_id(self, resource_group): + response = self.client.policy_assignments.get_by_id( + policy_assignment_id="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_update_by_id(self, resource_group): + response = self.client.policy_assignments.update_by_id( + policy_assignment_id="str", + parameters={ + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "location": "str", + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations_async.py new file mode 100644 index 000000000000..4dc457727160 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_assignments_operations_async.py @@ -0,0 +1,257 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyAssignmentsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_delete(self, resource_group): + response = await self.client.policy_assignments.delete( + scope="str", + policy_assignment_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_create(self, resource_group): + response = await self.client.policy_assignments.create( + scope="str", + policy_assignment_name="str", + parameters={ + "definitionVersion": "str", + "description": "str", + "displayName": "str", + "effectiveDefinitionVersion": "str", + "enforcementMode": "Default", + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "latestDefinitionVersion": "str", + "location": "str", + "metadata": {}, + "name": "str", + "nonComplianceMessages": [{"message": "str", "policyDefinitionReferenceId": "str"}], + "notScopes": ["str"], + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "parameters": {"str": {"value": {}}}, + "policyDefinitionId": "str", + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + "scope": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_get(self, resource_group): + response = await self.client.policy_assignments.get( + scope="str", + policy_assignment_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_update(self, resource_group): + response = await self.client.policy_assignments.update( + scope="str", + policy_assignment_name="str", + parameters={ + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "location": "str", + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_list_for_resource_group(self, resource_group): + response = self.client.policy_assignments.list_for_resource_group( + resource_group_name=resource_group.name, + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_list_for_resource(self, resource_group): + response = self.client.policy_assignments.list_for_resource( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_list_for_management_group(self, resource_group): + response = self.client.policy_assignments.list_for_management_group( + management_group_id="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_list(self, resource_group): + response = self.client.policy_assignments.list( + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_delete_by_id(self, resource_group): + response = await self.client.policy_assignments.delete_by_id( + policy_assignment_id="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_create_by_id(self, resource_group): + response = await self.client.policy_assignments.create_by_id( + policy_assignment_id="str", + parameters={ + "definitionVersion": "str", + "description": "str", + "displayName": "str", + "effectiveDefinitionVersion": "str", + "enforcementMode": "Default", + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "latestDefinitionVersion": "str", + "location": "str", + "metadata": {}, + "name": "str", + "nonComplianceMessages": [{"message": "str", "policyDefinitionReferenceId": "str"}], + "notScopes": ["str"], + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "parameters": {"str": {"value": {}}}, + "policyDefinitionId": "str", + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + "scope": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_get_by_id(self, resource_group): + response = await self.client.policy_assignments.get_by_id( + policy_assignment_id="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_update_by_id(self, resource_group): + response = await self.client.policy_assignments.update_by_id( + policy_assignment_id="str", + parameters={ + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "location": "str", + "overrides": [ + {"kind": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}], "value": "str"} + ], + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations.py new file mode 100644 index 000000000000..784e7081ae10 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations.py @@ -0,0 +1,239 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyDefinitionVersionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_all_builtins(self, resource_group): + response = self.client.policy_definition_versions.list_all_builtins( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_all_at_management_group(self, resource_group): + response = self.client.policy_definition_versions.list_all_at_management_group( + management_group_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_all(self, resource_group): + response = self.client.policy_definition_versions.list_all( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_create_or_update(self, resource_group): + response = self.client.policy_definition_versions.create_or_update( + policy_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_delete(self, resource_group): + response = self.client.policy_definition_versions.delete( + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_get(self, resource_group): + response = self.client.policy_definition_versions.get( + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_get_built_in(self, resource_group): + response = self.client.policy_definition_versions.get_built_in( + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_create_or_update_at_management_group(self, resource_group): + response = self.client.policy_definition_versions.create_or_update_at_management_group( + management_group_name="str", + policy_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_delete_at_management_group(self, resource_group): + response = self.client.policy_definition_versions.delete_at_management_group( + management_group_name="str", + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_get_at_management_group(self, resource_group): + response = self.client.policy_definition_versions.get_at_management_group( + management_group_name="str", + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list(self, resource_group): + response = self.client.policy_definition_versions.list( + policy_definition_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_built_in(self, resource_group): + response = self.client.policy_definition_versions.list_built_in( + policy_definition_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_by_management_group(self, resource_group): + response = self.client.policy_definition_versions.list_by_management_group( + management_group_name="str", + policy_definition_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations_async.py new file mode 100644 index 000000000000..24f06e299437 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definition_versions_operations_async.py @@ -0,0 +1,240 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyDefinitionVersionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_all_builtins(self, resource_group): + response = await self.client.policy_definition_versions.list_all_builtins( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_all_at_management_group(self, resource_group): + response = await self.client.policy_definition_versions.list_all_at_management_group( + management_group_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_all(self, resource_group): + response = await self.client.policy_definition_versions.list_all( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_create_or_update(self, resource_group): + response = await self.client.policy_definition_versions.create_or_update( + policy_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_delete(self, resource_group): + response = await self.client.policy_definition_versions.delete( + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_get(self, resource_group): + response = await self.client.policy_definition_versions.get( + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_get_built_in(self, resource_group): + response = await self.client.policy_definition_versions.get_built_in( + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_create_or_update_at_management_group(self, resource_group): + response = await self.client.policy_definition_versions.create_or_update_at_management_group( + management_group_name="str", + policy_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_delete_at_management_group(self, resource_group): + response = await self.client.policy_definition_versions.delete_at_management_group( + management_group_name="str", + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_get_at_management_group(self, resource_group): + response = await self.client.policy_definition_versions.get_at_management_group( + management_group_name="str", + policy_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list(self, resource_group): + response = self.client.policy_definition_versions.list( + policy_definition_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_built_in(self, resource_group): + response = self.client.policy_definition_versions.list_built_in( + policy_definition_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_by_management_group(self, resource_group): + response = self.client.policy_definition_versions.list_by_management_group( + management_group_name="str", + policy_definition_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations.py new file mode 100644 index 000000000000..2b1965134aa6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations.py @@ -0,0 +1,200 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyDefinitionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_create_or_update(self, resource_group): + response = self.client.policy_definitions.create_or_update( + policy_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_delete(self, resource_group): + response = self.client.policy_definitions.delete( + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_get(self, resource_group): + response = self.client.policy_definitions.get( + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_get_built_in(self, resource_group): + response = self.client.policy_definitions.get_built_in( + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_create_or_update_at_management_group(self, resource_group): + response = self.client.policy_definitions.create_or_update_at_management_group( + management_group_id="str", + policy_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_delete_at_management_group(self, resource_group): + response = self.client.policy_definitions.delete_at_management_group( + management_group_id="str", + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_get_at_management_group(self, resource_group): + response = self.client.policy_definitions.get_at_management_group( + management_group_id="str", + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_list(self, resource_group): + response = self.client.policy_definitions.list( + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_list_built_in(self, resource_group): + response = self.client.policy_definitions.list_built_in( + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_list_by_management_group(self, resource_group): + response = self.client.policy_definitions.list_by_management_group( + management_group_id="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations_async.py new file mode 100644 index 000000000000..bbec542c33e9 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_definitions_operations_async.py @@ -0,0 +1,201 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_create_or_update(self, resource_group): + response = await self.client.policy_definitions.create_or_update( + policy_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_delete(self, resource_group): + response = await self.client.policy_definitions.delete( + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_get(self, resource_group): + response = await self.client.policy_definitions.get( + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_get_built_in(self, resource_group): + response = await self.client.policy_definitions.get_built_in( + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_create_or_update_at_management_group(self, resource_group): + response = await self.client.policy_definitions.create_or_update_at_management_group( + management_group_id="str", + policy_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "mode": "Indexed", + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyRule": {}, + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_delete_at_management_group(self, resource_group): + response = await self.client.policy_definitions.delete_at_management_group( + management_group_id="str", + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_get_at_management_group(self, resource_group): + response = await self.client.policy_definitions.get_at_management_group( + management_group_id="str", + policy_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_list(self, resource_group): + response = self.client.policy_definitions.list( + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_list_built_in(self, resource_group): + response = self.client.policy_definitions.list_built_in( + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_list_by_management_group(self, resource_group): + response = self.client.policy_definitions.list_by_management_group( + management_group_id="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations.py new file mode 100644 index 000000000000..cfaf494b118a --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations.py @@ -0,0 +1,140 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyExemptionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_delete(self, resource_group): + response = self.client.policy_exemptions.delete( + scope="str", + policy_exemption_name="str", + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_create_or_update(self, resource_group): + response = self.client.policy_exemptions.create_or_update( + scope="str", + policy_exemption_name="str", + parameters={ + "exemptionCategory": "str", + "policyAssignmentId": "str", + "assignmentScopeValidation": "str", + "description": "str", + "displayName": "str", + "expiresOn": "2020-02-20 00:00:00", + "id": "str", + "metadata": {}, + "name": "str", + "policyDefinitionReferenceIds": ["str"], + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_get(self, resource_group): + response = self.client.policy_exemptions.get( + scope="str", + policy_exemption_name="str", + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_update(self, resource_group): + response = self.client.policy_exemptions.update( + scope="str", + policy_exemption_name="str", + parameters={ + "assignmentScopeValidation": "str", + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + }, + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_list(self, resource_group): + response = self.client.policy_exemptions.list( + api_version="2022-07-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_list_for_resource_group(self, resource_group): + response = self.client.policy_exemptions.list_for_resource_group( + resource_group_name=resource_group.name, + api_version="2022-07-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_list_for_resource(self, resource_group): + response = self.client.policy_exemptions.list_for_resource( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + api_version="2022-07-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_list_for_management_group(self, resource_group): + response = self.client.policy_exemptions.list_for_management_group( + management_group_id="str", + api_version="2022-07-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations_async.py new file mode 100644 index 000000000000..7960bd6eb74c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_exemptions_operations_async.py @@ -0,0 +1,141 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicyExemptionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_delete(self, resource_group): + response = await self.client.policy_exemptions.delete( + scope="str", + policy_exemption_name="str", + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_create_or_update(self, resource_group): + response = await self.client.policy_exemptions.create_or_update( + scope="str", + policy_exemption_name="str", + parameters={ + "exemptionCategory": "str", + "policyAssignmentId": "str", + "assignmentScopeValidation": "str", + "description": "str", + "displayName": "str", + "expiresOn": "2020-02-20 00:00:00", + "id": "str", + "metadata": {}, + "name": "str", + "policyDefinitionReferenceIds": ["str"], + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_get(self, resource_group): + response = await self.client.policy_exemptions.get( + scope="str", + policy_exemption_name="str", + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_update(self, resource_group): + response = await self.client.policy_exemptions.update( + scope="str", + policy_exemption_name="str", + parameters={ + "assignmentScopeValidation": "str", + "resourceSelectors": [{"name": "str", "selectors": [{"in": ["str"], "kind": "str", "notIn": ["str"]}]}], + }, + api_version="2022-07-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_list(self, resource_group): + response = self.client.policy_exemptions.list( + api_version="2022-07-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_list_for_resource_group(self, resource_group): + response = self.client.policy_exemptions.list_for_resource_group( + resource_group_name=resource_group.name, + api_version="2022-07-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_list_for_resource(self, resource_group): + response = self.client.policy_exemptions.list_for_resource( + resource_group_name=resource_group.name, + resource_provider_namespace="str", + parent_resource_path="str", + resource_type="str", + resource_name="str", + api_version="2022-07-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_list_for_management_group(self, resource_group): + response = self.client.policy_exemptions.list_for_management_group( + management_group_id="str", + api_version="2022-07-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations.py new file mode 100644 index 000000000000..62b7d7194bf4 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations.py @@ -0,0 +1,275 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicySetDefinitionVersionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list_all_builtins(self, resource_group): + response = self.client.policy_set_definition_versions.list_all_builtins( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list_all_at_management_group(self, resource_group): + response = self.client.policy_set_definition_versions.list_all_at_management_group( + management_group_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list_all(self, resource_group): + response = self.client.policy_set_definition_versions.list_all( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_create_or_update(self, resource_group): + response = self.client.policy_set_definition_versions.create_or_update( + policy_set_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_delete(self, resource_group): + response = self.client.policy_set_definition_versions.delete( + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_get(self, resource_group): + response = self.client.policy_set_definition_versions.get( + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_get_built_in(self, resource_group): + response = self.client.policy_set_definition_versions.get_built_in( + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list(self, resource_group): + response = self.client.policy_set_definition_versions.list( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list_built_in(self, resource_group): + response = self.client.policy_set_definition_versions.list_built_in( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_create_or_update_at_management_group(self, resource_group): + response = self.client.policy_set_definition_versions.create_or_update_at_management_group( + management_group_name="str", + policy_set_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_delete_at_management_group(self, resource_group): + response = self.client.policy_set_definition_versions.delete_at_management_group( + management_group_name="str", + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_get_at_management_group(self, resource_group): + response = self.client.policy_set_definition_versions.get_at_management_group( + management_group_name="str", + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list_by_management_group(self, resource_group): + response = self.client.policy_set_definition_versions.list_by_management_group( + management_group_name="str", + policy_set_definition_name="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations_async.py new file mode 100644 index 000000000000..8bcf4cb39fb2 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definition_versions_operations_async.py @@ -0,0 +1,276 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicySetDefinitionVersionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list_all_builtins(self, resource_group): + response = await self.client.policy_set_definition_versions.list_all_builtins( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list_all_at_management_group(self, resource_group): + response = await self.client.policy_set_definition_versions.list_all_at_management_group( + management_group_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list_all(self, resource_group): + response = await self.client.policy_set_definition_versions.list_all( + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_create_or_update(self, resource_group): + response = await self.client.policy_set_definition_versions.create_or_update( + policy_set_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_delete(self, resource_group): + response = await self.client.policy_set_definition_versions.delete( + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_get(self, resource_group): + response = await self.client.policy_set_definition_versions.get( + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_get_built_in(self, resource_group): + response = await self.client.policy_set_definition_versions.get_built_in( + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list(self, resource_group): + response = self.client.policy_set_definition_versions.list( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list_built_in(self, resource_group): + response = self.client.policy_set_definition_versions.list_built_in( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_create_or_update_at_management_group(self, resource_group): + response = await self.client.policy_set_definition_versions.create_or_update_at_management_group( + management_group_name="str", + policy_set_definition_name="str", + policy_definition_version="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_delete_at_management_group(self, resource_group): + response = await self.client.policy_set_definition_versions.delete_at_management_group( + management_group_name="str", + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_get_at_management_group(self, resource_group): + response = await self.client.policy_set_definition_versions.get_at_management_group( + management_group_name="str", + policy_set_definition_name="str", + policy_definition_version="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list_by_management_group(self, resource_group): + response = self.client.policy_set_definition_versions.list_by_management_group( + management_group_name="str", + policy_set_definition_name="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations.py new file mode 100644 index 000000000000..640d2c73344f --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations.py @@ -0,0 +1,236 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicySetDefinitionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_create_or_update(self, resource_group): + response = self.client.policy_set_definitions.create_or_update( + policy_set_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_delete(self, resource_group): + response = self.client.policy_set_definitions.delete( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_get(self, resource_group): + response = self.client.policy_set_definitions.get( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_get_built_in(self, resource_group): + response = self.client.policy_set_definitions.get_built_in( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_list(self, resource_group): + response = self.client.policy_set_definitions.list( + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_list_built_in(self, resource_group): + response = self.client.policy_set_definitions.list_built_in( + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_create_or_update_at_management_group(self, resource_group): + response = self.client.policy_set_definitions.create_or_update_at_management_group( + management_group_id="str", + policy_set_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_delete_at_management_group(self, resource_group): + response = self.client.policy_set_definitions.delete_at_management_group( + management_group_id="str", + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_get_at_management_group(self, resource_group): + response = self.client.policy_set_definitions.get_at_management_group( + management_group_id="str", + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_list_by_management_group(self, resource_group): + response = self.client.policy_set_definitions.list_by_management_group( + management_group_id="str", + api_version="2023-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations_async.py new file mode 100644 index 000000000000..f1fdf201e272 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_policy_set_definitions_operations_async.py @@ -0,0 +1,237 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyPolicySetDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_create_or_update(self, resource_group): + response = await self.client.policy_set_definitions.create_or_update( + policy_set_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_delete(self, resource_group): + response = await self.client.policy_set_definitions.delete( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_get(self, resource_group): + response = await self.client.policy_set_definitions.get( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_get_built_in(self, resource_group): + response = await self.client.policy_set_definitions.get_built_in( + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_list(self, resource_group): + response = self.client.policy_set_definitions.list( + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_list_built_in(self, resource_group): + response = self.client.policy_set_definitions.list_built_in( + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_create_or_update_at_management_group(self, resource_group): + response = await self.client.policy_set_definitions.create_or_update_at_management_group( + management_group_id="str", + policy_set_definition_name="str", + parameters={ + "description": "str", + "displayName": "str", + "id": "str", + "metadata": {}, + "name": "str", + "parameters": { + "str": { + "allowedValues": [{}], + "defaultValue": {}, + "metadata": { + "assignPermissions": bool, + "description": "str", + "displayName": "str", + "strongType": "str", + }, + "schema": {}, + "type": "str", + } + }, + "policyDefinitionGroups": [ + { + "name": "str", + "additionalMetadataId": "str", + "category": "str", + "description": "str", + "displayName": "str", + } + ], + "policyDefinitions": [ + { + "policyDefinitionId": "str", + "definitionVersion": "str", + "effectiveDefinitionVersion": "str", + "groupNames": ["str"], + "latestDefinitionVersion": "str", + "parameters": {"str": {"value": {}}}, + "policyDefinitionReferenceId": "str", + } + ], + "policyType": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + "version": "str", + "versions": ["str"], + }, + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_delete_at_management_group(self, resource_group): + response = await self.client.policy_set_definitions.delete_at_management_group( + management_group_id="str", + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_get_at_management_group(self, resource_group): + response = await self.client.policy_set_definitions.get_at_management_group( + management_group_id="str", + policy_set_definition_name="str", + api_version="2023-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_list_by_management_group(self, resource_group): + response = self.client.policy_set_definitions.list_by_management_group( + management_group_id="str", + api_version="2023-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations.py new file mode 100644 index 000000000000..e09d26b19c57 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations.py @@ -0,0 +1,145 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyVariableValuesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_delete(self, resource_group): + response = self.client.variable_values.delete( + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_create_or_update(self, resource_group): + response = self.client.variable_values.create_or_update( + variable_name="str", + variable_value_name="str", + parameters={ + "values": [{"columnName": "str", "columnValue": {}}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_get(self, resource_group): + response = self.client.variable_values.get( + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_list(self, resource_group): + response = self.client.variable_values.list( + variable_name="str", + api_version="2022-08-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_list_for_management_group(self, resource_group): + response = self.client.variable_values.list_for_management_group( + management_group_id="str", + variable_name="str", + api_version="2022-08-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_delete_at_management_group(self, resource_group): + response = self.client.variable_values.delete_at_management_group( + management_group_id="str", + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_create_or_update_at_management_group(self, resource_group): + response = self.client.variable_values.create_or_update_at_management_group( + management_group_id="str", + variable_name="str", + variable_value_name="str", + parameters={ + "values": [{"columnName": "str", "columnValue": {}}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variable_values_get_at_management_group(self, resource_group): + response = self.client.variable_values.get_at_management_group( + management_group_id="str", + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations_async.py new file mode 100644 index 000000000000..a7bbd7e294fc --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variable_values_operations_async.py @@ -0,0 +1,146 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyVariableValuesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_delete(self, resource_group): + response = await self.client.variable_values.delete( + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_create_or_update(self, resource_group): + response = await self.client.variable_values.create_or_update( + variable_name="str", + variable_value_name="str", + parameters={ + "values": [{"columnName": "str", "columnValue": {}}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_get(self, resource_group): + response = await self.client.variable_values.get( + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_list(self, resource_group): + response = self.client.variable_values.list( + variable_name="str", + api_version="2022-08-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_list_for_management_group(self, resource_group): + response = self.client.variable_values.list_for_management_group( + management_group_id="str", + variable_name="str", + api_version="2022-08-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_delete_at_management_group(self, resource_group): + response = await self.client.variable_values.delete_at_management_group( + management_group_id="str", + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_create_or_update_at_management_group(self, resource_group): + response = await self.client.variable_values.create_or_update_at_management_group( + management_group_id="str", + variable_name="str", + variable_value_name="str", + parameters={ + "values": [{"columnName": "str", "columnValue": {}}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variable_values_get_at_management_group(self, resource_group): + response = await self.client.variable_values.get_at_management_group( + management_group_id="str", + variable_name="str", + variable_value_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations.py new file mode 100644 index 000000000000..19f865cb0853 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations.py @@ -0,0 +1,137 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyVariablesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_delete(self, resource_group): + response = self.client.variables.delete( + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_create_or_update(self, resource_group): + response = self.client.variables.create_or_update( + variable_name="str", + parameters={ + "columns": [{"columnName": "str"}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_get(self, resource_group): + response = self.client.variables.get( + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_delete_at_management_group(self, resource_group): + response = self.client.variables.delete_at_management_group( + management_group_id="str", + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_create_or_update_at_management_group(self, resource_group): + response = self.client.variables.create_or_update_at_management_group( + management_group_id="str", + variable_name="str", + parameters={ + "columns": [{"columnName": "str"}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_get_at_management_group(self, resource_group): + response = self.client.variables.get_at_management_group( + management_group_id="str", + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_list(self, resource_group): + response = self.client.variables.list( + api_version="2022-08-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_list_for_management_group(self, resource_group): + response = self.client.variables.list_for_management_group( + management_group_id="str", + api_version="2022-08-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations_async.py b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations_async.py new file mode 100644 index 000000000000..df7d9ca1d591 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/generated_tests/test_policy_variables_operations_async.py @@ -0,0 +1,138 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestPolicyVariablesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_delete(self, resource_group): + response = await self.client.variables.delete( + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_create_or_update(self, resource_group): + response = await self.client.variables.create_or_update( + variable_name="str", + parameters={ + "columns": [{"columnName": "str"}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_get(self, resource_group): + response = await self.client.variables.get( + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_delete_at_management_group(self, resource_group): + response = await self.client.variables.delete_at_management_group( + management_group_id="str", + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_create_or_update_at_management_group(self, resource_group): + response = await self.client.variables.create_or_update_at_management_group( + management_group_id="str", + variable_name="str", + parameters={ + "columns": [{"columnName": "str"}], + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_get_at_management_group(self, resource_group): + response = await self.client.variables.get_at_management_group( + management_group_id="str", + variable_name="str", + api_version="2022-08-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_list(self, resource_group): + response = self.client.variables.list( + api_version="2022-08-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_list_for_management_group(self, resource_group): + response = self.client.variables.list_for_management_group( + management_group_id="str", + api_version="2022-08-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/resources/azure-mgmt-resource-policy/pyproject.toml b/sdk/resources/azure-mgmt-resource-policy/pyproject.toml new file mode 100644 index 000000000000..ff0ca2bde3e1 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/pyproject.toml @@ -0,0 +1,87 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-resource-policy" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Policy Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.resource.policy._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", + "azure.mgmt.resource", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + +[tool.azure-sdk-build] +breaking = false +pyright = false +mypy = false + +[packaging] +package_name = "azure-mgmt-resource-policy" +package_nspkg = "azure-mgmt-resource-nspkg" +package_pprint_name = "Resource Policy Management" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" +title = "PolicyClient" diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/conftest.py b/sdk/resources/azure-mgmt-resource-policy/tests/conftest.py new file mode 100644 index 000000000000..e95ee7df4d34 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + policy_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + policy_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + policy_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + policy_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=policy_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_async_test.py new file mode 100644 index 000000000000..e1034e05a9e4 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyDataPolicyManifestsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_data_policy_manifests_list(self, resource_group): + response = self.client.data_policy_manifests.list() + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_test.py new file mode 100644 index 000000000000..4bd2212ec9d2 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_data_policy_manifests_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyDataPolicyManifestsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_data_policy_manifests_list(self, resource_group): + response = self.client.data_policy_manifests.list() + result = [r for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_async_test.py new file mode 100644 index 000000000000..9a8da64bdf27 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_async_test.py @@ -0,0 +1,36 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyAssignmentsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_list_for_resource_group(self, resource_group): + response = self.client.policy_assignments.list_for_resource_group( + resource_group_name=resource_group.name, + ) + result = [r async for r in response] + assert result + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_assignments_list(self, resource_group): + response = self.client.policy_assignments.list() + result = [r async for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_test.py new file mode 100644 index 000000000000..861288ebd0b6 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_assignments_operations_test.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyAssignmentsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_list_for_resource_group(self, resource_group): + response = self.client.policy_assignments.list_for_resource_group( + resource_group_name=resource_group.name, + ) + result = [r for r in response] + assert result + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_assignments_list(self, resource_group): + response = self.client.policy_assignments.list() + result = [r for r in response] + assert result diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_async_test.py new file mode 100644 index 000000000000..6b887d662066 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_async_test.py @@ -0,0 +1,34 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyDefinitionVersionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_all_builtins(self, resource_group): + response = await self.client.policy_definition_versions.list_all_builtins() + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definition_versions_list_all(self, resource_group): + response = await self.client.policy_definition_versions.list_all() + + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_test.py new file mode 100644 index 000000000000..3dcbfa780bc5 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definition_versions_operations_test.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyDefinitionVersionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_all_builtins(self, resource_group): + response = self.client.policy_definition_versions.list_all_builtins() + + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definition_versions_list_all(self, resource_group): + response = self.client.policy_definition_versions.list_all() + + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_async_test.py new file mode 100644 index 000000000000..32d331e6880d --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_async_test.py @@ -0,0 +1,34 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_list(self, resource_group): + response = self.client.policy_definitions.list() + result = [r async for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_definitions_list_built_in(self, resource_group): + response = self.client.policy_definitions.list_built_in() + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_test.py new file mode 100644 index 000000000000..93ec578d34c9 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_definitions_operations_test.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyDefinitionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_list(self, resource_group): + response = self.client.policy_definitions.list() + result = [r for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_definitions_list_built_in(self, resource_group): + response = self.client.policy_definitions.list_built_in() + result = [r for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_async_test.py new file mode 100644 index 000000000000..dc2337c35ac7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_async_test.py @@ -0,0 +1,36 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyExemptionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_list(self, resource_group): + response = self.client.policy_exemptions.list() + result = [r async for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_exemptions_list_for_resource_group(self, resource_group): + response = self.client.policy_exemptions.list_for_resource_group( + resource_group_name=resource_group.name, + ) + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_test.py new file mode 100644 index 000000000000..3d078607ddfc --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_exemptions_operations_test.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicyExemptionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_list(self, resource_group): + response = self.client.policy_exemptions.list() + result = [r for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_exemptions_list_for_resource_group(self, resource_group): + response = self.client.policy_exemptions.list_for_resource_group( + resource_group_name=resource_group.name, + ) + result = [r for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_async_test.py new file mode 100644 index 000000000000..ea1f58d602ee --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicySetDefinitionVersionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definition_versions_list_all(self, resource_group): + response = await self.client.policy_set_definition_versions.list_all() + + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_test.py new file mode 100644 index 000000000000..aa04e847393c --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definition_versions_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicySetDefinitionVersionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definition_versions_list_all(self, resource_group): + response = self.client.policy_set_definition_versions.list_all() + + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_async_test.py new file mode 100644 index 000000000000..d86dc3a171c7 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_async_test.py @@ -0,0 +1,34 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicySetDefinitionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_list(self, resource_group): + response = self.client.policy_set_definitions.list() + result = [r async for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_policy_set_definitions_list_built_in(self, resource_group): + response = self.client.policy_set_definitions.list_built_in() + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_test.py new file mode 100644 index 000000000000..7db6084261de --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_policy_set_definitions_operations_test.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyPolicySetDefinitionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_list(self, resource_group): + response = self.client.policy_set_definitions.list() + result = [r for r in response] + assert response + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_policy_set_definitions_list_built_in(self, resource_group): + response = self.client.policy_set_definitions.list_built_in() + result = [r for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_async_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_async_test.py new file mode 100644 index 000000000000..9682e9c9c549 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_async_test.py @@ -0,0 +1,27 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy.aio import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyVariablesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_variables_list(self, resource_group): + response = self.client.variables.list() + result = [r async for r in response] + assert response diff --git a/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_test.py b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_test.py new file mode 100644 index 000000000000..e70731415786 --- /dev/null +++ b/sdk/resources/azure-mgmt-resource-policy/tests/test_policy_variables_operations_test.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.resource.policy import PolicyClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestPolicyVariablesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(PolicyClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_variables_list(self, resource_group): + response = self.client.variables.list() + result = [r for r in response] + assert response