Timer based trigger - Testing locally - azure

Trying to test CRON trigger function app locally but getting an error:
"The listener for function 'Functions.timer' was unable to start. Microsoft.Azure.WebJobs.Script: Could not create BlobServiceClient to obtain the BlobContainerClient using Connection: Storage."
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "node",
"ConnectionStrings:BlobStorageAccount": "UseDevelopmentStorage=true"
}
}
function.json
{
"bindings": [
{
"schedule": "*/1 * * * *",
"name": "reportScheduler",
"type": "timerTrigger",
"direction": "in"
}
],
"disabled": false
}
and index.js
const timer = async function(context, req) {
context.log("=======PROCESSED=======");
context.res = {
// status: 200, /* Defaults to 200 */
body: "HELLO WORLD",
};
};
module.exports = timer;
Really struggling with the documentation specifically around these error messages and translating those into the required changes in local.settings.json
other information:
npm i -g azure-functions-core-tools#3 --unsafe-perm true
func start

To run the azure functions (whatever the trigger type), need the azure functions core tools to be installed in your system.
That you can install using npm command or executable file installation available in this documentation.
Note: To install the azure function core tools using npm command is: npm i -g azure-functions-core-tools#3 --unsafe-perm true and you have to run this command in integrated terminal of Visual Studio Code.
For Windows, integrated terminal of VS Code is PowerShell, here you can find the integrated terminal:
To Create and run the Timer Triggered Function, please refer this documentation for step by step procedure.
I have created the timer trigger JavaScript Azure Function and started to run the function using command func start, running successfully:
I set the CRON expression to every minute for running the function so it is showing the function runs at every minute in the above output console.
local.settings.json code:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "node"
}
}
And
In your index.js:
const timer = async function(context, req
The req object refers to http request class so the req and res objects should be defined in function.json class like:
This documentation refers to Azure JavaScript Function Http Trigger.

Related

process.env variable undefined on test using Jest in Azure function(Nodejs)

process.env variable showing undefined while running yarn run jest. I have stored every config variables in my local.settings.json file, and it is working perfectly in normal debug.
My code is like this:
local.settings.json:
{
"IsEncrypted": false,
"Host": {
"LocalHttpPort": 7071,
"CORS": "*"
},
"Values": {
"IOTHUB_CONNECTION_STRING": "xxxxxxxxxxxxxxxxxx",
"AZURE_DEVOPS_URL": "xxxxxxxxxxxxxxxxxxxx"
}
}
jest.config.js:
module.exports = {
log: jest.fn(),
}
azure httptrigger function - index.js:
const iothubConnectionString = process.env["IOTHUB_CONNECTION_STRING"];
console.log( iothubConnectionString ) //undefined
My tests fail due to these configuration variables. I need to pass the test. anyone can you please help me.
local.settings.json is specific to Azure Functions Core Tools. As long as you use Core Tools CLI to run the function you can access environment variables defined in this file via process.env

How to set environment variables or inputs in timerTrigger Azure Functions?

I am trying to setup a timerTrigger azure function
My function.json:
{
"disabled": false,
"bindings": [
{
"type": "timerTrigger",
"direction": "in",
"name": "sampleCronTrigger",
"schedule": "*/5 * * * * *",
}
],
"entryPoint": "sampleCron",
"scriptFile": "index.js"
}
In this I need to set an environment variable, but I am not able to do so. I tried looking for some documentation but couldn't find anything which doesn't require some setup on the Azure console?
I can I define environment variables? Or If here is any way I can pass an input to the function, that works too.
App settings in a function app contain global configuration options that affect all functions for that function app. When you run locally, these settings are accessed as local environment variables.
Local settings file
The file local.settings.json stores app settings, connection strings, and settings for Azure Functions Core Tools. Settings in the local.settings.json file are only used by Functions tools when running locally. By default, these settings are not migrated automatically when the project is published to Azure. Use the --publish-local-settings switch when you publish to make sure these settings are added to the function app in Azure.
In Functions, app settings, such as service connection strings, are exposed as environment variables during execution. You can access these settings using process.env, as shown here in the GetEnvironmentVariable function:
module.exports = function (context, myTimer) {
var timeStamp = new Date().toISOString();
context.log('Node.js timer trigger function ran!', timeStamp);
context.log(GetEnvironmentVariable("AzureWebJobsStorage"));
context.log(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
context.done();
};
function GetEnvironmentVariable(name)
{
return name + ": " + process.env[name];
}
There are several ways that you can add, update, and delete function app settings:
From Azure portal.
By using the Azure CLI.
When running locally, app settings are read from the local.settings.json project file.
References:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-app-settings
https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node#environment-variables
https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node#environment-variables
Additionally for retrieving values from local.settings.json, another way is to create an IConfigurationRoot object using ExecutionContext executionContext.
ExecutionContext can be added to function definition:
[FunctionName("FunctionName")]
public static async Task Run(
[ServiceBusTrigger(...)]
SomeMessage msg,
ILogger log,
ExecutionContext executionContext)
{
}
After that, you can instantiate an IConfigurationRoot instance, which you instruct to optionally load local.appsettings.json.
var configurationRoot = new ConfigurationBuilder()
.SetBasePath(executionContext.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
With the configurationRoot object, you can retrieve configuration values:
var value = configurationRoot["SomeKey"];
Example local.settings.json:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "...",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"SomeKey": "Value",
},
"Host": {
"LocalHttpPort": "7071"
}
}

How to add record to Azure Table Storage from Azure Functions with binding?

I user those and run Azure Functions at local environment.
Azure Functions Core Tools (2.0.3)
Function Runtime Version:2.0.12115.0
azurite#2.7.0
I try as Microsoft document says.
Here is functions.json
{
"bindings": [
{
"name": "input",
"type": "httpTrigger",
"direction": "in"
},
{
"tableName": "Person",
"connection": "MyStorageConnectionAppSetting",
"name": "tableBinding",
"type": "table",
"direction": "out"
}
],
"disabled": false
}
Here is local.settings.json
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "node",
"MyStorageConnectionAppSetting": "UseDevelopmentStorage=true"
}
}
Here is index.js
module.exports = function (context) {
context.bindings.tableBinding = [];
for (var i = 1; i < 10; i++) {
context.bindings.tableBinding.push({
PartitionKey: "Test",
RowKey: i.toString(),
Name: "Name " + i
});
}
context.done();
};
Installed extensions with this.
$ func extensions install -p Microsoft.Azure.WebJobs.Extensions.Storage --version 3.0.0
Run functions from mac terminal, Send http request, I got this error.
System.Private.CoreLib: Exception while executing function:
Functions.test. Microsoft.Azure.WebJobs.Host: Error while handling
parameter _binder after function returned:.
Microsoft.Azure.WebJobs.Extensions.Storage: Not Implemented (HTTP
status code 501: . ). Microsoft.WindowsAzure.Storage: Not Implemented.
Error from Table Storage
POST /devstoreaccount1/$batch 501 0.980 ms - 45
Any help?
UseDevelopmentStorage=true represents function is set to use Storage emulator, which provides a local environment that emulates the Azure Storage Blob, Queue and Table services for development purposes. But unfortunately it's only available on OS Windows, so you got Not Implemented on Mac.
Workaround is to use a real world Storage account, follow the tutorial to get the Connection string, if you don't have a Storage account you may have to create one first.
One more suggestion is install latest Azure Functions Core Tools, right now it's 2.1.725.

Unable to run cosmosDB trigger locally with Azure Function Core Tools

I am trying to run an azure function locally on my laptop using the Azure Functions Core Tools. Notice that this function is configured as a cosmosDB trigger
I was partially inspired by the instructions in this tutorial
I started by creating a function called MyFirstFunction with the following commands (and inserting the required inputs when prompted):
func init
func start
My generated javascript function is (the same the Azure portal creates for the same kind of template function):
module.exports = function (context, documents) {
if (!!documents && documents.length > 0) {
context.log('Document Id: ', documents[0].id);
}
context.done();
}
My generated function.json is:
{
"bindings":
[
{
"type": "cosmosDBTrigger",
"name": "documents",
"direction": "in",
"leaseCollectionName": "leases"
}
]
}
My generated local.settings.json is
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "node",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}
Given this setup I try to run the function by executing:
func host start
Everything runs fine in the console output until the error message:
Unable to configure binding 'documents' of type 'cosmosDBTrigger'. This may indicate invalid function.json properties. Can't figure out which ctor to call.
What I missing? I was supposed to trigger the function through an http POST to:
http://localhost:{port}/admin/functions/{function_name}
as explained in the tutorial linked above (being this function a cosmosDB trigger) but the function cannot even be loaded after this error.
What am I missing to run a cosmosDB trigger locally?
Many thanks.
The problem is your local.settings.json and function.json lack necessary configuration of cosmosdb connection string.
See cosmosdb trigger document.
function.json
{
"bindings":
[
{
"type": "cosmosDBTrigger",
"name": "documents",
"direction": "in",
"leaseCollectionName": "leases",
// Missed in your code
"connectionStringSetting": "CosmosDBConnectionString",
"databaseName": "<Get db name>",
"collectionName": "<Get coll name>",
"createLeaseCollectionIfNotExists": true
}
]
}
local.settings.json
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "node",
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
//Missed in your code
"CosmosDBConnectionString":"<Get connection string from Azure portal>"
}
}
Note that in latest version of function core tools(2.0.1-beta.31), no need to register CosmosDB extension if you use func new to create CosmosDB Trigger, tools will install it automatically.
After this problem solved, if you met another error about Microsoft.Azure.Documents.ServiceInterop.dll
The listener for function 'Functions.CosmosDb' was unable to start.
The listener for function 'Functions.CosmosDb' was unable to start. System.Private.CoreLib: One or more errors occurred. (Unable to load DLL 'Microsoft.Azure.Documents.ServiceInterop.dll' or one of its dependencies: The specified module could not be found. (Exception from HRESULT: 0x8007007E)).
Microsoft.Azure.DocumentDB.Core: Unable to load DLL 'Microsoft.Azure.Documents.ServiceInterop.dll' or one of its dependencies: The specified module could not be found. (Exception from HRESULT: 0x8007007E).
Just install one package to fix(See this issue)
func extensions install -p Microsoft.Azure.DocumentDB.Core -v 2.0.0-preview
Then everything should work.

How to get a connection string environment variable in an Azure function running locally?

I am trying to setup an Azure Function to run locally on my development environment. I wish to connect to a MongoDb database instance.
In my local.settings.json file I have added:
"ConnectionStrings": {
"DB_CONNECT_STRING": "mongodb://localhost:27017/MyDatabase"
}
In my function I then have:
module.exports = function (context, myTimer) {
console.log(process.env.DB_CONNECT_STRING);
context.done();
};
process.env.DB_CONNECT_STRING is undefined.
I assume I need to add some kind of prefix to the environment variable, but I can't find this documented anywhere. How do I specify a connection string and reference it in the function code?
Matt Mason is right.
In Node.js, we should specify app settings in the Values collection. These settings can then be read as environment variables by using process.env.
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"DB_CONNECT_STRING": "mongodb://localhost:27017/MyDatabase"
}
}
Then use process.env.DB_CONNECT_STRING to get the value.
For the purists out there, I found it. I set a breakpoint and evaluated "process.env" and found my connection string in this format:
ConnectionStrings:<ConnectionName>
So if my local.settings.json looks like this:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "node",
},
"Host": {
"CORS": "http://localhost:8080"
},
"ConnectionStrings": {
"Prod": "MyConnString"
}
}
Then I would access it like this:
const sqlConnString = process.env['ConnectionStrings:Prod'];
You have to use bracket notation because of the colon.

Resources