概要
serverless frameworkをつかってプライベートAWSアカウントのコストを毎日プライベートなSlackに飛ばすlambda関数などを作ってみる。
今回はそのためのローカル開発環境構築を行う。
詳細
- PC: Mac(OS: 14.6.1)
- Node.jsのバージョン管理: Volta
- Node.jsバージョン: 20.11.1
方法
- 下記の記事を参考にserverless frameworkの環境を準備
-
上記の記事を参考に設定し、下記の様になったので前提条件は満たせていそう
[12:35:30]~/workspace/02_study/serverless_framework$ npm -v 10.2.4 [12:39:05]~/workspace/02_study/serverless_framework$ node -v v20.11.1 [12:39:07]~/workspace/02_study/serverless_framework$ volta -v 1.1.1 [12:39:13]~/workspace/02_study/serverless_framework$ aws -h usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters] To see help text, you can run: aws help aws <command> help aws <command> <subcommand> help aws: error: the following arguments are required: command
-
$ aws configure
コマンドを実行してデプロイしたいAWSアカウントの情報が正しく設定されていることを確認した -
ディレクトリ
aws-cost-notify
というディレクトリを作り、その中でserverless.ymlを作成し、下記のように記載aws-cost-notify/serverless.ymlapp: cost-monitoring service: aws-cost-notify provider: name: aws runtime: nodejs20.x region: ap-northeast-1 iamRoleStatements: - Effect: "Allow" Action: - "ce:GetCostAndUsage" Resource: "*" functions: notify: handler: handler.notify name: aws-cost-notify events: - eventBridge: eventBus: default pattern: source: - "aws.cost" detail-type: - "AWS Cost and Usage Report"
-
aws-cost-notify
ディレクトリにてコマンド$ serverless
を実行してserverless frameworkのプロジェクトを作成、作成過程で設定する内容があったので下記の様に指定(「Your Serverless Framework Service is ready to deploy.」のように出たのでデプロイ準備が整ったと思われる)✔ Create Or Select An Existing App: · Create A New App ✔ Name Your New App: · aws-cost-notify Your Serverless Framework Service is ready to deploy.
-
aws-cost-notify
ディレクトリにて下記を実行npm init -y npm install
-
aws-cost-notify
ディレクトリ直下にhandler.jsを作成し、下記のように記入aws-cost-notify/handler.jsexports.notify = async (event, context) => { try { console.log('コスト通知イベントを受信しました:', JSON.stringify(event)); // ここにコスト通知ロジックを実装 // 例: Slack通知、メール送信、データベース保存など return { statusCode: 200, body: JSON.stringify({ message: 'コスト通知が正常に処理されました' }) }; } catch (error) { console.error('エラーが発生しました:', error); return { statusCode: 500, body: JSON.stringify({ message: 'コスト通知の処理中にエラーが発生しました' }) }; } };
-
aws-cost-notify
ディレクトリにて下記を実行して一旦今の状態でデプロイを実施serverless deploy
-
AWSのマネジメントコンソールにログインしLambdaに移動、「aws-cost-notify」という関数が作られているはずなので開く
-
テストのタブを開き、hello-worldテストのデフォルトで「key_value」というテストを作成
-
作成したテストを実行し、下記のように値が返ったらデプロイ先のコードは問題ない