You are on page 1of 7

Azure Blob storage output binding for Azure

Functions
• Article
• 14 minutes to read



The output binding allows you to modify and delete blob storage data in an Azure Function.
For information on setup and configuration details, see the overview.

Example
• C#
• C# Script
• Java
• JavaScript
• PowerShell
• Python
The following example is a C# function that uses a blob trigger and two output blob bindings. The
function is triggered by the creation of an image blob in the sample-images container. It creates
small and medium size copies of the image blob.
C#
using System.Collections.Generic;
using System.IO;
using Microsoft.Azure.WebJobs;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

public class ResizeImages


{
[FunctionName("ResizeImage")]
public static void Run([BlobTrigger("sample-images/{name}")] Stream image,
[Blob("sample-images-sm/{name}", FileAccess.Write)] Stream imageSmall,
[Blob("sample-images-md/{name}", FileAccess.Write)] Stream imageMedium)
{
IImageFormat format;
using (Image<Rgba32> input = Image.Load<Rgba32>(image, out format))
{
ResizeImage(input, imageSmall, ImageSize.Small, format);
}

image.Position = 0;
using (Image<Rgba32> input = Image.Load<Rgba32>(image, out format))
{
ResizeImage(input, imageMedium, ImageSize.Medium, format);
}
}

public static void ResizeImage(Image<Rgba32> input, Stream output, ImageSize


size, IImageFormat format)
{
var dimensions = imageDimensionsTable[size];

input.Mutate(x => x.Resize(dimensions.Item1, dimensions.Item2));


input.Save(output, format);
}

public enum ImageSize { ExtraSmall, Small, Medium }

private static Dictionary<ImageSize, (int, int)> imageDimensionsTable = new


Dictionary<ImageSize, (int, int)>() {
{ ImageSize.ExtraSmall, (320, 200) },
{ ImageSize.Small, (640, 400) },
{ ImageSize.Medium, (800, 600) }
};

Attributes and annotations


• C#
• C# Script
• Java
• JavaScript
• PowerShell
• Python
In C# class libraries, use the BlobAttribute.
The attribute's constructor takes the path to the blob and a FileAccess parameter indicating read
or write, as shown in the following example:
C#
[FunctionName("ResizeImage")]
public static void Run(
[BlobTrigger("sample-images/{name}")] Stream image,
[Blob("sample-images-md/{name}", FileAccess.Write)] Stream imageSmall)
{
...
}

You can set the Connection property to specify the storage account to use, as shown in the
following example:
C#
[FunctionName("ResizeImage")]
public static void Run(
[BlobTrigger("sample-images/{name}")] Stream image,
[Blob("sample-images-md/{name}", FileAccess.Write, Connection =
"StorageConnectionAppSetting")] Stream imageSmall)
{
...
}

For a complete example, see Output example.


You can use the StorageAccount attribute to specify the storage account at class, method, or
parameter level. For more information, see Trigger - attributes.

Configuration
The following table explains the binding configuration properties that you set in the function.json
file and the Blob attribute.

Configuration
function.json Attribute
Description
property property
type n/a Must be set to blob.
Must be set to out for an output binding. Exceptions are noted
direction n/a
in the usage section.
The name of the variable that represents the blob in function
name n/a
code. Set to $return to reference the function return value.
path BlobPath The path to the blob container.
The name of an app setting or setting collection that specifies
connection Connection
how to connect to Azure Blobs. See Connections.
n/a Access Indicates whether you will be reading or writing.
When you're developing locally, app settings go into the local.settings.json file.

Connections
The connection property is a reference to environment configuration which specifies how the
app should connect to Azure Blobs. It may specify:
• The name of an application setting containing a connection string
• The name of a shared prefix for multiple application settings, together defining an identity-
based connection.
If the configured value is both an exact match for a single setting and a prefix match for other
settings, the exact match is used.

Connection string
To obtain a connection string, follow the steps shown at Manage storage account access keys. The
connection string must be for a general-purpose storage account, not a Blob storage account.
This connection string should be stored in an application setting with a name matching the value
specified by the connection property of the binding configuration.

If the app setting name begins with "AzureWebJobs", you can specify only the remainder of the
name here. For example, if you set connection to "MyStorage", the Functions runtime looks for
an app setting that is named "AzureWebJobsMyStorage." If you leave connection empty, the
Functions runtime uses the default Storage connection string in the app setting that is named
AzureWebJobsStorage.

Identity-based connections
If you are using version 5.x or higher of the extension, instead of using a connection string with a
secret, you can have the app use an Azure Active Directory identity. To do this, you would define
settings under a common prefix which maps to the connection property in the trigger and
binding configuration.
In this mode, the extension requires the following properties:
Identity-based connections
Environment variable
Property Description Example value
template
Blob <CONNECTION_NAME_ The data plane URI of the
Service PREFIX>__serviceU blob service to which you https://<storage_account_nam
are connecting, using the e>.blob.core.windows.net
URI ri1
HTTPS scheme.
1 <CONNECTION_NAME_PREFIX>__blobServiceUri can be used as an alias. If the

connection configuration will be used by a blob trigger, blobServiceUri must also be


accompanied by queueServiceUri. See below.

Additional properties may be set to customize the connection. See Common properties for identity-
based connections.
The serviceUri form cannot be used when the overall connection configuration is to be used
across blobs, queues, and/or tables. The URI itself can only designate the blob service. As an
alternative, you can provide a URI specifically for each service, allowing a single connection to be
used. If both versions are provided, the multi-service form will be used. To configure the connection
for multiple services, instead of <CONNECTION_NAME_PREFIX>__serviceUri, set:

Table 3
Environment variable
Property Description Example value
template
The data plane URI of
the blob service to
Blob Service <CONNECTION_NAME_PRE https://<storage_account_na
FIX>__blobServiceUri which you are
URI me>.blob.core.windows.net
connecting, using the
HTTPS scheme.
Queue Service <CONNECTION_NAME_PRE The data plane URI of https://<storage_account_na
URI FIX>__queueServiceUr a queue service, using me>.queue.core.windows.ne
(required for i the HTTPS scheme. t
blob This value is only
Environment variable
Property Description Example value
template
needed for blob
triggers2) triggers.
2 By default, the blob trigger uses Azure Queues internally. In the serviceUri form, the

AzureWebJobsStorage connection is used. However, when specifying blobServiceUri, a


queue service URI must also be provided with queueServiceUri. It is recommended that you
use the service from the same storage account as the blob service. You will also need to make sure
the trigger can read and write messages in the configured queue service by assigning a role like
Storage Queue Data Contributor.
When hosted in the Azure Functions service, identity-based connections use a managed identity.
The system-assigned identity is used by default, although a user-assigned identity can be specified
with the credential and clientID properties. When run in other contexts, such as local
development, your developer identity is used instead, although this can be customized. See Local
development with identity-based connections.

Grant permission to the identity


Whatever identity is being used must have permissions to perform the intended actions. You will
need to assign a role in Azure RBAC, using either built-in or custom roles which provide those
permissions.
Important
Some permissions might be exposed by the target service that are not necessary for all contexts.
Where possible, adhere to the principle of least privilege, granting the identity only required
privileges. For example, if the app only needs to be able to read from a data source, use a role that
only has permission to read. It would be inappropriate to assign a role that also allows writing to
that service, as this would be excessive permission for a read operation. Similarly, you would want
to ensure the role assignment is scoped only over the resources that need to be read.
You will need to create a role assignment that provides access to your blob container at runtime.
Management roles like Owner are not sufficient. The following table shows built-in roles that are
recommended when using the Blob Storage extension in normal operation. Your application may
require additional permissions based on the code you write.
Grant permission to the identity
Binding type Example built-in roles
Trigger Storage Blob Data Owner and Storage Queue Data Contributor1
Input binding Storage Blob Data Reader
Output binding Storage Blob Data Owner
1 By default, the blob trigger uses Azure Queues internally. It therefore also requires Storage Queue

Data Contributor permissions to create and receive messages.

Usage
• C#
• C# Script
• Java
• JavaScript
• PowerShell
• Python

Default
You can bind to the following types to write blobs:
• TextWriter
• out string
• out Byte[]
• CloudBlobStream
• Stream
• CloudBlobContainer1
• CloudBlobDirectory
• ICloudBlob2
• CloudBlockBlob2
• CloudPageBlob2
• CloudAppendBlob2
1 Requires "in" binding direction in function.json or FileAccess.Read in a C# class
library. However, you can use the container object that the runtime provides to do write operations,
such as uploading blobs to the container.
2 Requires "inout" binding direction in function.json or FileAccess.ReadWrite in a C#
class library.
If you try to bind to one of the Storage SDK types and get an error message, make sure that you
have a reference to the correct Storage SDK version.
Binding to string or Byte[] is only recommended if the blob size is small, as the entire blob
contents are loaded into memory. Generally, it is preferable to use a Stream or
CloudBlockBlob type. For more information, see Concurrency and memory usage earlier in this
article.

Additional types
Apps using the 5.0.0 or higher version of the Storage extension may also use types from the Azure
SDK for .NET. This version drops support for the legacy CloudBlobContainer,
CloudBlobDirectory, ICloudBlob, CloudBlockBlob, CloudPageBlob, and
CloudAppendBlob types in favor of the following types:

• BlobContainerClient1
• BlobClient2
• BlockBlobClient2
• PageBlobClient2
• AppendBlobClient2
• BlobBaseClient2
1 Requires "in" binding direction in function.json or FileAccess.Read in a C# class
library. However, you can use the container object that the runtime provides to do write operations,
such as uploading blobs to the container.
2 Requires "inout" binding direction in function.json or FileAccess.ReadWrite in a C#
class library.
For examples using these types, see the GitHub repository for the extension. Learn more about
these new types are different and how to migrate to them from the Azure.Storage.Blobs Migration
Guide.

Exceptions and return codes


Exceptions and return codes
Binding Reference
Blob Blob Error Codes
Blob, Table, Queue Storage Error Codes
Blob, Table, Queue Troubleshooting

The following example is a C# function that uses a queue trigger and an input blob binding. The
queue message contains the name of the blob, and the function logs the size of the blob.
C#
[FunctionName("BlobInput")]
public static void Run(
[QueueTrigger("myqueue-items")] string myQueueItem,
[Blob("samples-workitems/{queueTrigger}", FileAccess.Read)] Stream myBlob,
ILogger log)
{
log.LogInformation($"BlobInput processed blob\n Name:{myQueueItem} \n Size:
{myBlob.Length} bytes");
}

You might also like