Table of Contents


Azure Functions Quickstart - Create, Debug, Deploy, Monitor

Here, we’ll learn quickly about Azure Functions. It’s a cloud service by Azure where you can run pieces of code without worry about server and hosting. We’ll start by setting up our workspace in VS Code and adding it with essential extensions. Then, we’ll test our function. After debugging, we’ll deploy it to Azure. Then, we’ll monitor its performance. If you want to know more, I’ve put some essential info in the appendix section.

Create

Let’s start by installing the following three Visual Studio Extensions and One Command Line Tool:

Extension Name Why Install? How to Install?
Azure Tools for Visual Studio Code This extension holds a collection of extensions, including the Azure Functions extension. While you can install just the Azure Functions extension in this ‘pack’, having the full collection is never bad Ctrl+Shift+X, “Azure Tools for Visual Studio Code”, InstallAlt text
Python extension for Visual Studio Code Provides extensive features for Python development, enabling linting, debugging, and IntelliSense for Azure Functions written in Python. Ctrl+Shift+X, “Python”, InstallAlt text
Azurite An Azure Storage emulator, crucial for local testing and debugging of Azure Functions. Ctrl+Shift+X, “Azurite”, Install. Alt text
Azure Functions Core Tools Command-line tools essential for local development and testing of Azure Functions. These tools enable local function runtime, debugging, and deployment capabilities. Install via npm with the command: npm install -g azure-functions-core-tools@3 --unsafe-perm true (for version 3.x) Or using GUI Alt text

Create the Azure Function Project

  • Open Visual Studio and Click the Azure Icon on the Left
  • In the Workspace (local) area, click the thunder button, and select Create New Project. Alt text
  • Choose a folder location for the project Alt text
  • Select Python as the programming language. Alt text
  • Opt for Model V2 as the programming model. Alt text
  • Choose the Python environment. Refer to the Appendix section for more details.
  • Select HTTP trigger. Refer to the appendix section below for more details. Alt text
  • Provide a unique name for our function. Alt text
  • VS Code will generate a complete project structure like shown below Alt text
  • Write your custom code, say you want to perform some blob operations, in function_app.py. This is the main/entry point function to the Fnction app.

Add Python packages to requirements.txt

Add library names of Python packages you imported in your script, like numpy , in requirements.txt.

  • When you start you local debugging VS Code will install the requirements.txt packages to your local python virtual enviornment’s .venv.

    Alt text

  • During actual deployment, VS Code will install the packages to Azure cloud.

Debug

Now, I will show you how to debug the azure function:

Test/Debug the Azure Function

  • With your function_app.py open press Ctrl+Shift+P. Select Azurite: Start.

    Alt text

    This action starts the Azurite storage Emulator. You can check the status at the bottom right corner of VS Code, where you should see something like this:

    Alt text

  • Press F5. Then, under Workspace Right-click the function and select Execute. Alt text

  • If the execution is successful, the output will be similar to this: Alt text

Deploy

Here I will show you how to deploy the function to Azure.

Create an Azure Function App

Now, our function is ready and we need to deploy it to Azure. To deploy an azure function we need Azure Function App. This is like a container for the function. You can create the Azure Function app from the portal. But, here I will show you how to do it right from VS code.

  • Click the Azure icon, then select the thunder icon in the workspace.

  • Choose Create Function app in Azure..(Advanced).

    Alt text

  • Assign a unique name to your function app.

    Alt text

  • If you’re working on an Azure Function in Python, ensure you set the runtime environment to Python.

    Alt text

  • Decide on using an existing resource group or create a new one. Ensure consistency in the chosen region.

    Alt text

  • Carefully select the hosting plan. If you’re budget-conscious, consider the Consumption-based plan.

    Alt text

  • Allocate a storage account for the Azure Function App. Using separate storage accounts for each function app simplifies the structure.

    Alt text

  • Incorporate an Application Insights resource for detailed insights and improved monitoring.

After these steps, your Azure Function App is set up. The next phase involves deploying your Azure Function to this newly created app.

Deploy the Azure Function To The Azure Function App

  • The deployment process is straightforward. In the workspace, click the thunder icon and choose Deploy to Function App. Alt text

  • Visual Studio Code will display the Function App where you can deploy our Azure Function. Select the Function App.

    Alt text

  • Click Deploy

    Alt text

    Note: This will overwrite ANY function present in the Azure Func app.

  • After successful deployment, you will see output like the following in the console:

    Alt text

  • And you can see the Function inside the Azure Function App:

    Alt text

Monitor

Afer deploying the function, I will show you how to monitor it in the portal.

Monitor the function post deployment

  • Open the Azure Function in the Azure portal.

    Alt text

  • Go to the “Monitor” section to access detailed information about function invocations.

Appendix

Key takeways

  • Azure function is different from Azure Function App. Azure Function app is the container which holds Azure Functions.
  • Azure functions can be developed using Python V2 Programming model, which uses decorators, lesser files, less-complex folder structure and a function_app.py
  • HTTP-triggered functions and Timer-triggered functions are common in Function apps. Timer-triggered function have in-built trigger mechanism.

When to choose Azure Functions

Imagine you’re thinking of using Azure Functions to convert JSON files to Parquet. Should you just use simple Python code in Azure Functions or go for Databricks? Here are some advantages and challenges of Azure Functions to help you decide:

Advantages:

  • Auto-scaling: The function can scale up and down. This means you don’t have to worry about resources if the workload increases, and you don’t have to be concerned about costs if it decreases.
  • Pay-as-long-as-you-use: You only pay for the actual time your code runs, making it very cost-efficient.
  • Triggers: It offers numerous event triggers and has a built-in timer for automatic scheduling.
  • Serverless: There’s no need to fret about server infrastructure. Just focus on writing the correct code.
  • The V2 programming model makes it easier and to create Azure functions. See section below.

Challenges:

  • Time Limit: There’s a limit to how long Azure Functions can run. If you have a big file or slow processing, it might not finish in time.

  • Not for Heavy Work: Azure Functions is good for small tasks. If you’re doing a lot of heavy calculations or have very big files, it might not be the best choice.

  • Slow Start: If your function is not used for a while and then suddenly starts, it might take a bit more time to begin, which can delay your processing.

For tasks that involve heavy data manipulation, transformation, and analysis, Databricks often becomes a preferred choice due to its scale-out architecture, optimized data processing capabilities, advanced dataframe support, built-in data cleansing tools, integrated machine learning libraries, and robust resource management. In contrast, for simpler tasks like just converting files, and when the data volume isn’t immense, Azure Functions can offer a speedy and cost-effective approach.

Azure Functions: V2 Python Programming Model Vs V1

The V2 programming model for Python, gives more Python-centric development experience for Azure Functions. Here are some key points about the V2 model:

  • Need fewer files for a function app, so you can have many functions in one file.
  • Decorators are used instead of the function.json file for triggers and things.
  • Blueprints are a new thing in V2. They help group functions in an app.
  • With blueprints, functions aren’t directly indexed. They need to be registered first.
  • All functions go in one function_app.py file, no need for many folders.
  • No need for the function.json file now. Decorators in the function_app.py file do the job.

The folder structure of Azure Functions(V2)

This is how the project folder structure looks like:

Alt text

Here is what each item means:

<project_root>/
├── 📁 .venv/ - (Optional) Python virtual environment.
├── 🛠 .venv/pyvenv.cfg - Local python, version, command.
├── 📁 .vscode/ - (Optional) VS Code config.
├── 🐍 function_app.py - Default location for functions.
├── 🐍 additional_functions.py - (Optional) Additional functions.
├── 📁 tests/ - (Optional) Test cases.
├── 🛠 .funcignore - (Optional) Declares ignored files.
├── 🌐 host.json - Configuration options.
├── 🏠 local.settings.json - Local app settings.
├── 📄 requirements.txt - Python packages for Azure.
└── 🐳 Dockerfile - (Optional) Custom container.

I will try to modify the section later to give you a better understanding of the project structure.

What is this Azurite

When you click F5 you will see a message which looks like the one below.

Alt text

This is where Azurite comes into play. Azurite is a free tool to mimic Azure Storage on your computer. It helps in testing Azure storage without actually using the real Azure services. It saves money,can work offline, its safe, and quick.

What happens during debugging

Here are the events that take place when you debug an Azure Function using VS Code:

Azure Function Core Tools Warms Up

  • The Azure Functions Core Tools will set up the libraries mentioned in the requirements.txt file to the virtual environment’s .venv\lib\site-packages using the command:
      Executing task: .venv\Scripts\python -m pip install -r requirements.txt
    

    Alt text

  • Then the virtual environment is activated with .venv\Scripts\activate.
  • It starts the debugger using func host start Alt text
  • Then it attaches to the Azure Function runtime, loads the Azure Function app and set a breakpoint at the first line of the code.
    • You’ll notice two main things in the output:
      • Functions: This lists down all functions in your Azure Function app.
      • A line like [2023-10-25T04:16:47.402Z] Host lock lease acquired by instance ID '0000000000000000000000002B26484C', tells that the debugger has locked the Azure Function host. This lock prevents the Azure Function host from being restarted by another process while the debugger is attached. Alt text

User Clicks Execute Function Now..

  • Now the user right-clicks on the function and clicks Execute function Now... This executes the function. Alt text
  • The rest is stepping through the function and checking if all is working fine. And, finally the debugging completes.

Common Errors

“AzureWebJobsStorage” app setting is not present

Alt text

The “AzureWebJobsStorage” app setting error indicates that our Azure Functions app is missing a crucial configuration related to the storage account connection string. This could also be realted to the following deployment failure message

12:23:58 PM FetchWeatherAzFunc: Deployment Log file does not exist in /tmp/oryx-build.log
12:23:58 PM FetchWeatherAzFunc: The logfile at /tmp/oryx-build.log is empty. Unable to fetch the summary of build
12:23:58 PM FetchWeatherAzFunc: Deployment Failed. deployer = ms-azuretools-vscode deploymentPath = Functions App ZipDeploy. Extract zip. Remote build.
12:24:00 PM FetchWeatherAzFunc: Deployment failed.
12:35:57 PM FetchWeatherAzFunc: Starting deployment.

To resolve this:

  • Create or Identify a Storage Account: If you don’t already have an Azure Storage account, create one in the same region as our function app.

  • Get the Storage Account Connection String: Navigate to the Azure Storage account in the Azure Portal. Under the “Settings” section, click on “Access keys.” Here, you’ll find two keys (key1 and key2) each with a connection string. You can use either of these connection strings for the next step.

  • Update Function App Settings:
    • Navigate to our Azure Functions app in the Azure Portal.
    • Under the “Settings” section, click on “Configuration.”
    • In the “Application settings” tab, locate or create the AzureWebJobsStorage setting.
    • Add the setting:
      • Name: AzureWebJobsStorage
      • Value: [our Azure Storage Account connection string from step 2]
    • Click “OK” or “Save” to add the setting and save our changes on the main configuration page.
  • Restart our Function App: After adding the necessary setting, restart our function app for the changes to take effect. Following these steps will resolve the error related to the “AzureWebJobsStorage” app setting.

© D Das
📧 das.d@hotmail.com | ddasdocs@gmail.com