示例#1
0
async def _query_subscription(ctx: Context, sub: Subscription):

    logger.info(
        f"Querying for resources in subscription - {sub.subscription_id}")
    sub_dict = sub.as_dict()
    sub_dict["resourceGroups"] = []

    async with ResourceManagementClient(
            ctx.cred_async,
            sub.subscription_id,
            base_url=ctx.cloud["ARM"],
    ) as rm_client:

        # GET RESOURCE GROUPS
        async for r_group in rm_client.resource_groups.list():
            sub_dict["resourceGroups"].append(r_group.as_dict())

        # GET RESOURCES IN SUBSCRIPTION
        async for resource in rm_client.resources.list():
            res = await _query_resource(rm_client, resource.id)
            if res:
                output = OUTPUT_FOLDER / f"{sub.subscription_id}.sqlite"
                await sqlite_writer(output, res)
            else:
                logger.warning(f"Could not access - {resource}")

    logger.info(f"Finished querying - {sub.subscription_id}")
    return sub_dict
示例#2
0
def __create_resource_management_client(credential):
    """
    Create a ResourceManagementClient object using the subscription ID from environment variables
    """

    subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", None)
    if subscription_id is None:
        return None

    return ResourceManagementClient(
        credential=credential,
        subscription_id=subscription_id
    )
示例#3
0
async 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/
    credential = DefaultAzureCredential()
    resource_client = ResourceManagementClient(credential=credential,
                                               subscription_id=SUBSCRIPTION_ID)

    # Check resource group existence
    result_check = await resource_client.resource_groups.check_existence(
        GROUP_NAME)
    print("Whether resource group exists:\n{}".format(result_check))

    # Create resource group
    resource_group = await resource_client.resource_groups.create_or_update(
        GROUP_NAME, {"location": "eastus"})
    print("Create resource group:\n{}".format(resource_group))

    # Get resource group
    resource_group = await resource_client.resource_groups.get(GROUP_NAME)
    print("Get resource group:\n{}".format(resource_group))

    # List resource group
    resource_groups = list()
    async for g in resource_client.resource_groups.list():
        resource_groups.append(g)
    print("List resource groups:\n{}".format(resource_groups))

    # Update resource group
    resource_group = await resource_client.resource_groups.update(
        GROUP_NAME, {"tags": {
            "tag1": "valueA",
            "tag2": "valueB"
        }})
    print("Update resource group:\n{}".format(resource_group))

    # Delete Group
    async_poller = await resource_client.resource_groups.begin_delete(
        GROUP_NAME)
    await async_poller.result()
    print("Delete resource group.\n")

    # [Warning] All clients and credentials need to be closed.
    # link: https://github.com/Azure/azure-sdk-for-python/issues/8990
    await resource_client.close()
    await credential.close()
示例#4
0
async def main():

    TENANT_ID = os.environ.get("AZURE_TENANT_ID", None)
    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    VAULT = "vaultxxyyzz"

    # Create client
    # # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    credential = DefaultAzureCredential()
    resource_client = ResourceManagementClient(credential=credential,
                                               subscription_id=SUBSCRIPTION_ID)
    keyvault_client = KeyVaultManagementClient(credential=credential,
                                               subscription_id=SUBSCRIPTION_ID)

    # Create resource group
    await resource_client.resource_groups.create_or_update(
        GROUP_NAME, {"location": "eastus"})

    # Create vault
    async_poller = await keyvault_client.vaults.begin_create_or_update(
        GROUP_NAME, VAULT, {
            "location": "eastus",
            "properties": {
                "tenant_id":
                TENANT_ID,
                "sku": {
                    "family": "A",
                    "name": "standard"
                },
                "access_policies": [{
                    "tenant_id": TENANT_ID,
                    "object_id": "00000000-0000-0000-0000-000000000000",
                    "permissions": {
                        "keys": [
                            "encrypt", "decrypt", "wrapKey", "unwrapKey",
                            "sign", "verify", "get", "list", "create",
                            "update", "import", "delete", "backup", "restore",
                            "recover", "purge"
                        ],
                        "secrets": [
                            "get", "list", "set", "delete", "backup",
                            "restore", "recover", "purge"
                        ],
                        "certificates": [
                            "get", "list", "delete", "create", "import",
                            "update", "managecontacts", "getissuers",
                            "listissuers", "setissuers", "deleteissuers",
                            "manageissuers", "recover", "purge"
                        ]
                    }
                }],
                "enabled_for_deployment":
                True,
                "enabled_for_disk_encryption":
                True,
                "enabled_for_template_deployment":
                True
            }
        })
    vault = await async_poller.result()
    print("Create vault:\n{}".format(vault))

    # Get vault
    vault = await keyvault_client.vaults.get(GROUP_NAME, VAULT)
    print("Get vault:\n{}".format(vault))

    # List vault (List operation will return asyncList)
    vaults = list()
    async for v in keyvault_client.vaults.list_by_resource_group(GROUP_NAME,
                                                                 top="1"):
        vaults.append(v)
    print("List vaults:\n{}".format(vaults))

    # Update vault
    vault = await keyvault_client.vaults.update(
        GROUP_NAME, VAULT, {"tags": {
            "category": "Marketing"
        }})
    print("Update vault:\n{}".format(vault))

    # Delete vault
    await keyvault_client.vaults.delete(GROUP_NAME, VAULT)
    print("Delete vault.\n")

    # Purge a deleted vault
    async_poller = await keyvault_client.vaults.begin_purge_deleted(
        VAULT, "eastus")
    await async_poller.result()
    print("Purge a deleted vault.\n")

    # Delete Group
    async_poller = await resource_client.resource_groups.begin_delete(
        GROUP_NAME)
    await async_poller.result()

    # [Warning] All clients and credentials need to be closed.
    # link: https://github.com/Azure/azure-sdk-for-python/issues/8990
    await keyvault_client.close()
    await resource_client.close()
    await credential.close()
示例#5
0
async 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/
    credential = DefaultAzureCredential()
    resource_client = ResourceManagementClient(credential=credential,
                                               subscription_id=SUBSCRIPTION_ID)

    eventhub_client = EventHubManagementClient(credential=credential,
                                               subscription_id=SUBSCRIPTION_ID)

    # Create resource group
    await resource_client.resource_groups.create_or_update(
        GROUP_NAME, {"location": "eastus"})

    # Create Namespace
    async_poller = await eventhub_client.namespaces.begin_create_or_update(
        GROUP_NAME, NAMESPACE_NAME, {
            "sku": {
                "name": "Standard",
                "tier": "Standard"
            },
            "location": "eastus",
            "tags": {
                "tag1": "value1",
                "tag2": "value2"
            }
        })
    namespace = await async_poller.result()
    print("Create Namespace:\n{}".format(namespace))

    # Get Namesapce
    namespace = await eventhub_client.namespaces.get(GROUP_NAME,
                                                     NAMESPACE_NAME)
    print("Get Namespace:\n{}".format(namespace))

    # List Namespace (List operation will return asyncList)
    namespaces = list()
    async for n in eventhub_client.namespaces.list_by_resource_group(
            GROUP_NAME):
        namespaces.append(n)
    print("List Namespace:\n{}".format(namespaces))

    # Update Namespace
    namespace = await eventhub_client.namespaces.update(
        GROUP_NAME, NAMESPACE_NAME, {
            "location": "eastus",
            "tags": {
                "tag3": "value3",
                "tag4": "value4"
            }
        })
    print("Update Namespace:\n{}".format(namespace))

    await asyncio.sleep(30)

    # Delete Namespace
    async_poller = await eventhub_client.namespaces.begin_delete(
        GROUP_NAME, NAMESPACE_NAME)
    await async_poller.result()
    print("Delete Namespace.\n")

    # Delete resource group
    async_poller = await resource_client.resource_groups.begin_delete(
        GROUP_NAME)
    await async_poller.result()

    # [Warning] All clients and credentials need to be closed.
    # link: https://github.com/Azure/azure-sdk-for-python/issues/8990
    await eventhub_client.close()
    await resource_client.close()
    await credential.close()
示例#6
0
 def get_client(self) -> ResourceManagementClient:
     return ResourceManagementClient(self.auth, self.subscription)
async def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    STORAGE_ACCOUNT = "storageaccountxxyyzz"

    # Create client
    # # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    credential = DefaultAzureCredential()
    resource_client = ResourceManagementClient(
        credential=credential,
        subscription_id=SUBSCRIPTION_ID
    )
    storage_client = StorageManagementClient(
        credential=credential,
        subscription_id=SUBSCRIPTION_ID
    )

    # Create resource group
    await resource_client.resource_groups.create_or_update(
        GROUP_NAME,
        {"location": "eastus"}
    )

    # Create storage account
    async_poller = await storage_client.storage_accounts.begin_create(
        GROUP_NAME,
        STORAGE_ACCOUNT,
        {
          "sku": {
            "name": "Standard_GRS"
          },
          "kind": "StorageV2",
          "location": "eastus",
          "encryption": {
            "services": {
              "file": {
                "key_type": "Account",
                "enabled": True
              },
              "blob": {
                "key_type": "Account",
                "enabled": True
              }
            },
            "key_source": "Microsoft.Storage"
          },
          "tags": {
            "key1": "value1",
            "key2": "value2"
          }
        }
    )
    storage_account = await async_poller.result()
    print("Create storage account:\n{}".format(storage_account))

    # Get storage account
    storage_account = await storage_client.storage_accounts.get_properties(
        GROUP_NAME,
        STORAGE_ACCOUNT
    )
    print("Get storage account:\n{}".format(storage_account))

    # List storage account (List operation will return asyncList)
    storage_accounts = list()
    async for ac in storage_client.storage_accounts.list():
        storage_accounts.append(ac)
    print("List storage accounts:\n{}".format(storage_accounts))

    # Update storage account
    storage_account = await storage_client.storage_accounts.update(
        GROUP_NAME,
        STORAGE_ACCOUNT,
        {
          "network_acls": {
            "default_action": "Allow"
          },
          "encryption": {
            "services": {
              "file": {
                "key_type": "Account",
                "enabled": True
              },
              "blob": {
                "key_type": "Account",
                "enabled": True
              }
            },
            "key_source": "Microsoft.Storage"
          }
        }
    )
    print("Update storage account:\n{}".format(storage_account))
    
    # Delete storage account
    storage_account = await storage_client.storage_accounts.delete(
        GROUP_NAME,
        STORAGE_ACCOUNT
    )
    print("Delete storage account.\n")

    # Delete Group
    async_poller = await resource_client.resource_groups.begin_delete(
        GROUP_NAME
    )
    await async_poller.result()

    # [Warning] All clients and credentials need to be closed.
    # link: https://github.com/Azure/azure-sdk-for-python/issues/8990
    await storage_client.close()
    await resource_client.close()
    await credential.close()
示例#8
0
async 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/
    credential = DefaultAzureCredential()
    resource_client = ResourceManagementClient(credential=credential,
                                               subscription_id=SUBSCRIPTION_ID)
    monitor_client = MonitorClient(credential=credential,
                                   subscription_id=SUBSCRIPTION_ID)
    storage_client = StorageManagementClient(credential=credential,
                                             subscription_id=SUBSCRIPTION_ID)

    # Create resource group
    await resource_client.resource_groups.create_or_update(
        GROUP_NAME, {"location": "eastus"})

    # Create Storage
    async_poller = await storage_client.storage_accounts.begin_create(
        GROUP_NAME, STORAGE_ACCOUNT_NAME, {
            "sku": {
                "name": "Standard_LRS"
            },
            "kind": "Storage",
            "location": "eastus",
            "enable_https_traffic_only": True
        })
    storage_account = await async_poller.result()

    # Create log profile
    log_profile = await 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))

    # Need wait seconds
    await asyncio.sleep(20)

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

    # List log profile (List operation will return asyncList)
    log_profiles = list()
    async for log in monitor_client.log_profiles.list():
        log_profiles.append(log)
    print("List log profiles:\n{}".format(log_profiles))

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

    # Delete Group
    async_poller = await resource_client.resource_groups.begin_delete(
        GROUP_NAME)
    await async_poller.result()

    # [Warning] All clients and credentials need to be closed.
    # link: https://github.com/Azure/azure-sdk-for-python/issues/8990
    await monitor_client.close()
    await resource_client.close()
    await storage_client.close()
    await credential.close()
async 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/
    credential = DefaultAzureCredential()
    resource_client = ResourceManagementClient(
        credential=credential,
        subscription_id=SUBSCRIPTION_ID
    )
    network_client = NetworkManagementClient(
        credential=credential,
        subscription_id=SUBSCRIPTION_ID
    )
    compute_client = ComputeManagementClient(
        credential=credential,
        subscription_id=SUBSCRIPTION_ID
    )

    # Create resource group
    await resource_client.resource_groups.create_or_update(
        GROUP_NAME,
        {"location": "eastus"}
    )

    # Create virtual network
    async_poller = await network_client.virtual_networks.begin_create_or_update(
        GROUP_NAME,
        NETWORK_NAME,
        {
            'location': "eastus",
            'address_space': {
                'address_prefixes': ['10.0.0.0/16']
            }
        }
    )
    await async_poller.result()

    async_poller = await network_client.subnets.begin_create_or_update(
        GROUP_NAME,
        NETWORK_NAME,
        SUBNET_NAME,
        {'address_prefix': '10.0.0.0/24'}
    )
    subnet = await async_poller.result()

    # Create network interface
    async_poller = await network_client.network_interfaces.begin_create_or_update(
        GROUP_NAME,
        INTERFACE_NAME,
        {
            'location': "eastus",
            'ip_configurations': [{
                'name': 'MyIpConfig',
                'subnet': {
                    'id': subnet.id
                }
            }]
        } 
    )
    await async_poller.result()

    # Create virtual machine
    async_poller = await 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 + "",
                    "properties": {
                    "primary": True
                    }
                }
                ]
            }
        }
    )
    vm = await async_poller.result()
    print("Create virtual machine:\n{}".format(vm))

    # Create vm extension
    async_poller = await 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",
        }
    )
    extension = await async_poller.result()
    print("Create vm extension:\n{}".format(extension))

    # Get virtual machine
    vm = await compute_client.virtual_machines.get(
        GROUP_NAME,
        VIRTUAL_MACHINE_NAME
    )
    print("Get virtual machine:\n{}".format(vm))

    # List virtual machine (List operation will return asyncList)
    vms = list()
    async for vm in compute_client.virtual_machines.list(GROUP_NAME):
        vms.append(vm)
    print("List virtual machine:\n{}".format(vms))

    # Get vm extension
    extension = await 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
    async_poller = await 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
                }
            }
            ]
        }
        }
    )
    vm = await async_poller.result()
    print("Update virtual machine:\n{}".format(vm))

    # Update vm extension
    async_poller = await 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"
            }
        }
    )
    extension = await async_poller.result()
    print("Update vm extension:\n{}".format(extension))


    # Delete vm extension (Need vm started)
    async_poller = await compute_client.virtual_machines.begin_start(
        GROUP_NAME,
        VIRTUAL_MACHINE_NAME
    )
    await async_poller.result()

    async_poller = await compute_client.virtual_machine_extensions.begin_delete(
        GROUP_NAME,
        VIRTUAL_MACHINE_NAME,
        VIRTUAL_MACHINE_EXTENSION_NAME
    )
    await async_poller.result()
    print("Delete vm extension.\n")

    # Delete virtual machine
    async_poller = await compute_client.virtual_machines.begin_power_off(
        GROUP_NAME,
        VIRTUAL_MACHINE_NAME
    )
    await async_poller.result()

    async_poller = await compute_client.virtual_machines.begin_delete(
        GROUP_NAME,
        VIRTUAL_MACHINE_NAME
    )
    await async_poller.result()
    print("Delete virtual machine.\n")

    # Delete Group
    async_poller = await resource_client.resource_groups.begin_delete(
        GROUP_NAME
    )
    await async_poller.result()

    # [Warning] All clients and credentials need to be closed.
    # link: https://github.com/Azure/azure-sdk-for-python/issues/8990
    await resource_client.close()
    await compute_client.close()
    await network_client.close()
    await credential.close()
async 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/
    credential = DefaultAzureCredential()
    appconfig_client = AppConfigurationManagementClient(
        credential=credential, subscription_id=SUBSCRIPTION_ID)
    resource_client = ResourceManagementClient(credential=credential,
                                               subscription_id=SUBSCRIPTION_ID)

    # Create resource group
    await resource_client.resource_groups.create_or_update(
        GROUP_NAME, {"location": "eastus"})

    # Create appconfiguration store
    async_poller = await appconfig_client.configuration_stores.begin_create(
        GROUP_NAME, CONFIG_STORE_NAME, {
            "location": "eastus",
            "sku": {
                "name": "Standard"
            }
        })
    appconfig_store = await async_poller.result()
    print("Create appconfigruation store:\n{}".format(appconfig_store))

    # Get appconfiguration store
    appconfig_store = await appconfig_client.configuration_stores.get(
        GROUP_NAME, CONFIG_STORE_NAME)
    print("Get appconfigruation store:\n{}".format(appconfig_store))

    # List appconfiguration store (List operation will return asyncList)
    appconfig_stores = list()
    async for app_store in appconfig_client.configuration_stores.list():
        appconfig_stores.append(app_store)
    print("List appconfiguration stores:\n{}".format(appconfig_stores))

    # Update appconfiguration store
    async_poller = await appconfig_client.configuration_stores.begin_update(
        GROUP_NAME, CONFIG_STORE_NAME, {
            "tags": {
                "category": "Marketing"
            },
            "sku": {
                "name": "Standard"
            }
        })
    appconfig_store = await async_poller.result()
    print("Update appconfigruation store:\n{}".format(appconfig_store))

    # Delete appconfiguration store
    async_poller = await appconfig_client.configuration_stores.begin_delete(
        GROUP_NAME, CONFIG_STORE_NAME)
    await async_poller.result()
    print("Delete appconfiguration store")

    # Delete Group
    async_poller = await resource_client.resource_groups.begin_delete(
        GROUP_NAME)
    await async_poller.result()

    # [Warning] All clients and credentials need to be closed.
    # link: https://github.com/Azure/azure-sdk-for-python/issues/8990
    await appconfig_client.close()
    await resource_client.close()
    await credential.close()