Azure Classroomnotes 05/Mar/2022

Deploying Azure Functions with Managed Identity to access other Azure Services

  • Now deploy the Azure Function with the code
import logging

import azure.functions as func
from azure.mgmt.compute import ComputeManagementClient
from azure.identity import DefaultAzureCredential

subscription_id = "<your-subscription-id>"

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

def start_vm(credential, resource_group_name, vm_name):
    compute_client = ComputeManagementClient(credential, subscription_id)
    poller = compute_client.virtual_machines.begin_start(resource_group_name, vm_name)

def main(req: func.HttpRequest) -> func.HttpResponse:'Python HTTP trigger function processed a request.')

    rg_name = req.params.get('rg')
    vm_name = req.params.get('vm')
    action = req.params.get("action")
    if not rg_name:
            req_body = req.get_json()
        except ValueError:
            rg_name = 'elastic'
            vm_name = 'qtapche'
            action = "deallocate"
            rg_name = req_body.get('rg')
            vm_name = req_body.get('vm')
            action = req_body.get("action")
    credential = DefaultAzureCredential()
    if action == "deallocate":
        start_vm(credential, rg_name, vm_name)
    return func.HttpResponse(f"This HTTP triggered function executed successfully.")

    # if name:
    #     return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
    # else:
    #     return func.HttpResponse(
    #          "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
    #          status_code=200
    #     )

  • We we would get 5xx errors when we execute this code after deploying on azure as credential object might not get the credentials, so we need to add azure managed identity.
  • Note: As discussed in class Looking into various log areas would help to get more info about failures
  • Now after we have added the managed identity from http we are able to do vm operations as discussed in the class
  • Exercise:
    • Try to find an approach to fetch the subcription id programatically in your Azure function.

Leave a Reply

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

About continuous learner

devops & cloud enthusiastic learner