Github Actioins にて SSH 接続した時に npm コマンドが not found になりエラーになった時の対応

環境

  • AmazonLinux 2023
  • Node v22

Command 'npm' not found

test.yml

下記のように SSH接続して npm コマンドを叩くようにしたら、
npm コマンドが見つからないというエラーが出た。

# This is a basic workflow to help you get started with Actions

name: TEST

# Controls when the workflow will run
on:
  # Triggers the workflow on push or pull request events but only for the "main" branch
  push:
    branches: [ "main" ]

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  ssh-test:
    runs-on: ubuntu-latest
    steps:
      - name: AWSにSSH接続する
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.EC2_HOST_01 }}
          username: ${{ secrets.EC2_USER }}
          key: ${{ secrets.EC2_KEY }}
          script: |
            git checkout main
            git pull origin main
            npm install
            npm run build

一応 node コマンドは使える

$ ssh デプロイ先のサーバー
$ node -v
v22.9.0

export してあげる

.bashrc や .zshrc に書いてある export コマンドの行を script に追加する。
自分は Node.js は nodebrew で管理しているので下記のようになる。

# This is a basic workflow to help you get started with Actions

name: TEST

# Controls when the workflow will run
on:
  # Triggers the workflow on push or pull request events but only for the "main" branch
  push:
    branches: [ "main" ]

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  ssh-test:
    runs-on: ubuntu-latest
    steps:
      - name: AWSにSSH接続する
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.EC2_HOST_01 }}
          username: ${{ secrets.EC2_USER }}
          key: ${{ secrets.EC2_KEY }}
          script: |
            export PATH=$HOME/.nodebrew/current/bin:$PATH
            git checkout main
            git pull origin main
            npm install
            npm run build