7 min read

Azure functions help you easily run small pieces of code in the cloud without worrying about a whole application or the infrastructure to run it. With Azure functions, you can use triggers to execute your code and bindings to simplify the input and output of your code.

In this article, we will look at the anatomy and structure of an Azure Function. This article is taken from the book Learning Azure Functions by Manisha Yadav and Mitesh Soni. In this book, you will you learn the techniques of scaling your Azure functions and making the most of serverless architecture.

In this article, we will cover the following topics:

  • Anatomy of Azure Functions
  • Setting up a basic Azure Function

Anatomy of Azure Functions

Let’s understand the different components or resources that are used while creating Azure Functions.

The following image describes the Functions in Azure in different pricing plans:

Azure Function App

A function app is a collection of one or more functions that are managed together. All the functions in a Function App share the same pricing plan and it can be a consumption plan or an App Service plan. When we utilize Visual Studio Team Services for Continuous Integration and Continuous Delivery using build and release definitions, then the Function app is also shared. The way we manage different resources in Azure with the Azure Resource Group is similar to how we

can manage multiple functions with the Function App.

Function code

In this article, we will consider a scenario where a photography competition is held and photographers need to upload photographs to the portal. The moment a photograph is uploaded, a thumbnail should be created immediately.

A function code is the main content that executes and performs some operations as shown as follows:

var Jimp = require("jimp"); 
 
// JavaScript function must export a single function via module.exports 
// To find the function and execute it 
 
module.exports = (context, myBlob) => { 
// context is a must have parameter and first parameter always 
// context is used to pass data to and from the function 
//context name is not fixed; it can be anything 
 
    // Read Photograph with Jimp 
    Jimp.read(myBlob).then((image) => { 
        // Manipulate Photograph  
      // resize the Photograph. Jimp.AUTO can be passed as one of the values. 
        image 
            .resize(200, 200)  
            .quality(40) 
            .getBuffer(Jimp.MIME_JPEG, (error, stream) => { 
                // Check for errors while processing the Photograph. 
                if (error) { 
               // To print the message on log console 
                    context.log('There was an error processing the Photograph.'); 
               // To communicate with the runtime that function is finished to avoid timeout 
                    context.done(error); 
                } 
                else { 
               // To print the message on log console 
                    context.log('Successfully processed the Photograph'); 
                    // To communicate with the runtime that function is finished to avoid timeout   
               // Bind the stream to the output binding to create a new blob 
                    context.done(null, stream); 
                } 
            }); 
    }); 
};

Function configuration

Function configuration defines the function bindings and other configuration settings. It contains configurations such as the type of trigger, paths for blob containers, and so on:

{ 
  "bindings": [ 
    { 
      "name": "myBlob", 
      "type": "blobTrigger", 
      "direction": "in", 
      "path": "photographs/{name}", 
      "connection": "origphotography2017_STORAGE", 
      "dataType": "binary" 
    }, 
    { 
      "type": "blob", 
      "name": "$return", 
      "path": "thumbnails/{name}", 
      "connection": "origphotography2017_STORAGE", 
      "direction": "out" 
    } 
  ], 
  "disabled": false 
}

The function runtime uses this configuration file to decide which events to monitor and how to pass data to and from the function execution.

Function settings

We can limit the daily usage quota and application settings. We can enable Azure Function proxies and change the edit mode of our function app. The application settings in the Function App are similar to the application settings in Azure App Services. We can configure .NET Framework v4.6, Java version, Platform, ARR Affinity, remote debugging, remote Visual Studio version, app settings, and connection strings.

Runtime

The runtime is responsible for executing function code on the underlying WebJobs SDK host.

In the next section, we will create our Function App and functions using the Azure Portal.

Setting up a basic Azure Function

Let’s understand Azure Functions and create one in Azure Portal.

  1. Go to https://portal.azure.com. Click on Function Apps in the left sidebar:

There is no Function App available as of now.

  1. Click on the plus + sign and search for Function Apps. Then click on Create:

  1. Provide the App name, Subscription details, and existing Resource Group. Select Consumption Plan in Hosting Plan. Then select Location:

  1. Select Create New in Storage and click on Create:

  1. Now, let’s go to Function Apps in the left sidebar and verify whether the recently created Function App is available in the list or not:

  1. Click on the Function App and we can see the details related to the Subscription, Resource group, URL, Location, App Service Plan / pricing tier.

We can stop or restart the function from the same pane.

  1. The Settings tab provides details on the Runtime version, Application settings, and the limit on daily usage:

It also allows us to keep the Function App in Read/Write or Read Only mode. We can also enable deployment slots, a well-known feature of Azure App Services:

  1. In the Platform features tab as shown below, we get different kinds of options to enable the Function App with MONITORING, NETWORKING, DEPLOYMENT TOOLS, and so on. We will cover most of the features in this chapter and in upcoming chapters in detail:

  1. Click on Properties. Verify the different details that are available:

There is a property named OUTBOUND IP ADDRESSES which is useful if we need the IP addresses of the Function App for whitelisting.

  1. Click on App Service plan and it will open a consumption plan in the pane:

  1. On the left sidebar in the Azure Portal, go to Storage services and verify the storage accounts that are available:

What we want to achieve is that when we upload an image in a specific blob container, the function should be available immediately in the Function App and should be executed and create a thumbnail in another blob container.

  1. Create a new storage account:

  1. Go to the Overview section of the Storage accounts and check all the available settings:

  1. Click on the Containers section in the Storage accounts:

There is no container available in the Storage accounts.

  1. Click on + Container and fill in the Name and Access type and click on OK:

  1. Similarly, create another container to store thumbnails:

  1. Verify both containers in the Storage accounts:

Once we have all the components ready to achieve our main objective of creating a function that creates thumbnails of photographs, we can start creating a function:

  1. Click on the Functions section in the Function App:

  1. Select Webhook + API and then choose a language:

  1. Click on Custom function so that we can utilize the already available templates:

  1. Select the Language as JavaScript:

  1. Select the BlobTrigger template:

  1. Provide the name of our function.
  2. Give the path to the container for the source and select Storage account connection:

  1. Look at the function and code available in the code editor in the Microsoft Azure Portal:

Before we write the actual code in the function, let’s configure the triggers and outputs:

  1. Select Blob parameter name, Storage account connection, and Path:

  1. Click on New Output.
  2. Select Azure Blob Storage:

  1. Select Blob parameter name, Storage account connection, and Path.
  2. Click on Save:

  1. Review the final output bindings:

  1. Click on the advanced editor link to review function.json:

  1. Now, paste the function code for creating a thumbnail into the Functions code editor:

Now, once everything is set and configured, let’s upload a photograph in the photographs blob container:

  1. Click on the container and click on Upload. Select the photograph that needs to be uploaded to the container.
  1. Click on Upload:

  1. Go to Function Apps and check the logs.
  2. We may get an Error: Cannot find module ‘jimp’:
2017-06-30T16:54:18 Welcome, you are now connected to log-streaming service.
2017-06-30T16:54:41.202 Script for function 'photoProcessing' changed. Reloading.
2017-06-30T16:55:01.309 Function started (Id=411e4d84-5ef0-4ca9-b963-ed94c0ba8e84)
2017-06-30T16:55:01.371 Function completed (Failure, Id=411e4d84-5ef0-4ca9-b963-ed94c0ba8e84, Duration=59ms)
2017-06-30T16:55:01.418 Exception while executing function: Functions.photoProcessing. mscorlib: Error: Cannot find module 'jimp'
at Function.Module._resolveFilename (module.js:455:15)
at Function.Module._load (module.js:403:25)
at Module.require (module.js:483:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\home\site\wwwroot\photoProcessing\index.js:1:74)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3).

Thus we created our first function that processes a photograph and creates a thumbnail for a photography competition scenario. We also saw the anatomy of Azure Functions. To know more on how triggers can activate a function, and how binding can be used to output the results of a function, read our book Learning Azure Functions.

Read Next

Azure DevOps outage root cause analysis starring greedy threads and rogue scale units.

Working with Azure container service cluster [Tutorial].

Implementing Identity Security in Microsoft Azure [Tutorial].

Content Marketing Editor at Packt Hub. I blog about new and upcoming tech trends ranging from Data science, Web development, Programming, Cloud & Networking, IoT, Security and Game development.