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)
print(poller.status())
#poller.wait()
#print(poller.status())
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)
print(poller.status())
#poller.wait()
#print(poller.status())
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('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:
try:
req_body = req.get_json()
except ValueError:
rg_name = 'elastic'
vm_name = 'qtapche'
action = "deallocate"
else:
rg_name = req_body.get('rg')
vm_name = req_body.get('vm')
action = req_body.get("action")
credential = DefaultAzureCredential()
if action == "deallocate":
deallocate_vm(credential,rg_name,vm_name)
else:
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.
Like this:
Like Loading...