appleboy / ssh-action

GitHub Actions for executing remote ssh commands.
https://github.com/marketplace/actions/ssh-remote-commands
MIT License
4.84k stars 576 forks source link

accessing to GITHUB_ENV to write some data #325

Open DanyaKulko opened 5 months ago

DanyaKulko commented 5 months ago

I'm trying to write some data to GITHUB_ENV but it's empty during other step. I understand the problem but i don't know how to solve this. Here my action:

name: Backend deployment to server

on:
  push:
    branches:
      - '*'

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Deployment
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          password: ${{ secrets.PASSWORD }}
          script: |            
            export NVM_DIR="$HOME/.nvm"
            [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

            run_cmd() {
              if ! "$@"; then
                local cmd_failed="$@"
                echo "Command failed: $cmd_failed"
                echo "ERROR_MESSAGE='$cmd_failed'" >> $GITHUB_ENV
                echo "STATUS=failure" >> $GITHUB_ENV
                exit 1
              fi
            }

            run_cmd cd /home/test/server

            echo "Pulling the latest code from the repository"
            run_cmd git checkout $BRANCH_NAME
            run_cmd git pull origin $BRANCH_NAME

            echo "Installing dependencies"
            run_cmd npm install

            echo "Restarting the server"
            run_cmd pm2 startOrRestart ecosystem.config.cjs --env production

            echo "STATUS=success" >> $GITHUB_ENV
            echo "Deployment completed successfully"

      - name: Telegram Notification
        if: always()
        uses: DanyaKulko/telegram-deployment-notifications@main
        with:
          token: ${{ secrets.BOT_TOKEN }}
          chatId: ${{ secrets.CHAT_ID }}
          status: ${{ env.STATUS }}
          errorMessage: ${{ env.ERROR_MESSAGE }}

i also tried something like this

          run_cmd() {
              if ! "$@"; then
                local cmd_failed="$@"
                echo "::error::Command failed: $cmd_failed"
                exit 1
              fi
            }

....

      - name: Set success status
        if: success()
        run: echo "status=success" >> $GITHUB_ENV

      - name: Set failure status and capture error message
        if: failure()
        run: |
            echo "status=failure" >> $GITHUB_ENV
            error_message=$(echo '${{ steps.deploy_server.outputs.stderr }}' | grep '::error::' | sed 's/::error:://')
            echo "error_message=$error_message" >> $GITHUB_ENV

but in this case i can't get message error. As i think it happens because i try to write env on my ssh but i don't know how to resolve this