Example #1
0
def main():

    credential = DefaultAzureCredential()

    subscription_client = SubscriptionClient(credential)
    subscription = subscription_client.subscriptions.list()

    for subsc in subscription:
        subscription_id = subsc.subscription_id

        compute_client = ComputeManagementClient(
            credential=DefaultAzureCredential(),
            subscription_id=subscription_id)
        network_client = NetworkManagementClient(
            credential=DefaultAzureCredential(),
            subscription_id=subscription_id)

        monitor_client = MonitorClient(credential=DefaultAzureCredential(),
                                       subscription_id=subscription_id)

        # monitor = monitor_client.operations
        # val = monitor.list().value
        # for v in val:
        #     print(v.display.resource)

        resource_client = ResourceManagementClient(credential, subscription_id)
        resource_group = resource_client.resource_groups.list()
        print(next(resource_group))

        for rsc_g in resource_group:
            resource_group_name = rsc_g.name
            # rg_list = resource_client.resources.list_by_resource_group(resource_group_name)
            compute = compute_client.virtual_machines.list(resource_group_name)
    def set_connect(self, schema, options: dict, secret_data: dict):
        """
        cred(dict)
            - type: ..
            - tenant_id: ...
            - client_id: ...
            - client_secret: ...
            - subscription_id: ...
        """
        try:
            subscription_id = secret_data['subscription_id']

            os.environ["AZURE_SUBSCRIPTION_ID"] = subscription_id
            os.environ["AZURE_TENANT_ID"] = secret_data['tenant_id']
            os.environ["AZURE_CLIENT_ID"] = secret_data['client_id']
            os.environ["AZURE_CLIENT_SECRET"] = secret_data['client_secret']

            credential = DefaultAzureCredential()

            self.monitor_client = MonitorClient(
                credential=credential, subscription_id=subscription_id)

        except Exception as e:
            print(e)
            raise ERROR_INVALID_CREDENTIALS(
                message=
                'connection failed. Please check your authentication information.'
            )
Example #3
0
  def __init__(self,
               az_account: 'account.AZAccount') -> None:
    """Initialize the Azure monitoring class.

    Args:
      az_account (AZAccount): An Azure account object.
    """
    self.monitoring_client = MonitorClient(
        az_account.credentials, az_account.subscription_id)
Example #4
0
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    LOGPROFILE_NAME = "logprofilexx"
    STORAGE_ACCOUNT_NAME = "storageaccountxxy"

    # Create client
    # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    monitor_client = MonitorClient(credential=DefaultAzureCredential(),
                                   subscription_id=SUBSCRIPTION_ID)
    storage_client = StorageManagementClient(
        credential=DefaultAzureCredential(), 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 log profile
    log_profile = monitor_client.log_profiles.create_or_update(
        LOGPROFILE_NAME, {
            "location": "",
            "locations": ["global"],
            "categories": ["Write", "Delete", "Action"],
            "retention_policy": {
                "enabled": True,
                "days": "3"
            },
            "storage_account_id": storage_account.id,
        })
    print("Create log profile:\n{}".format(log_profile))

    # Get log profile
    log_profile = monitor_client.log_profiles.delete(LOGPROFILE_NAME)
    print("Get log profile:\n{}".format(log_profile))

    # Delete log profile
    monitor_client.log_profiles.delete(LOGPROFILE_NAME)
    print("Delete log profile.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()
Example #5
0
    def run(self, args):
        """Run the remediation job.
        :param args: List of arguments provided to the job.
        :type args: list.
        :returns: int
        """
        params = self.parse(args[1])
        client_id = os.environ.get("AZURE_CLIENT_ID")
        client_secret = os.environ.get("AZURE_CLIENT_SECRET")
        tenant_id = os.environ.get("AZURE_TENANT_ID")

        # credential for Storage Account and Key Vault management and SQL client
        credential = ClientSecretCredential(
            client_id=client_id, client_secret=client_secret, tenant_id=tenant_id,
        )

        # credential for AzureGraphRbacManagementClient
        credentials_graph = ServicePrincipalCredentials(
            client_id=client_id,
            secret=client_secret,
            tenant=tenant_id,
            resource="https://graph.windows.net",
        )

        client_storage = StorageManagementClient(credential, params["subscription_id"])

        keyvault_client = KeyVaultManagementClient(
            credential, params["subscription_id"]
        )
        graph_client = GraphRbacManagementClient(
            credentials_graph, tenant_id, base_url=None
        )

        monitor_client = MonitorClient(credential, params["subscription_id"])

        client = SqlManagementClient(
            credential, params["subscription_id"], base_url=None
        )
        return self.remediate(
            client_id,
            tenant_id,
            credential,
            client,
            client_storage,
            keyvault_client,
            graph_client,
            monitor_client,
            params["resource_group_name"],
            params["sql_server_name"],
            params["region"],
            params["subscription_id"],
        )
Example #6
0
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=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    storage_client = StorageManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    eventhub_client = EventHubManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    monitor_client = MonitorClient(credential=DefaultAzureCredential(),
                                   subscription_id=SUBSCRIPTION_ID)
    loganalytics_client = LogAnalyticsManagementClient(
        credentials=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    logic_client = LogicManagementClient(credentials=DefaultAzureCredential(),
                                         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"
    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"
    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()
Example #9
0
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=DefaultAzureCredential(),
        subscription_id=SUBSCRIPTION_ID
    )
    monitor_client = MonitorClient(
        credential=DefaultAzureCredential(),
        subscription_id=SUBSCRIPTION_ID
    )
    loganalytics_client = LogAnalyticsManagementClient(
        credentials=DefaultAzureCredential(),
        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"
    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()
Example #11
0
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()