上传时如何更改对 AWS Lambda 层的引用?
How do I change references to an AWS Lambda Layer when it gets uploaded?
我正在使用 AWS Lambda 层来保留一些 node_modules 以及我自己的一些辅助函数,我将它们存储在一个名为 helpers
的文件夹中。从 AWS 文档中我看到要引用我必须做的层中的助手
require('/opt/layer/helpers/foo.js');
但是目前在我的代码中我将其设置为
require('./helpers/foo.js');
我想保持这种状态,这样我就可以在本地 运行。有没有一种方法可以保留第二条路径,并且只在我上传代码时将其更改为第一条路径(我正在使用来自 CLI 的 aws lambda update-function-code
)?
你可以在Lambda上测试一下你是不是运行,然后require相关的代码路径。例如:
const isLambda = !!process.env.LAMBDA_TASK_ROOT;
const foo = require(isLambda ? '/opt/layer/helpers/foo.js' : './helpers/foo.js');
您可以使用 sed
或等价物在您的代码库中自动执行此替换。
这是我最终编写的批处理脚本(针对 Windows)。在我的例子中,我所有助手的封闭文件夹被称为 /layer/helpers.
:: This batch file redeploys an existing lambda function
echo off
echo WARNING: this will delete any index.js or index.zip you have in the current directory!
pause
set /p toDeploy=Enter lambda name (without the .js):
powershell -Command "(gc %toDeploy%.js) -replace './helpers', '/opt/layer/helpers' | Out-File -encoding ASCII index.js"
powershell "Compress-Archive index.js index.zip"
aws lambda update-function-code --function-name %toDeploy% --zip-file fileb://index.zip
del index.js
del index.zip
我正在使用 AWS Lambda 层来保留一些 node_modules 以及我自己的一些辅助函数,我将它们存储在一个名为 helpers
的文件夹中。从 AWS 文档中我看到要引用我必须做的层中的助手
require('/opt/layer/helpers/foo.js');
但是目前在我的代码中我将其设置为
require('./helpers/foo.js');
我想保持这种状态,这样我就可以在本地 运行。有没有一种方法可以保留第二条路径,并且只在我上传代码时将其更改为第一条路径(我正在使用来自 CLI 的 aws lambda update-function-code
)?
你可以在Lambda上测试一下你是不是运行,然后require相关的代码路径。例如:
const isLambda = !!process.env.LAMBDA_TASK_ROOT;
const foo = require(isLambda ? '/opt/layer/helpers/foo.js' : './helpers/foo.js');
您可以使用 sed
或等价物在您的代码库中自动执行此替换。
这是我最终编写的批处理脚本(针对 Windows)。在我的例子中,我所有助手的封闭文件夹被称为 /layer/helpers.
:: This batch file redeploys an existing lambda function
echo off
echo WARNING: this will delete any index.js or index.zip you have in the current directory!
pause
set /p toDeploy=Enter lambda name (without the .js):
powershell -Command "(gc %toDeploy%.js) -replace './helpers', '/opt/layer/helpers' | Out-File -encoding ASCII index.js"
powershell "Compress-Archive index.js index.zip"
aws lambda update-function-code --function-name %toDeploy% --zip-file fileb://index.zip
del index.js
del index.zip