def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" LOCK_NAME = "locktestx" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ lock_client = ManagementLockClient(credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create resource lock lock = lock_client.management_locks.create_or_update_at_resource_group_level( GROUP_NAME, LOCK_NAME, {"level": "CanNotDelete"}) print("Create lock: {}".format(lock)) # Get lock lock = lock_client.management_locks.get_at_resource_group_level( GROUP_NAME, LOCK_NAME) print("Get lock: {}".format(lock)) # Delete lock lock_client.management_locks.delete_at_resource_group_level( GROUP_NAME, LOCK_NAME) print("Delete lock.") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" NAMESPACE_NAME = "namespacex" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) eventhub_client = EventHubManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create Namespace namesapce = eventhub_client.namespaces.begin_create_or_update( GROUP_NAME, NAMESPACE_NAME, { "sku": { "name": "Standard", "tier": "Standard" }, "location": "eastus", "tags": { "tag1": "value1", "tag2": "value2" } }).result() print("Create Namespace: {}".format(namesapce)) # Get Namesapce namespace = eventhub_client.namespaces.get(GROUP_NAME, NAMESPACE_NAME) print("Get Namespace: {}".format(namespace)) # Update Namespace namespace = eventhub_client.namespaces.update(GROUP_NAME, NAMESPACE_NAME, { "location": "eastus", "tags": { "tag3": "value3", "tag4": "value4" } }) print("Update Namespace: {}".format(namesapce)) # Delete Namespace eventhub_client.namespaces.begin_delete(GROUP_NAME, NAMESPACE_NAME).result() print("Delete Namespace.") # Delete resource group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" CONFIG_STORE_NAME = "configstorexyz" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ appconfig_client = AppConfigurationManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create appconfiguration store appconfig_store = appconfig_client.configuration_stores.begin_create( GROUP_NAME, CONFIG_STORE_NAME, { "location": "eastus", "sku": { "name": "Standard" } }).result() print("Create appconfigruation store:\n{}".format(appconfig_store)) # Get appconfiguration store appconfig_store = appconfig_client.configuration_stores.get( GROUP_NAME, CONFIG_STORE_NAME) print("Get appconfigruation store:\n{}".format(appconfig_store)) # Update appconfiguration store appconfig_store = appconfig_client.configuration_stores.begin_update( GROUP_NAME, CONFIG_STORE_NAME, { "tags": { "category": "Marketing" }, "sku": { "name": "Standard" } }).result() print("Update appconfigruation store:\n{}".format(appconfig_store)) # Delete appconfiguration store appconfig_client.configuration_stores.begin_delete( GROUP_NAME, CONFIG_STORE_NAME).result() print("Delete appconfiguration store") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" PROXIMITY_PLACEMENT_GROUP_NAME = "proximityplacementgroup" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) compute_client = ComputeManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create proximity placement group proximity_placement_group = compute_client.proximity_placement_groups.create_or_update( GROUP_NAME, PROXIMITY_PLACEMENT_GROUP_NAME, { "location": "eastus", "proximity_placement_group_type": "Standard" }) print("Create proximity placement group:\n{}".format( proximity_placement_group)) # Get proximity placement group proximity_placement_group = compute_client.proximity_placement_groups.get( GROUP_NAME, PROXIMITY_PLACEMENT_GROUP_NAME) print( "Get proximity placement group:\n{}".format(proximity_placement_group)) # Update proximity placement group proximity_placement_group = compute_client.proximity_placement_groups.update( GROUP_NAME, PROXIMITY_PLACEMENT_GROUP_NAME, { "location": "eastus", "proximity_placement_group_type": "Standard" }) print("Update proximity placement group:\n{}".format( proximity_placement_group)) # Delete proximity placement group compute_client.proximity_placement_groups.delete( GROUP_NAME, PROXIMITY_PLACEMENT_GROUP_NAME) print("Delete proximity placement group.\n") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) TAG_NAME = "tagxyz" TAG_VALUE = "value1" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create tag tag = resource_client.tags.create_or_update(TAG_NAME) print("Create tag:\n{}".format(tag)) # Create tag value tag = resource_client.tags.create_or_update_value(TAG_NAME, TAG_VALUE) print("Create tag value:\n{}".format(tag)) # Get at scope scope = "subscriptions/" + SUBSCRIPTION_ID tag = resource_client.tags.get_at_scope(scope) print("Get tag:\n{}".format(tag)) # Delete tag value resource_client.tags.delete_value(TAG_NAME, TAG_VALUE) print("Delete tag value:\n") # Delete tag tag = resource_client.tags.delete(TAG_NAME) print("Delete tag.\n")
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" AVAILABILITY_SET_NAME = "availabilityset" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) compute_client = ComputeManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create availability set availability_set = compute_client.availability_sets.create_or_update( GROUP_NAME, AVAILABILITY_SET_NAME, { "location": "eastus", "platform_fault_domain_count": "2", "platform_update_domain_count": "20" }) print("Create availability set:\n{}".format(availability_set)) # Get availability set availability_set = compute_client.availability_sets.get( GROUP_NAME, AVAILABILITY_SET_NAME) print("Get availability set:\n{}".format(availability_set)) # Update availability set availability_set = compute_client.availability_sets.update( GROUP_NAME, AVAILABILITY_SET_NAME, { "platform_fault_domain_count": "2", "platform_update_domain_count": "20" }) print("Update availability set:\n{}".format(availability_set)) # Delete availability set compute_client.availability_sets.delete(GROUP_NAME, AVAILABILITY_SET_NAME) print("Delete availability set.\n") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) # Check resource group existence result_check = resource_client.resource_groups.check_existence( GROUP_NAME ) print("Whether resource group exists:\n{}".format(result_check)) # Create resource group resource_group = resource_client.resource_groups.create_or_update( GROUP_NAME, {"location": "eastus"} ) print("Create resource group:\n{}".format(resource_group)) # Get resource group resource_group = resource_client.resource_groups.get( GROUP_NAME ) print("Get resource group:\n{}".format(resource_group)) # Update resource group resource_group = resource_client.resource_groups.update( GROUP_NAME, { "tags":{ "tag1": "valueA", "tag2": "valueB" } } ) print("Update resource group:\n{}".format(resource_group)) # Delete Group resource_client.resource_groups.begin_delete( GROUP_NAME ).result() print("Delete resource group.\n")
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" IDENTITY_NAME = "uai" SCRIPT_NAME = "scriptxx" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) script_client = DeploymentScriptsClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) msi_client = ManagedServiceIdentityClient( credentials=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) # Create resource group resource_client.resource_groups.create_or_update( GROUP_NAME, {"location": "eastus"} ) # Create identity msi_client.user_assigned_identities.create_or_update( GROUP_NAME, IDENTITY_NAME, "westus", {"key1": "value1"} ) # Create script # azure.core.exceptions.HttpResponseError: Operation returned an invalid status 'OK' script_client.deployment_scripts.begin_create( GROUP_NAME, SCRIPT_NAME, { "kind": "AzurePowerShell", "location": "westus", "identity": { "type": "UserAssigned", "user_assigned_identities": { "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + GROUP_NAME + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities/" + IDENTITY_NAME: {} } }, "azPowerShellVersion": "3.0", "scriptContent": "Param([string]$Location,[string]$Name) $deploymentScriptOutputs['test'] = 'value' Get-AzResourceGroup -Location $Location -Name $Name", "arguments": "-Location 'westus' -Name \"*rg2\"", "retentionInterval": "P7D", "timeout": "PT1H", "cleanupPreference": "Always" } ).result() print("Create script.\n") # Update script script = script_client.deployment_scripts.update( GROUP_NAME, SCRIPT_NAME, { "tags": {"key1": "value1"} } ) print("Update script:\n{}".format(script)) # Get script script = script_client.deployment_scripts.get( GROUP_NAME, SCRIPT_NAME ) print("Get script:\n{}".format(script)) # Get script logs script_logs = script_client.deployment_scripts.get_logs( GROUP_NAME, SCRIPT_NAME ) print("Get script logs:\n{}".format(script_logs)) # Delete script script_client.deployment_scripts.delete( GROUP_NAME, SCRIPT_NAME ) print("Delete script.\n") # Delete Group resource_client.resource_groups.begin_delete( GROUP_NAME ).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" RESOURCE_1 = "resource1" RESOURCE_2 = "resource2" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) link_client = ManagementLinkClient(credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create resource 1 resource_1 = resource_client.resources.begin_create_or_update( resource_group_name=GROUP_NAME, resource_provider_namespace="Microsoft.Compute", parent_resource_path="", resource_type="availabilitySets", resource_name=RESOURCE_1, parameters={ 'location': "eastus" }, api_version='2019-07-01').result() # Create resource 2 resource_2 = resource_client.resources.begin_create_or_update( resource_group_name=GROUP_NAME, resource_provider_namespace="Microsoft.Compute", parent_resource_path="", resource_type="availabilitySets", resource_name=RESOURCE_2, parameters={ 'location': "eastus" }, api_version='2019-07-01').result() # Create link link = link_client.resource_links.create_or_update( resource_1.id + "/providers/Microsoft.Resources/links/myLink", {"properties": { "target_id": resource_2.id, "notes": "Testing links" }}) print("Create link:\n{}".format(link)) # Get link link = link_client.resource_links.get(link.id) print("Get link:\n{}".format(link)) # Delete link link_client.resource_links.delete(link.id) print("Delete link.\n") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" RESOURCE_NAME = "pytestresource" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Check resource existence check_result = resource_client.resources.check_existence( resource_group_name=GROUP_NAME, resource_provider_namespace="Microsoft.Compute", parent_resource_path="", resource_type="availabilitySets", resource_name=RESOURCE_NAME, api_version="2019-10-01") print("Check resource existence:\n{}".format(check_result)) # Create resource resource = resource_client.resources.begin_create_or_update( resource_group_name=GROUP_NAME, resource_provider_namespace="Microsoft.Compute", parent_resource_path="", resource_type="availabilitySets", resource_name=RESOURCE_NAME, parameters={ 'location': "eastus" }, api_version="2019-07-01").result() print("Create resource:\n{}".format(resource)) # Get resource resource = resource_client.resources.get( resource_group_name=GROUP_NAME, resource_provider_namespace="Microsoft.Compute", parent_resource_path="", resource_type="availabilitySets", resource_name=RESOURCE_NAME, api_version="2019-07-01") print("Get resource:\n{}".format(resource)) # Update resource resource = resource_client.resources.begin_update( resource_group_name=GROUP_NAME, resource_provider_namespace="Microsoft.Compute", parent_resource_path="", resource_type="availabilitySets", resource_name=RESOURCE_NAME, parameters={ 'tags': { "tag1": "value1" } }, api_version="2019-07-01").result() print("Update resource:\n{}".format(resource)) # Delete resource resource_client.resources.begin_delete( resource_group_name=GROUP_NAME, resource_provider_namespace="Microsoft.Compute", parent_resource_path="", resource_type="availabilitySets", resource_name=RESOURCE_NAME, api_version="2019-07-01").result() print("Delete resource.\n") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" NETWORK_NAME = "networkx" SUBNET_NAME = "subnetx" INTERFACE_NAME = "interfacex" VMSS_NAME = "vmssxyz" AUTOSCALESETTING_NAME = "autoscalesettingx" your_password = '******' + ''.join(random.choice(string.ascii_lowercase) for i in range(8)) # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) monitor_client = MonitorClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) compute_client = ComputeManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) network_client = NetworkManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) # Create resource group resource_client.resource_groups.create_or_update( GROUP_NAME, {"location": "eastus"} ) # Create virtual network network_client.virtual_networks.begin_create_or_update( GROUP_NAME, NETWORK_NAME, { 'location': "eastus", 'address_space': { 'address_prefixes': ['10.0.0.0/16'] } } ).result() subnet = network_client.subnets.begin_create_or_update( GROUP_NAME, NETWORK_NAME, SUBNET_NAME, {'address_prefix': '10.0.0.0/24'} ).result() # Create network interface network_client.network_interfaces.begin_create_or_update( GROUP_NAME, INTERFACE_NAME, { 'location': "eastus", 'ip_configurations': [{ 'name': 'MyIpConfig', 'subnet': { 'id': subnet.id } }] } ).result() # Create vmss vmss = compute_client.virtual_machine_scale_sets.begin_create_or_update( GROUP_NAME, VMSS_NAME, { "sku": { "tier": "Standard", "capacity": "2", "name": "Standard_D1_v2" }, "location": "eastus", "overprovision": True, "virtual_machine_profile": { "storage_profile": { "image_reference": { "offer": "UbuntuServer", "publisher": "Canonical", "sku": "18.04-LTS", "version": "latest" }, "os_disk": { "caching": "ReadWrite", "managed_disk": { "storage_account_type": "Standard_LRS" }, "create_option": "FromImage", "disk_size_gb": "512" } }, "os_profile": { "computer_name_prefix": "testPC", "admin_username": "******", "admin_password": your_password }, "network_profile": { "network_interface_configurations": [ { "name": "testPC", "primary": True, "enable_ipforwarding": True, "ip_configurations": [ { "name": "testPC", "properties": { "subnet": { "id": subnet.id } } } ] } ] } }, "upgrade_policy": { "mode": "Manual" }, "upgrade_mode": "Manual" } ).result() # Create autoscale setting autoscale_setting = monitor_client.autoscale_settings.create_or_update( GROUP_NAME, AUTOSCALESETTING_NAME, { "location": "West US", "profiles": [ { "name": "adios", "capacity": { "minimum": "1", "maximum": "10", "default": "1" }, "rules": [ ] } ], "enabled": True, "target_resource_uri": vmss.id, "notifications": [ { "operation": "Scale", "email": { "send_to_subscription_administrator": True, "send_to_subscription_co_administrators": True, "custom_emails": [ "*****@*****.**", "*****@*****.**" ] }, "webhooks": [ ] } ] } ) print("Create autoscale setting:\n{}".format(autoscale_setting)) # Get autoscale setting autoscale_setting = monitor_client.autoscale_settings.get( GROUP_NAME, AUTOSCALESETTING_NAME ) # Update autoscale setting autoscale_setting = monitor_client.autoscale_settings.update( GROUP_NAME, AUTOSCALESETTING_NAME, { "location": "West US", "profiles": [ { "name": "adios", "capacity": { "minimum": "1", "maximum": "10", "default": "1" }, "rules": [ ] } ], "enabled": True, "target_resource_uri": vmss.id, "notifications": [ { "operation": "Scale", "email": { "send_to_subscription_administrator": True, "send_to_subscription_co_administrators": True, "custom_emails": [ "*****@*****.**", "*****@*****.**" ] }, "webhooks": [ ] } ] } ) print("Update autoscale setting:\n{}".format(autoscale_setting)) # Delete autoscale setting monitor_client.autoscale_settings.delete( GROUP_NAME, AUTOSCALESETTING_NAME ) print("Delete autoscale setting.\n") # Delete Group resource_client.resource_groups.begin_delete( GROUP_NAME ).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" GROUP_NAME_2 = "testgroupx2" APP_DEF_NAME = "applicationdefinition" APPLICATION_NAME = "applicationtest" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ app_client = ApplicationClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) # Create resource group resource_client.resource_groups.create_or_update( GROUP_NAME, {"location": "eastus"} ) resource_client.resource_groups.create_or_update( GROUP_NAME_2, {"location": "eastus"} ) # Create application definition app_definition = app_client.application_definitions.begin_create_or_update( GROUP_NAME, APP_DEF_NAME, { "lock_level": "None", "display_name": "myManagedApplicationDef", "description": "myManagedApplicationDef description", "authorizations": [], "package_file_uri": "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-managed-application/artifacts/ManagedAppZip/pkg.zip", "location": "East US" } ).result() print("Create application definition: {}".format(app_definition)) # Get application definition app_definition = app_client.application_definitions.get( GROUP_NAME, APP_DEF_NAME ) print("Get application definition: {}".format(app_definition)) # Create application app = app_client.applications.begin_create_or_update( GROUP_NAME, APPLICATION_NAME, { "application_definition_id": app_definition.id, "managed_resource_group_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/myManagedRG" + GROUP_NAME_2, "location": "East US", "kind": "ServiceCatalog" } ) # ).result() print("Create application: {}".format(app)) # Get application app = app_client.applications.get( GROUP_NAME, APPLICATION_NAME ) print("Get application: {}".format(app)) # Update application app = app_client.applications.update( GROUP_NAME, APPLICATION_NAME, { "managed_resource_group_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/myManagedRG" + GROUP_NAME_2, "kind": "ServiceCatalog" } ) print("Update application: {}".format(app)) # Delete application app_client.applications.begin_delete( GROUP_NAME, APPLICATION_NAME ).result() print("Delete application.") # Delete application definition app_client.application_definitions.begin_delete( GROUP_NAME, APP_DEF_NAME ).result() print("Delete appliation definition.")
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" VIRTUAL_MACHINE_NAME = "virtualmachinex" SUBNET_NAME = "subnetx" INTERFACE_NAME = "interfacex" NETWORK_NAME = "networknamex" VIRTUAL_MACHINE_EXTENSION_NAME = "virtualmachineextensionx" your_password = '******' + ''.join( random.choice(string.ascii_lowercase) for i in range(8)) # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) network_client = NetworkManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) compute_client = ComputeManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create virtual network network_client.virtual_networks.begin_create_or_update( GROUP_NAME, NETWORK_NAME, { 'location': "eastus", 'address_space': { 'address_prefixes': ['10.0.0.0/16'] } }).result() subnet = network_client.subnets.begin_create_or_update( GROUP_NAME, NETWORK_NAME, SUBNET_NAME, { 'address_prefix': '10.0.0.0/24' }).result() # Create network interface network_client.network_interfaces.begin_create_or_update( GROUP_NAME, INTERFACE_NAME, { 'location': "eastus", 'ip_configurations': [{ 'name': 'MyIpConfig', 'subnet': { 'id': subnet.id } }] }).result() # Create virtual machine vm = compute_client.virtual_machines.begin_create_or_update( GROUP_NAME, VIRTUAL_MACHINE_NAME, { "location": "eastus", "hardware_profile": { "vm_size": "Standard_D2_v2" }, "storage_profile": { "image_reference": { "sku": "2016-Datacenter", "publisher": "MicrosoftWindowsServer", "version": "latest", "offer": "WindowsServer" }, "os_disk": { "caching": "ReadWrite", "managed_disk": { "storage_account_type": "Standard_LRS" }, "name": "myVMosdisk", "create_option": "FromImage" }, "data_disks": [{ "disk_size_gb": "1023", "create_option": "Empty", "lun": "0" }, { "disk_size_gb": "1023", "create_option": "Empty", "lun": "1" }] }, "os_profile": { "admin_username": "******", "computer_name": "myVM", "admin_password": your_password, "windows_configuration": { "enable_automatic_updates": True # need automatic update for reimage } }, "network_profile": { "network_interfaces": [{ "id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + GROUP_NAME + "/providers/Microsoft.Network/networkInterfaces/" + INTERFACE_NAME + "", # "id": NIC_ID, "properties": { "primary": True } }] } }).result() print("Create virtual machine:\n{}".format(vm)) # Create vm extension extension = compute_client.virtual_machine_extensions.begin_create_or_update( GROUP_NAME, VIRTUAL_MACHINE_NAME, VIRTUAL_MACHINE_EXTENSION_NAME, { "location": "eastus", "auto_upgrade_minor_version": True, "publisher": "Microsoft.Azure.NetworkWatcher", "type_properties_type": "NetworkWatcherAgentWindows", # TODO: Is this a bug? "type_handler_version": "1.4", }).result() print("Create vm extension:\n{}".format(extension)) # Get virtual machine vm = compute_client.virtual_machines.get(GROUP_NAME, VIRTUAL_MACHINE_NAME) print("Get virtual machine:\n{}".format(vm)) # Get vm extension extension = compute_client.virtual_machine_extensions.get( GROUP_NAME, VIRTUAL_MACHINE_NAME, VIRTUAL_MACHINE_EXTENSION_NAME) print("Get vm extesnion:\n{}".format(extension)) # Update virtual machine vm = compute_client.virtual_machines.begin_update( GROUP_NAME, VIRTUAL_MACHINE_NAME, { "network_profile": { "network_interfaces": [{ "id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + GROUP_NAME + "/providers/Microsoft.Network/networkInterfaces/" + INTERFACE_NAME + "", "properties": { "primary": True } }] } }).result() print("Update virtual machine:\n{}".format(vm)) # Update vm extension extension = compute_client.virtual_machine_extensions.begin_update( GROUP_NAME, VIRTUAL_MACHINE_NAME, VIRTUAL_MACHINE_EXTENSION_NAME, { "auto_upgrade_minor_version": True, "instance_view": { "name": VIRTUAL_MACHINE_EXTENSION_NAME, "type": "CustomScriptExtension" } }).result() print("Update vm extension:\n{}".format(extension)) # Delete vm extension (Need vm started) compute_client.virtual_machines.begin_start(GROUP_NAME, VIRTUAL_MACHINE_NAME).result() compute_client.virtual_machine_extensions.begin_delete( GROUP_NAME, VIRTUAL_MACHINE_NAME, VIRTUAL_MACHINE_EXTENSION_NAME).result() print("Delete vm extension.\n") # Delete virtual machine compute_client.virtual_machines.begin_power_off( GROUP_NAME, VIRTUAL_MACHINE_NAME).result() compute_client.virtual_machines.begin_delete( GROUP_NAME, VIRTUAL_MACHINE_NAME).result() print("Delete virtual machine.\n") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" METRIC_ALERT_NAME = "metricnamexx" VM_NAME = "vm_name" NETWORK_NAME = "networkxx" SUBNET_NAME = "subnetx" INTERFACE_NAME = "interfacexx" your_password = '******' + ''.join( random.choice(string.ascii_lowercase) for i in range(8)) # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) compute_client = ComputeManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) network_client = NetworkManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) monitor_client = MonitorClient(credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create virtual network vnet = network_client.virtual_networks.begin_create_or_update( GROUP_NAME, NETWORK_NAME, { 'location': "eastus", 'address_space': { 'address_prefixes': ['10.0.0.0/16'] } }).result() subnet = network_client.subnets.begin_create_or_update( GROUP_NAME, NETWORK_NAME, SUBNET_NAME, { 'address_prefix': '10.0.0.0/24' }).result() # Create network interface interface = network_client.network_interfaces.begin_create_or_update( GROUP_NAME, INTERFACE_NAME, { 'location': "eastus", 'ip_configurations': [{ 'name': 'MyIpConfig', 'subnet': { 'id': subnet.id } }] }).result() # Create vm vm = compute_client.virtual_machines.begin_create_or_update( GROUP_NAME, VM_NAME, { "location": "eastus", "hardware_profile": { "vm_size": "Standard_D2_v2" }, "storage_profile": { "image_reference": { "sku": "2016-Datacenter", "publisher": "MicrosoftWindowsServer", "version": "latest", "offer": "WindowsServer" }, "os_disk": { "caching": "ReadWrite", "managed_disk": { "storage_account_type": "Standard_LRS" }, "name": "myVMosdisk", "create_option": "FromImage" }, "data_disks": [{ "disk_size_gb": "1023", "create_option": "Empty", "lun": "0" }, { "disk_size_gb": "1023", "create_option": "Empty", "lun": "1" }] }, "os_profile": { "admin_username": "******", "computer_name": "myVM", "admin_password": your_password, "windows_configuration": { "enable_automatic_updates": True # need automatic update for reimage } }, "network_profile": { "network_interfaces": [{ "id": interface.id, "properties": { "primary": True } }] } }).result() RESOURCE_URI = vm.id # Create metric alert metric_alert = monitor_client.metric_alerts.create_or_update( GROUP_NAME, METRIC_ALERT_NAME, { "location": "global", "description": "This is the description of the rule1", "severity": "3", "enabled": True, "scopes": [RESOURCE_URI], "evaluation_frequency": "PT1M", "window_size": "PT15M", "target_resource_type": "Microsoft.Compute/virtualMachines", "target_resource_region": "southcentralus", "criteria": { "odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria", "all_of": [{ "criterion_type": "DynamicThresholdCriterion", "name": "High_CPU_80", "metric_name": "Percentage CPU", "metric_namespace": "microsoft.compute/virtualmachines", "operator": "GreaterOrLessThan", "time_aggregation": "Average", "dimensions": [], "alert_sensitivity": "Medium", "failing_periods": { "number_of_evaluation_periods": "4", "min_failing_periods_to_alert": "4" }, }] }, "auto_mitigate": False, "actions": [] }) print("Create metric alert:\n{}".format(metric_alert)) # Get metric alert metric_alert = monitor_client.metric_alerts.get(GROUP_NAME, METRIC_ALERT_NAME) print("Get metric alert:\n{}".format(metric_alert)) # Delete metric alert monitor_client.metric_alerts.delete(GROUP_NAME, METRIC_ALERT_NAME) print("Delete metric alert.\n") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) TENANT_ID = os.environ.get("AZURE_TENANT_ID", None) DISK_ENCRYPTION_SET_NAME = "diskencryptionsetxxx" GROUP_NAME = "testgroupx" KEY_VAULT = "keyvaultxyzxxxxx" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) compute_client = ComputeManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) keyvault_client = KeyVaultManagementClient( credentials=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create key vault = keyvault_client.vaults.create_or_update( GROUP_NAME, KEY_VAULT, { 'location': "eastus", 'properties': { 'sku': { 'name': 'standard' }, 'tenant_id': TENANT_ID, "access_policies": [{ "tenant_id": TENANT_ID, "object_id": "123743cc-88ef-49ee-920e-13958fe5697d", "permissions": { "keys": [ "encrypt", "decrypt", "wrapKey", "unwrapKey", "sign", "verify", "get", "list", "create", "update", "import", "delete", "backup", "restore", "recover", "purge" ] } }], 'enabled_for_disk_encryption': True, } }).result() key_client = KeyClient(vault.properties.vault_uri, DefaultAzureCredentials()) expires_on = date_parse.parse("2050-02-02T08:00:00.000Z") key = key_client.create_key("testkey", "RSA", size=2048, expires_on=expires_on) # Create disk encryption set encryption_set = compute_client.disk_encryption_sets.begin_create_or_update( GROUP_NAME, DISK_ENCRYPTION_SET_NAME, { "location": "eastus", "identity": { "type": "SystemAssigned" }, "active_key": { "source_vault": { "id": vault.id }, "key_url": key.id } }).result() print("Create disk encryption set:\n{}".format(encryption_set)) # Get disk encrytion set encryption_set = compute_client.disk_encryption_sets.get( GROUP_NAME, DISK_ENCRYPTION_SET_NAME) print("Get disk encryption set:\n{}".format(encryption_set)) # Update disk encryption set encryption_set = compute_client.disk_encryption_sets.begin_update( GROUP_NAME, DISK_ENCRYPTION_SET_NAME, { "active_key": { "source_vault": { "id": vault.id }, "key_url": key.id }, "tags": { "department": "Development", "project": "Encryption" } }).result() print("Update disk encryption set:\n{}".format(encryption_set)) # Delete disk encryption set compute_client.disk_encryption_sets.begin_delete(GROUP_NAME, DISK_ENCRYPTION_SET_NAME) print("Delete disk encryption set.\n") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" STORAGE_ACCOUNT_NAME = "storageaccountxyzxyzxx" NAMESPACE = "namespacex" EVENTHUB = "eventhub" AUTHORIZATION_RULE = "authorizationx" INSIGHT = "insightx" WORKSPACE_NAME = "workspacex" WORKFLOW_NAME = "workflow" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) storage_client = StorageManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) eventhub_client = EventHubManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) monitor_client = MonitorClient(credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) loganalytics_client = LogAnalyticsManagementClient( credentials=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) logic_client = LogicManagementClient(credentials=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create Storage storage_account = storage_client.storage_accounts.begin_create( GROUP_NAME, STORAGE_ACCOUNT_NAME, { "sku": { "name": "Standard_LRS" }, "kind": "Storage", "location": "eastus", "enable_https_traffic_only": True }).result() # Create eventhub authorization rule eventhub_client.namespaces.begin_create_or_update( GROUP_NAME, NAMESPACE, { "sku": { "name": "Standard", "tier": "Standard" }, "location": "eastus", "tags": { "tag1": "value1", "tag2": "value2" } }).result() eventhub_client.namespaces.create_or_update_authorization_rule( GROUP_NAME, NAMESPACE, AUTHORIZATION_RULE, {"rights": ["Listen", "Send", "Manage"]}) eventhub_client.event_hubs.create_or_update( GROUP_NAME, NAMESPACE, EVENTHUB, { "message_retention_in_days": "4", "partition_count": "4", "status": "Active", "capture_description": { "enabled": True, "encoding": "Avro", "interval_in_seconds": "120", "size_limit_in_bytes": "10485763", "destination": { "name": "EventHubArchive.AzureBlockBlob", "storage_account_resource_id": storage_account.id, "blob_container": "container", "archive_name_format": "{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}" } } }) eventhub_client.event_hubs.create_or_update_authorization_rule( GROUP_NAME, NAMESPACE, EVENTHUB, AUTHORIZATION_RULE, {"rights": ["Listen", "Send", "Manage"]}) # Create workspace workspace = loganalytics_client.workspaces.create_or_update( GROUP_NAME, WORKSPACE_NAME, { "sku": { "name": "PerNode" }, "retention_in_days": 30, "location": "eastus", "tags": { "tag1": "val1" } }).result() # Create workflow workflow = logic_client.workflows.create_or_update( GROUP_NAME, WORKFLOW_NAME, { "location": "eastus", "definition": { "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#", "contentVersion": "1.0.0.0", "parameters": {}, "triggers": {}, "actions": {}, "outputs": {} } }) RESOURCE_URI = workflow.id # Create diagnostic setting diagnostic_setting = monitor_client.diagnostic_settings.create_or_update( RESOURCE_URI, INSIGHT, { "storage_account_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + GROUP_NAME + "/providers/Microsoft.Storage/storageAccounts/" + STORAGE_ACCOUNT_NAME + "", "workspace_id": workspace.id, "event_hub_authorization_rule_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + GROUP_NAME + "/providers/microsoft.eventhub/namespaces/" + NAMESPACE + "/authorizationrules/" + AUTHORIZATION_RULE, "event_hub_name": EVENTHUB, "metrics": [], "logs": [{ "category": "WorkflowRuntime", "enabled": True, "retention_policy": { "enabled": False, "days": "0" } }], }) print("Create diagnostic setting:\n{}".format(diagnostic_setting)) # Get diagnostic setting diagnostic_setting = monitor_client.diagnostic_settings.get( RESOURCE_URI, INSIGHT) print("Get diagnostic setting:\n{}".format(diagnostic_setting)) # Delete diagnostic setting monitor_client.diagnostic_settings.delete(RESOURCE_URI, INSIGHT) print("Delete diagnostic setting.") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" ACTIVITY_LOG_ALERT_NAME = "activitylogalertx" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) monitor_client = MonitorClient(credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create activity log alert log_alert = monitor_client.activity_log_alerts.create_or_update( GROUP_NAME, ACTIVITY_LOG_ALERT_NAME, { "location": "Global", "scopes": ["subscriptions/" + SUBSCRIPTION_ID], "enabled": True, "condition": { "all_of": [{ "field": "category", "equals": "Administrative" }, { "field": "level", "equals": "Error" }] }, "actions": { "action_groups": [] }, "description": "Sample activity log alert description" }) print("Create activity log alert:\n{}".format(log_alert)) # Get activity log alert log_alert = monitor_client.activity_log_alerts.get( GROUP_NAME, ACTIVITY_LOG_ALERT_NAME) print("Get activity log alert:\n{}".format(log_alert)) # Patch acitivity log alert log_alert = monitor_client.activity_log_alerts.update( GROUP_NAME, ACTIVITY_LOG_ALERT_NAME, { "tags": { "key1": "value1", "key2": "value2" }, "properties": { "enabled": False } }) print("Update activity log alert:\n{}".format(log_alert)) # Delete activate log alert monitor_client.activity_log_alerts.delete(GROUP_NAME, ACTIVITY_LOG_ALERT_NAME) print("Delete activity log alert.\n") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" NAMESPACE_NAME = "namespacex" NAMESPACE_NAME_2 = "namespacextwo" DISASTER_RECOVERY_CONFIG_NAME = "disasterrecoveryconfig" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) eventhub_client = EventHubManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) # Create resource group resource_client.resource_groups.create_or_update( GROUP_NAME, {"location": "eastus"} ) # Create Namespace eventhub_client.namespaces.begin_create_or_update( GROUP_NAME, NAMESPACE_NAME, { "sku": { "name": "Standard", "tier": "Standard" }, "location": "eastus", "tags": { "tag1": "value1", "tag2": "value2" } } ).result() # Create Second Namespace second_namespace = eventhub_client.namespaces.begin_create_or_update( GROUP_NAME, NAMESPACE_NAME_2, { "sku": { "name": "Standard", "tier": "Standard" }, "location": "westus", "tags": { "tag1": "value1", "tag2": "value2" } } ).result() # Check name availability result = eventhub_client.disaster_recovery_configs.check_name_availability( GROUP_NAME, NAMESPACE_NAME, { "name": NAMESPACE_NAME_2 } ) print("Check name availability: {}".format(result)) # Create disaster recovery config config = eventhub_client.disaster_recovery_configs.create_or_update( GROUP_NAME, NAMESPACE_NAME, DISASTER_RECOVERY_CONFIG_NAME, { "partner_namespace": second_namespace.id } ) print("Create disaster recovery config: {}".format(config)) # Get disaster recovery config for _ in range(5): config = eventhub_client.disaster_recovery_configs.get( GROUP_NAME, NAMESPACE_NAME, DISASTER_RECOVERY_CONFIG_NAME ) if config.provisioning_state == "Successed": break time.sleep(30) print("Get disaster recovery config: {}".format(config)) # Break pairing disaster recovery config eventhub_client.disaster_recovery_configs.break_pairing( GROUP_NAME, NAMESPACE_NAME, DISASTER_RECOVERY_CONFIG_NAME ) print("Break pairing disaster recovery config.") # Fail over disaster recovery config eventhub_client.disaster_recovery_configs.fail_over( GROUP_NAME, NAMESPACE_NAME_2, DISASTER_RECOVERY_CONFIG_NAME ) print("Fail over disaster recovery config.") # Delete disaster recovery config for _ in range(5): try: eventhub_client.disaster_recovery_configs.delete( GROUP_NAME, NAMESPACE_NAME, DISASTER_RECOVERY_CONFIG_NAME ) except HttpResponseError: time.sleep(30) else: break print("Delete disaster recovery config.") # Delete Namespace eventhub_client.namespaces.begin_delete( GROUP_NAME, NAMESPACE_NAME ).result() # Delete Second Namespace eventhub_client.namespaces.begin_delete( GROUP_NAME, NAMESPACE_NAME_2 ).result() # Delete resource group resource_client.resource_groups.begin_delete( GROUP_NAME ).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" STORAGE_ACCOUNT_NAME = "storageaccountxyztest" NAMESPACE_NAME = "namespacex" EVENTHUB_NAME = "eventhubx" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) eventhub_client = EventHubManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) storage_client = StorageManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create StorageAccount storage_client.storage_accounts.begin_create(GROUP_NAME, STORAGE_ACCOUNT_NAME, { "sku": { "name": "Standard_LRS" }, "kind": "StorageV2", "location": "eastus" }).result() # Create Namespace eventhub_client.namespaces.begin_create_or_update( GROUP_NAME, NAMESPACE_NAME, { "sku": { "name": "Standard", "tier": "Standard" }, "location": "South Central US", "tags": { "tag1": "value1", "tag2": "value2" } }).result() # Create EventHub eventhub = eventhub_client.event_hubs.create_or_update( GROUP_NAME, NAMESPACE_NAME, EVENTHUB_NAME, { "message_retention_in_days": "4", "partition_count": "4", "status": "Active", "capture_description": { "enabled": True, "encoding": "Avro", "interval_in_seconds": "120", "size_limit_in_bytes": "10485763", "destination": { "name": "EventHubArchive.AzureBlockBlob", "storage_account_resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + GROUP_NAME + "/providers/Microsoft.Storage/storageAccounts/" + STORAGE_ACCOUNT_NAME + "", "blob_container": "container", "archive_name_format": "{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}" } } }) print("Create EventHub: {}".format(eventhub)) # Get EventHub eventhub = eventhub_client.event_hubs.get(GROUP_NAME, NAMESPACE_NAME, EVENTHUB_NAME) print("Get EventHub: {}".format(eventhub)) # Delete EventHub eventhub_client.event_hubs.delete(GROUP_NAME, NAMESPACE_NAME, EVENTHUB_NAME) print("Delete EventHub.") # Delete Namespace eventhub_client.namespaces.begin_delete(GROUP_NAME, NAMESPACE_NAME).result() # Delete StorageAccount storage_client.storage_accounts.delete(GROUP_NAME, STORAGE_ACCOUNT_NAME) # Delete resource group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" POLICY_NAME = "policyxyz" POLICY_ASSIGNMENT_NAME = "assignmentx" POLICY_SET_NAME = "policysetdefinition" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ policy_client = PolicyClient(credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create policy definition definition = policy_client.policy_definitions.create_or_update( POLICY_NAME, { 'policy_type': 'Custom', 'description': 'Don\'t create a VM anywhere', 'policy_rule': { 'if': { 'allOf': [{ 'source': 'action', 'equals': 'Microsoft.Compute/virtualMachines/read' }, { 'field': 'location', 'in': ['eastus', 'eastus2', 'centralus'] }] }, 'then': { 'effect': 'deny' } } }) print("Create policy definition: {}".format(definition)) # Get policy definition definition = policy_client.policy_definitions.get(POLICY_NAME) print("Get policy definition: {}".format(definition)) # Policy Assignment - By Name scope = '/subscriptions/{}/resourceGroups/{}'.format( SUBSCRIPTION_ID, GROUP_NAME) # Create policy assignment assignment = policy_client.policy_assignments.create( scope, POLICY_ASSIGNMENT_NAME, { 'policy_definition_id': definition.id, }) print("Create policy assignment: {}".format(assignment)) # Get policy assignment assignment = policy_client.policy_assignments.get(assignment.scope, assignment.name) print("Get policy assignment: {}".format(assignment)) # Create policy set definition policy_set = policy_client.policy_set_definitions.create_or_update( POLICY_SET_NAME, { "properties": { "displayName": "Cost Management", "description": "Policies to enforce low cost storage SKUs", "metadata": { "category": "Cost Management" }, "policyDefinitions": [{ "policyDefinitionId": definition.id, "parameters": {} }] } }) print("Create policy set definition: {}".format(policy_set)) # Get policy set definition policy_set = policy_client.policy_set_definitions.get(POLICY_SET_NAME) print("Get policy set definition: {}".format(policy_set)) # Delete policy set definition policy_client.policy_set_definitions.delete(POLICY_SET_NAME) print("Delete policy set definition.") # Delete policy assignment policy_client.policy_assignments.delete(assignment.scope, assignment.name) print("Delete policy assignment.") # Delete policy definition policy_client.policy_definitions.delete(POLICY_NAME) print("Delete policy definition.") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" DEPLOYMENT_NAME = "deploymentx" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) # Create resource group resource_client.resource_groups.create_or_update( GROUP_NAME, {"location": "eastus"} ) # Check deployment existence exist_result = resource_client.deployments.check_existence( GROUP_NAME, DEPLOYMENT_NAME ) print("Check deployment existence:\n{}".format(exist_result)) # Create deployment deployment = resource_client.deployments.begin_create_or_update( GROUP_NAME, DEPLOYMENT_NAME, { "properties":{ "mode": "Incremental", "template": template, "parameters": {"location": { "value": "West US"}} } } ).result() print("Create deployment:\n{}".format(deployment)) # Get deployment deployment = resource_client.deployments.get( GROUP_NAME, DEPLOYMENT_NAME ) print("Get deployment:\n{}".format(deployment)) # Validate deployment validation = resource_client.deployments.begin_validate( GROUP_NAME, DEPLOYMENT_NAME, { "properties": { "mode": "Incremental", "template": template, "parameters": {"location": { "value": "West US"}} } } ).result() print("Vlidate deployment:\n{}".format(validation)) # Delete deployment resource_client.deployments.begin_delete( GROUP_NAME, DEPLOYMENT_NAME ).result() print("Delete deployment.\n") # Delete Group resource_client.resource_groups.begin_delete( GROUP_NAME ).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" WORKSPACE_NAME = "workspacex" SCHEDULED_QUERY_RULE = "scheduledqueryrule" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) monitor_client = MonitorClient(credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) loganalytics_client = LogAnalyticsManagementClient( credentials=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create workspace workspace = loganalytics_client.workspaces.create_or_update( GROUP_NAME, WORKSPACE_NAME, { "sku": { "name": "PerNode" }, "retention_in_days": 30, "location": "eastus", "tags": { "tag1": "val1" } }).result() # Create scheduled query rule schedueld_query_rule = monitor_client.scheduled_query_rules.create_or_update( GROUP_NAME, SCHEDULED_QUERY_RULE, { "location": "eastus", "description": "log alert description", "enabled": "true", "provisioning_state": "Succeeded", "source": { "query": "Heartbeat | summarize AggregatedValue = count() by bin(TimeGenerated, 5m)", "data_source_id": workspace.id, "query_type": "ResultCount" }, "schedule": { "frequency_in_minutes": "15", "time_window_in_minutes": "15" }, "action": { "odata.type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction", "severity": "1", "azns_action": { "action_group": [], "email_subject": "Email Header", "custom_webhook_payload": "{}" }, "trigger": { "threshold_operator": "GreaterThan", "threshold": "3", "metric_trigger": { "threshold_operator": "GreaterThan", "threshold": "5", "metric_trigger_type": "Consecutive", "metric_column": "Computer" } } } }) print("Create scheduled query rule:\n{}".format(schedueld_query_rule)) # Get scheduled query rule schedueld_query_rule = monitor_client.scheduled_query_rules.get( GROUP_NAME, SCHEDULED_QUERY_RULE) print("Get scheduled query rule:\n{}".format(schedueld_query_rule)) # Patch scheduled query rule schedueld_query_rule = monitor_client.scheduled_query_rules.update( GROUP_NAME, SCHEDULED_QUERY_RULE, {"enabled": "true"}) print("Update scheduled query rule:\n{}".format(schedueld_query_rule)) # Delete scheduled query rule monitor_client.scheduled_query_rules.delete(GROUP_NAME, SCHEDULED_QUERY_RULE) print("Delete scheduled query rule.\n") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" ACTION_GROUP_NAME = "actiongroupx" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) monitor_client = MonitorClient(credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create action group action_group = monitor_client.action_groups.create_or_update( GROUP_NAME, ACTION_GROUP_NAME, { "location": "Global", "group_short_name": "sample", "enabled": True, "email_receivers": [{ "name": "John Doe's email", "email_address": "*****@*****.**", "use_common_alert_schema": False }], "sms_receivers": [{ "name": "John Doe's mobile", "country_code": "1", "phone_number": "1234567890" }] }) print("Create action group:\n{}".format(action_group)) # Get action group action_group = monitor_client.action_groups.get(GROUP_NAME, ACTION_GROUP_NAME) print("Get action group:\n{}".format(action_group)) # Update action group action_group = monitor_client.action_groups.update( GROUP_NAME, ACTION_GROUP_NAME, { "tags": { "key1": "value1", "key2": "value2" }, "properties": { "enabled": False } }) print("Update action group:\n{}".format(action_group)) # Delete action group monitor_client.action_groups.delete(GROUP_NAME, ACTION_GROUP_NAME) print("Delete action group:\n{}".format(action_group)) # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" DISK_NAME = "disknamex" SNAPSHOT_NAME = "snapshotx" IMAGE_NAME = "imagex" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) compute_client = ComputeManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) # Create resource group resource_client.resource_groups.create_or_update( GROUP_NAME, {"location": "eastus"} ) # Create disk disk = compute_client.disks.begin_create_or_update( GROUP_NAME, DISK_NAME, { "location": "eastus", "creation_data": { "create_option": "Empty" }, "disk_size_gb": "200" } ).result() print("Create disk:\n{}".format(disk)) # Create snapshot snapshot = compute_client.snapshots.begin_create_or_update( GROUP_NAME, SNAPSHOT_NAME, { "location": "eastus", "creation_data": { "create_option": "Copy", "source_uri": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + GROUP_NAME + "/providers/Microsoft.Compute/disks/" + DISK_NAME } } ).result() print("Create snapshot:\n{}".format(snapshot)) # Create a virtual machine image form a snapshot image = compute_client.images.begin_create_or_update( GROUP_NAME, IMAGE_NAME, { "location": "eastus", "storage_profile": { "os_disk": { "os_type": "Linux", "snapshot": { "id": "subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + GROUP_NAME + "/providers/Microsoft.Compute/snapshots/" + SNAPSHOT_NAME }, "os_state": "Generalized" }, "zone_resilient": False }, "hyper_v_generation": "V1" # TODO: required } ).result() print("Create image:\n{}".format(image)) # Get disk disk = compute_client.disks.get( GROUP_NAME, DISK_NAME ) print("Get disk:\n{}".format(disk)) # Get snapshot snapshot = compute_client.snapshots.get( GROUP_NAME, SNAPSHOT_NAME ) print("Get snapshot:\n{}".format(snapshot)) # Get image image = compute_client.images.get( GROUP_NAME, IMAGE_NAME ) print("Get image:\n{}".format(image)) # Update disk disk = compute_client.disks.begin_update( GROUP_NAME, DISK_NAME, { "disk_size_gb": "200" } ).result() print("Update disk:\n{}".format(disk)) # Update snapshot snapshot = compute_client.snapshots.begin_update( GROUP_NAME, SNAPSHOT_NAME, { "creation_data": { "create_option": "Copy", "source_uri": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + GROUP_NAME + "/providers/Microsoft.Compute/disks/" + DISK_NAME } } ).result() print("Update snap shot:\n{}".format(snapshot)) # Update image image = compute_client.images.begin_update( GROUP_NAME, IMAGE_NAME, { "tags": { "department": "HR" } } ).result() print("Update image:\n{}".format(image)) # Delete image compute_client.images.begin_delete( GROUP_NAME, IMAGE_NAME ).result() print("Delete image.\n") # Delete snapshot compute_client.snapshots.begin_delete( GROUP_NAME, SNAPSHOT_NAME ).result() print("Delete snap shot.\n") # Delete disk compute_client.disks.begin_delete( GROUP_NAME, DISK_NAME ).result() print("Delete disk.\n") # Delete Group resource_client.resource_groups.begin_delete( GROUP_NAME ).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" GALLERY_NAME = "galleryname" APPLICATION_NAME = "applicationname" IMAGE_NAME = "imagex" DISK_NAME = "diskname" SNAPSHOT_NAME = "snapshotname" VERSION_NAME = "1.0.0" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) compute_client = ComputeManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID) # Create resource group resource_client.resource_groups.create_or_update(GROUP_NAME, {"location": "eastus"}) # Create disk disk = compute_client.disks.begin_create_or_update( GROUP_NAME, DISK_NAME, { "location": "eastus", "creation_data": { "create_option": "Empty" }, "disk_size_gb": "200" }).result() # Create snapshot snapshot = compute_client.snapshots.begin_create_or_update( GROUP_NAME, SNAPSHOT_NAME, { "location": "eastus", "creation_data": { "create_option": "Copy", "source_uri": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + GROUP_NAME + "/providers/Microsoft.Compute/disks/" + DISK_NAME } }).result() # Create gallery gallery = compute_client.galleries.begin_create_or_update( GROUP_NAME, GALLERY_NAME, { "location": "eastus", "description": "This is the gallery description." }).result() print("Create gallery:\n{}".format(gallery)) # Create gallery application application = compute_client.gallery_applications.begin_create_or_update( GROUP_NAME, GALLERY_NAME, APPLICATION_NAME, { "location": "eastus", "description": "This is the gallery application description.", "eula": "This is the gallery application EULA.", "supported_os_type": "Windows" }).result() print("Create gallery application:\n{}".format(application)) # Create gallery image image = compute_client.gallery_images.begin_create_or_update( GROUP_NAME, GALLERY_NAME, IMAGE_NAME, { "location": "eastus", "os_type": "Windows", "os_state": "Generalized", "hyper_vgeneration": "V1", "identifier": { "publisher": "myPublisherName", "offer": "myOfferName", "sku": "mySkuName" } }).result() print("Create gallery image:\n{}".format(image)) # Get gallery gallery = compute_client.galleries.get(GROUP_NAME, GALLERY_NAME) print("Get gallery:\n{}".format(gallery)) # Get gallery application application = compute_client.gallery_applications.get( GROUP_NAME, GALLERY_NAME, APPLICATION_NAME) print("Get gallery application:\n{}".format(application)) # Get gallery image image = compute_client.gallery_images.get(GROUP_NAME, GALLERY_NAME, IMAGE_NAME) print("Get gallery image:\n{}".format(image)) # Update gallery gallery = compute_client.galleries.begin_update( GROUP_NAME, GALLERY_NAME, { "description": "This is the gallery description." }).result() print("Update gallery:\n{}".format(gallery)) # Update gallery application application = compute_client.gallery_applications.begin_update( GROUP_NAME, GALLERY_NAME, APPLICATION_NAME, { "description": "This is the gallery application description.", "eula": "This is the gallery application EULA.", "supported_os_type": "Windows", "tags": { "tag1": "tag1" } }).result() print("Update gallery application:\n{}".format(application)) # Update gallery image image = compute_client.gallery_images.begin_update( GROUP_NAME, GALLERY_NAME, IMAGE_NAME, { "os_type": "Windows", "os_state": "Generalized", "hyper_vgeneration": "V1", "identifier": { "publisher": "myPublisherName", "offer": "myOfferName", "sku": "mySkuName" } }).result() print("Update gallery image:\n{}".format(image)) # Delete gallery image compute_client.gallery_images.begin_delete(GROUP_NAME, GALLERY_NAME, IMAGE_NAME).result() print("Delete gallery image.\n") # Delete gallery application compute_client.gallery_applications.begin_delete( GROUP_NAME, GALLERY_NAME, APPLICATION_NAME).result() print("Delete gallery application.\n") # Delete gallery compute_client.galleries.begin_delete(GROUP_NAME, GALLERY_NAME).result() print("Delete gallery.") # Delete Group resource_client.resource_groups.begin_delete(GROUP_NAME).result()
def main(): SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None) GROUP_NAME = "testgroupx" HOST_GROUP_NAME = "hostgroupx" HOST_NAME = "hostx" # Create client # For other authentication approaches, please see: https://pypi.org/project/azure-identity/ resource_client = ResourceManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) compute_client = ComputeManagementClient( credential=DefaultAzureCredentials(), subscription_id=SUBSCRIPTION_ID ) # Create resource group resource_client.resource_groups.create_or_update( GROUP_NAME, {"location": "eastus"} ) # Create dedicated host group host_group = compute_client.dedicated_host_groups.create_or_update( GROUP_NAME, HOST_GROUP_NAME, { "location": "eastus", "tags": { "department": "finance" }, "zones": [ "1" ], "platform_fault_domain_count": "3" } ) print("Create dedicated host group:\n{}".format(host_group)) # Create dedicated host host = compute_client.dedicated_hosts.begin_create_or_update( GROUP_NAME, HOST_GROUP_NAME, HOST_NAME, { "location": "eastus", "tags": { "department": "HR" }, "platform_fault_domain": "1", "sku": { "name": "DSv3-Type1" } } ).result() print("Create dedicated host:\n{}".format(host)) # Get dedicated host group host_group = compute_client.dedicated_host_groups.get( GROUP_NAME, HOST_GROUP_NAME ) print("Get dedicated host group:\n{}".format(host_group)) # Get dedicated host host = compute_client.dedicated_hosts.get( GROUP_NAME, HOST_GROUP_NAME, HOST_NAME ) print("Get dedicated host:\n{}".format(host)) # Update dedicated host group host_group = compute_client.dedicated_host_groups.update( GROUP_NAME, HOST_GROUP_NAME, { "tags": { "department": "finance" }, "platform_fault_domain_count": "3" } ) print("Update dedicated host group:\n{}".format(host_group)) # Update dedicated host host = compute_client.dedicated_hosts.begin_update( GROUP_NAME, HOST_GROUP_NAME, HOST_NAME, { "tags": { "department": "HR" } } ).result() print("Update dedicated host:\n{}".format(host)) # Delete dedicated host compute_client.dedicated_hosts.begin_delete( GROUP_NAME, HOST_GROUP_NAME, HOST_NAME ).result() print("Delete dedicated host.\n") # Delete dedicated host group compute_client.dedicated_host_groups.delete( GROUP_NAME, HOST_GROUP_NAME ) print("Delete dedicated host group.\n") # Delete Group resource_client.resource_groups.begin_delete( GROUP_NAME ).result()