
SAM で node_modules のファイルを編集したものをデプロイしてみた
この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
こんにちは。アノテーションの中村(誠)です。
今回は SAM で Node.js の node_modules 内のファイルを編集してデプロイする方法を紹介します。
結論
以下の方法で実現しました。
・編集したモジュールに対して、npx patch-package
を実行する
・package.json の scripts に、"postinstall": "npx patch-package"
を記載する
きっかけ
興味本位で「node_modules のファイルを編集したらデプロイ時にどうなるのか」ということを思いつきました。
とりあえずやってみるということで、SAM のチュートリアルレベルのアプリを作成してデプロイしてみました。
しかし、デフォルトの設定では、ローカル環境で編集した node_modules のファイルの内容は、デプロイ後の Lambda のデプロイパッケージには反映されていませんでした。
そこで、実現方法について調査したところ、以下の外部サイトがヒットしました。
上記のサイトで紹介されていた方法が、冒頭の結論で書いた方法でした。
ただし、検証しないと真偽が不明だったので、実際にサイト内の方法で実現可能かを検証しました。
検証環境
・OS: Windows 10
・SAM CLI バージョン: 1.53.0
・Node.js バージョン: 16.15.0
やってみた
実際にやってみた手順を紹介します。
1.サンプルアプリケーション作成
まずは SAM のサンプルアプリケーションを作成します。
特に変わった設定はせずに、サンプルアプリケーションを作成するだけです。
sam init
You can preselect a particular runtime or package type when using the `sam init` experience.
Call `sam init --help` to learn more.
Which template source would you like to use?
1 - AWS Quick Start Templates
2 - Custom Template Location
Choice: 1
Choose an AWS Quick Start application template
1 - Hello World Example
2 - Multi-step workflow
3 - Serverless API
4 - Scheduled task
5 - Standalone function
6 - Data processing
7 - Infrastructure event management
8 - Machine Learning
Template: 1
Use the most popular runtime and package type? (Python and zip) [y/N]: N
Which runtime would you like to use?
1 - dotnet6
2 - dotnet5.0
3 - dotnetcore3.1
4 - go1.x
5 - graalvm.java11 (provided.al2)
6 - graalvm.java17 (provided.al2)
7 - java11
8 - java8.al2
9 - java8
10 - nodejs16.x
11 - nodejs14.x
12 - nodejs12.x
13 - python3.9
14 - python3.8
15 - python3.7
16 - python3.6
17 - ruby2.7
18 - rust (provided.al2)
Runtime: 10
What package type would you like to use?
1 - Zip
2 - Image
Package type: 1
Select your starter template
1 - Hello World Example
2 - Hello World Example TypeScript
Template: 1
Would you like to enable X-Ray tracing on the function(s) in your application? [y/N]: N
Project name [sam-app]:
Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)
-----------------------
Generating application:
-----------------------
Name: sam-app
Runtime: nodejs16.x
Architectures: x86_64
Dependency Manager: npm
Application Template: hello-world
Output Directory: .
Next steps can be found in the README file at ./sam-app/README.md
Commands you can use next
=========================
[*] Create pipeline: cd sam-app && sam pipeline init --bootstrap
[*] Validate SAM template: sam validate
[*] Test Function in the Cloud: sam sync --stack-name {stack-name} --watch
もし、Windows 環境で、最後のクローンで失敗する場合には、GitHub Issue を参考に、以下のコマンドを Powershell の管理者権限で実行してください。
New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" `
-Name "LongPathsEnabled" -Value 1 -PropertyType DWORD -Force
私の環境では、上記コマンドを実行することで、エラーが解消され、サンプルアプリケーションのクローンをすることができました。
2.サンプルアプリケーションディレクトリ内でモジュールをインストール
サンプルアプリケーションディレクトリの、hello-world ディレクトリに移動し、aws-sdk をインストールします。
cd sam-app/hello-world
npm i aws-sdk
aws-sdk をインストールすると、hello-world ディレクトリ内に、node_modules が作成されます。
3.node_modules/aws-sdk/index.js を編集する
node_modules/aws-sdk/index.js は、デフォルトでは以下の内容です。
// Convenience file to require the SDK from the root of the repository
module.exports = require('./lib/aws');
今回は追加処理として、ログ出力処理を追記しました。
// Convenience file to require the SDK from the root of the repository
console.log("test")
module.exports = require('./lib/aws');
この追記した処理が、デプロイ後の Lambda のデプロイパッケージにも反映されていれば、目的は達成されます。
4.npx patch-package aws-sdk を実行
hello-world ディレクトリで、以下のコマンドを実行します。
npx patch-package aws-sdk
どうやらこのコマンドで、変更を加えたモジュールの内容を保持できるようになるようです。
5.package.json の scripts を編集する
hello-world ディレクトリ内の package.json の scripts に、以下の内容を追記します。
"postinstall": "npx patch-package"
追記後の scripts は以下のようになります。
"scripts": {
"test": "mocha tests/unit/",
"postinstall": "npx patch-package"
},
上記のスクリプトで、ビルド時に変更を加えたモジュールがインストールされるようになります。
6.ビルドを実行
サンプルアプリケーションのルートディレクトリに移動して、ビルドを実行します。
cd ../
sam build
ビルド後に、ルートディレクトリ配下の ./aws-sam/build/HelloWorldFunction/node_modules/aws-sdk/index.js の内容に、3 で追記した処理が反映されていることを確認します。
7.デプロイを実行
サンプルアプリケーションのルートディレクトリで、デプロイを実行します。
ほとんどデフォルト設定ですが、必要な場合には適宜変更してください。
sam deploy --guided --profile my-profile
Configuring SAM deploy
======================
Looking for config file [samconfig.toml] : Not found
Setting default arguments for 'sam deploy'
=========================================
Stack Name [sam-app]:
AWS Region [ap-northeast-1]:
#Shows you resources changes to be deployed and require a 'Y' to initiate deploy
Confirm changes before deploy [y/N]:
#SAM needs permission to be able to create roles to connect to the resources in your template
Allow SAM CLI IAM role creation [Y/n]:
#Preserves the state of previously provisioned resources when an operation fails
Disable rollback [y/N]:
HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
Save arguments to configuration file [Y/n]:
SAM configuration file [samconfig.toml]:
SAM configuration environment [default]:
Looking for resources needed for deployment:
Enter MFA code for arn:aws:iam::{account-id}:mfa/{user-name}:
Creating the required resources...
~ 以下、CloudFormation スタックの作成状況などは省略 ~
8.デプロイパッケージの確認
デプロイ完了後、Lambda コンソールからデプロイパッケージをダウンロードして、編集した node_modules/aws-sdk/index.js の内容が反映されているかを確認します。
反映されていることが確認できました。
以上が SAM で node_modules のファイルを編集したものをデプロイする手順です。
まとめ
今回は SAM で Node.js の node_modules 内のファイルを編集してデプロイする方法を紹介しました。 node_modules 内のファイルを編集する機会はあまりないかもしれませんが、参考になれば幸いです。
参考資料
- チュートリアル: Hello World アプリケーションのデプロイ - AWS Serverless Application Model
- node.js - How to edit a node module installed via npm? - Stack Overflow
アノテーション株式会社について
アノテーション株式会社は、クラスメソッド社のグループ企業として「オペレーション・エクセレンス」を担える企業を目指してチャレンジを続けています。「らしく働く、らしく生きる」のスローガンを掲げ、様々な背景をもつ多様なメンバーが自由度の高い働き方を通してお客様へサービスを提供し続けてきました。現在当社では一緒に会社を盛り上げていただけるメンバーを募集中です。少しでもご興味あれば、アノテーション株式会社 WEB サイトをご覧ください。