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
Related
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.
I am working on an Azure SignalR application and everything is working fine on my local machine when I set the following section in my appsettings.json:
"Azure": {
"SignalR": {
"ConnectionString": "XXXXX"
}
}
And then initialize in my startup.cs as follows:
services.AddSignalR().AddAzureSignalR();
However when I create the same environment variable in my Azure App Service using App Service>Configration>ApplicationSettings:
My application is unable to start and I get the following application error:
System.ArgumentException: Connection string missing required properties endpoint and accesskey. (Parameter 'connectionString')
at Microsoft.Azure.SignalR.ConnectionStringParser.Parse(String connectionString)
at Microsoft.Azure.SignalR.ServiceEndpoint..ctor(String connectionString, EndpointType type, String name)
When I hardcore my connection string onto the AddAzureSignalR() connectionstring parameter and deploy everything works fine.
It would seem that azuresignalR is unable to pickup this environment variable, despite also being able to see it via the Kudo Appsettings page as Azure:SginalR:ConnectionString.
You need to initiate like this,
string azureSignalrConnectionString = configuration["Azure:SignalR:ConnectionString"];
services.AddSignalR().AddNewtonsoftJsonProtocol().AddAzureSignalR(options =>
{
options.ConnectionString = azureSignalrConnectionString;
});
So I asked this same question on the Azure SignalR github page and below was the answer I got:
EnvironmentVariablesConfigurationProvider automatically replaces __
with : . So when you configures connection string via environment
variables, you should use Azure__SignalR__ConnectionString as the key.
When you configures it via JSON file, you should use the origin key
Azure:SignalR:ConnectionString.
Once I changed it to the double underscores all worked
For net core 5, use:
string azureSignalrConnectionString = Configuration["Azure:SignalR:ConnectionString"];
services.AddSignalR()
.AddAzureSignalR(options =>
{
options.ConnectionString = azureSignalrConnectionString;
});
appsettings.json, like:
{
"Azure": {
"SignalR": {
"ConnectionString": "<your-connection-string>"
}
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
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"
}
}
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.
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.