【问题标题】:How to set environment variables or inputs in timerTrigger Azure Functions?如何在 timerTrigger Azure Functions 中设置环境变量或输入?
【发布时间】:2019-03-15 12:54:44
【问题描述】:

我正在尝试设置 timerTrigger azure 函数

我的function.json

{
    "disabled": false,
    "bindings": [
        {
            "type": "timerTrigger",
            "direction": "in",
            "name": "sampleCronTrigger",
            "schedule": "*/5 * * * * *",
        }
    ],
    "entryPoint": "sampleCron",
    "scriptFile": "index.js"
}

在此我需要设置一个环境变量,但我无法这样做。我尝试查找一些文档,但找不到不需要在 Azure 控制台上进行某些设置的任何内容?

我可以定义环境变量吗?或者,如果我可以通过任何方式将输入传递给函数,那也可以。

【问题讨论】:

标签: node.js azure azure-functions


【解决方案1】:

函数应用中的应用设置包含影响该函数应用的所有函数的全局配置选项。当您在本地运行时,这些设置以local environment variables 访问。

本地设置文件 文件 local.settings.json 存储应用设置、连接字符串和 Azure Functions Core Tools 的设置。 local.settings.json 文件中的设置仅在本地运行时由 Functions 工具使用。默认情况下,当项目发布到 Azure 时,这些设置不会自动迁移。发布时使用 --publish-local-settings 开关,以确保将这些设置添加到 Azure 中的函数应用。

在 Functions 中,应用程序设置(例如服务连接字符串)在执行期间作为环境变量公开。您可以使用 process.env 访问这些设置,如 GetEnvironmentVariable 函数中所示:

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];
}

您可以通过多种方式添加、更新和删除函数应用设置:

在本地运行时,从 local.settings.json 项目文件中读取应用设置。

参考资料:

【讨论】:

  • 是否可以在功能级别而不是服务级别创建local.settings.json
  • 不行,整个应用只能有一个 local.settings.json。
【解决方案2】:

另外,为了从 local.settings.json 中检索值,另一种方法是使用 ExecutionContext executionContext 创建一个 IConfigurationRoot 对象。

ExecutionContext 可以添加到函数定义中:

[FunctionName("FunctionName")]
        public static async Task Run(
            [ServiceBusTrigger(...)]
            SomeMessage msg,
            ILogger log,
            ExecutionContext executionContext)
{
}

之后,您可以实例化一个 IConfigurationRoot 实例,您可以指示该实例选择性地加载 local.appsettings.json。

  var configurationRoot = new ConfigurationBuilder()
            .SetBasePath(executionContext.FunctionAppDirectory)
            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build();

使用 configurationRoot 对象,您可以检索配置值:

 var value = configurationRoot["SomeKey"];

local.settings.json 示例:

{
 "IsEncrypted": false,
 "Values": {
  "AzureWebJobsStorage": "...",
  "FUNCTIONS_WORKER_RUNTIME": "dotnet",
  "SomeKey": "Value",
},
"Host": {
 "LocalHttpPort": "7071"
}
}

【讨论】:

    猜你喜欢
    • 2021-07-28
    • 2021-09-23
    • 1970-01-01
    • 2016-11-29
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    相关资源
    最近更新 更多