Azure Classroomnotes 04/Mar/2022

Using Azure SDK for Python

  • Added some useful functions
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient


def list_resources(credential, subscription_id, tag_name=None, tag_value=None):
    # create a resource management client
    resource_manager_client = ResourceManagementClient(credential, subscription_id)

    # rg_list = resource_manager_client.resource_groups.list()
    # for rg in rg_list:
    #     print(rg.name)

    resource_list = resource_manager_client.resources.list()
    if not (tag_name or  tag_value):
        # get all the resources
        for resource in resource_list:
            print(f"name = {resource.name}, type = {resource.type}")
    else:

        for resource in resource_list:
            if resource.tags:
                if tag_name in resource.tags and resource.tags[tag_name] == tag_value:
                    print(f"name = {resource.name}, type = {resource.type}")

def deallocate_vm(credential, subscription_id, resource_group_name, vm_name):
    compute_client = ComputeManagementClient(credential, subscription_id)
    poller = compute_client.virtual_machines.begin_deallocate(resource_group_name, vm_name)
    print(poller.status())
    poller.wait()
    print(poller.status())

if __name__ == "__main__":
    credential = AzureCliCredential()
    subscription_id = "ec402c1e-e1fd-4f6d-8501-77ab3f944a13"
    list_resources(credential, subscription_id, 'env', 'dev')
    #deallocate_vm(credential, subscription_id, "forsdk", "qttestsrv")

Activity

  • Lets Design a python function
    • which would stop all the vms which have a specific tag
    • which pauses the database which have a specific tag
    • which pauses the app service environments with a specific tag
  • steps
    • Get the Azure Credential
    • Get the subscription details
    • Fetch the resources from resource manager client
    • Find the resource with a tag
    • Find the right client to perform operation
  • Now we need to make it run on Azure Functions. In Azure Functions, we will not have AzureCliCredential. So we need to get the credentials in a different way and rest of the code can stay as it is.
  • For that we need to use managed identity which we will in our next session.
    Preview

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner