Open5
Amplify で Lambda Function 開発
開発内容
1日毎に定期実行するLambdaバッチを開発しAmplify Studio Functionsに登録する
注意点
Lambdaの実行可能時間を超過しないような構成にすること
参考
前提
Amplify Studioの環境構築が完了していること
Amplify Functionの作成
% amplify add function
? Select which capability you want to add: Lambda function (serverless function)
? Provide an AWS Lambda function name: n2photoapps2DailyCrawler
? Choose the runtime that you want to use: NodeJS
? Choose the function template that you want to use: Hello World
✅ Available advanced settings:
- Resource access permissions
- Scheduled recurring invocation
- Lambda layers configuration
- Environment variables configuration
- Secret values configuration
? Do you want to configure advanced settings? Yes
? Do you want to access other resources in this project from your Lambda function? Yes
? Select the categories you want this function to have access to.
You can access the following resource attributes as environment variables from your Lambda function
ENV
REGION
? Do you want to invoke this function on a recurring schedule? Yes
? At which interval should the function be invoked: Daily
? Select the start time in UTC (use arrow keys): 09:00 PM
? Do you want to enable Lambda layers for this function? No
? Do you want to configure environment variables for this function? No
? Do you want to configure secret values this function can access? No
✔ Choose the package manager that you want to use: · Yarn
? Do you want to edit the local lambda function now? No
✅ Successfully added resource {lambda name} locally.
✅ Next steps:
Check out sample function code generated in <project-dir>/amplify/backend/function/{lambda name}/src
"amplify function build" builds all of your functions currently in the project
"amplify mock function <functionName>" runs your function locally
To access AWS resources outside of this Amplify app, edit the ...amplify/backend/function/{lambda name}/custom-policies.json
"amplify push" builds all of your local backend resources and provisions them in the cloud
"amplify publish" builds all of your local backend and front-end resources (if you added hosting category) and provisions them in the cloud
amplify push で BEがデプロイされる
amplify publish でBE&FEがデプロされる
ローカルの amplify/backend/function/{function name}/src にソースが生成される
event.json はテストparameter
index.json が本体
package.json が依存ライブラリ
index.js
/* Amplify Params - DO NOT EDIT
ENV
REGION
Amplify Params - DO NOT EDIT */
/**
* @type {import('@types/aws-lambda').APIGatewayProxyHandler}
*/
exports.handler = async (event) => {
console.log(`EVENT: ${JSON.stringify(event)}`);
return {
statusCode: 200,
// Uncomment below to enable CORS requests
// headers: {
// "Access-Control-Allow-Origin": "*",
// "Access-Control-Allow-Headers": "*"
// },
body: JSON.stringify('Hello from Lambda!'),
};
};
ローカルbuildでエラー発生
$ amplify function build
✔ Are you sure you want to continue building the resources? (y/N) · yes
🛑 Received error [Error: Command failed with exit code 1: yarn --no-bin-links --production
Unknown Syntax Error: Unsupported option name ("--no-bin-links").
body: JSON.stringify('Hello from Lambda! Hey boy'),
に書き換えてローカルテスト実行
$ amplify mock function {function name}
Ensuring latest function changes are built...
Received error [Error: Command failed with exit code 1: yarn --no-bin-links --production
Unknown Syntax Error: Unsupported option name ("--no-bin-links").
エラー発生。
その後いろいろ調査したところ backend/function/(function name)/amplify.state ファイルを下記の通り書き換えると成功した。
amplify.state
+ "build": "npm install --no-bin-links --production"
- "build": "yarn --no-bin-links --production"
% amplify mock function n2photoapps2DailyCrawler
✔ Provide the path to the event JSON object relative to /Users/amonden/hitomio/n2-photo-apps2_staging/amplify/backend/function/n2photoapps2DailyCrawler · src/event.json
Ensuring latest function changes are built...
Starting execution...
EVENT: {"key1":"value1","key2":"value2","key3":"value3"}
✅ Result:
{
"statusCode": 200,
"body": "\"Hello from Lambda! Hey boy\""
}
Finished execution.
本来はamplify.stateは修正すべきでないので、そちらを認識した上で変更すること。
.gitignore
参考)
デプロイしてクラウドで実行
FEのReactのコードと違い、github経由ではなくローカルから直接デプロイされる
% amplify push
⠇ Building resource api/n2photoapps2✅ GraphQL schema compiled successfully.
Edit your schema at /Users/amonden/hitomio/n2-photo-apps2_staging/amplify/backend/api/n2photoapps2/schema.graphql or place .graphql files in a directory at /Users/amonden/hitomio/n2-photo-apps2_staging/amplify/backend/api/n2photoapps2/schema
✔ Successfully pulled backend environment staging from the cloud.
Current Environment: staging
┌──────────┬──────────────────────────┬───────────┬───────────────────┐
│ Category │ Resource name │ Operation │ Provider plugin │
├──────────┼──────────────────────────┼───────────┼───────────────────┤
│ Function │ n2photoapps2DailyCrawler │ Create │ awscloudformation │
├──────────┼──────────────────────────┼───────────┼───────────────────┤
│ Api │ n2photoapps2 │ No Change │ awscloudformation │
└──────────┴──────────────────────────┴───────────┴───────────────────┘
✔ Are you sure you want to continue? (Y/n) · yes
Deployment completed.
Deploying root stack n2photoapps2 [ ===========================------------- ] 2/3
amplify-n2photoapps2-staging-… AWS::CloudFormation::Stack UPDATE_COMPLETE_CLEANUP_IN_PR… Mon Aug 07 2023 21:36:32…
apin2photoapps2 AWS::CloudFormation::Stack UPDATE_COMPLETE Mon Aug 07 2023 21:34:58…
functionn2photoapps2DailyCraw… AWS::CloudFormation::Stack CREATE_COMPLETE Mon Aug 07 2023 21:36:30…
Deployed function n2photoapps2DailyCrawler [ ======================================== ] 5/5
LambdaExecutionRole AWS::IAM::Role CREATE_COMPLETE Mon Aug 07 2023 21:35:06…
LambdaFunction AWS::Lambda::Function CREATE_COMPLETE Mon Aug 07 2023 21:35:16…
lambdaexecutionpolicy AWS::IAM::Policy CREATE_COMPLETE Mon Aug 07 2023 21:35:35…
CloudWatchEvent AWS::Events::Rule CREATE_IN_PROGRESS Mon Aug 07 2023 21:35:18…
Deployment state saved successfully.
GraphQL transformer version: 2
✅ GraphQL schema compiled successfully.
Edit your schema at /Users/amonden/hitomio/n2-photo-apps2_staging/amplify/backend/api/n2photoapps2/schema.graphql or place .graphql files in a directory at /Users/amonden/hitomio/n2-photo-apps2_staging/amplify/backend/api/n2photoapps2/schema
✔ Synced UI components.
⚠️ UIBuilder components require version "^4.6.0" of "@aws-amplify/ui-react". You currently are on version "^5.0.6". Run `npm install "@aws-amplify/ui-react@^4.6.0"`. Required to leverage Amplify UI primitives, and Amplify Studio component helper functions.
デプロイ後、Amplify Studio - Set up - Functions - Deployed functions resources にデプロイされたことを確認する。
Function name に環境名が自動付与される。
下記エラーが発生し、amplify.state ファイルが存在しない場合
% amplify function build
✔ Are you sure you want to continue building the resources? (y/N) · yes
🛑 Received error [Error: Command failed with exit code 1: yarn --no-bin-links --production
Unknown Syntax Error: Unsupported option name ("--no-bin-links").