circleci config.yml: install nodejs, copy to server and run some extra commands

18 Views Asked by At

I have the following (simple) circleci config.yml file to deploy a nodejs repo after a push to the dev-branch:

version: 2.1

jobs:
  deploy-dev:
    machine:
      image: ubuntu-2204:2024.01.1
    steps:
      - add_ssh_keys:
          fingerprints:
            - "SSH_FINGERPRINT"
      - run: ssh -o StrictHostKeyChecking=no user@ip './deploy-dev.sh'

workflows:
  version: 2
  deploy:
    jobs:
      - deploy-dev:
          filters:
            branches:
              only:
                - dev

The deploy-dev.sh-file looks like this:

#!/bin/bash

npx pm2 kill
rm -rf repo
git clone -b dev [email protected]:user/repo.git
cd repo
npm i --no-optional
npx pm2 start index.js

The problem is: it's a private repo, so when I want to have multiple servers, I need a separate deploy key for each server on my github repo, otherwise git clone won't work.

Is there an option to add a job before 'deploy-dev' to get "download" the repo to circleci, and the copy it (with scp ...) to the server, and then run bash-script like this:

#!/bin/bash

cd repo
npm i --no-optional
npx pm2 restart index.js

Can someone help me with this?

Edit:

I've edited the config.yml file to something like this:

version: 2.1

jobs:
  deploy-dev:
    machine:
      image: ubuntu-2204:2024.01.1
    steps:
      - checkout
      - run: npm install
      - add_ssh_keys:
          fingerprints:
            - "SSH_FINGERPRINT"
      - run: ssh -o StrictHostKeyChecking=no user@ip'rm -rf ~/backend && mkdir ~/backend'
      - run: scp -o StrictHostKeyChecking=no -r ./* user@ip:~/backend
      - run: ssh -o StrictHostKeyChecking=no user@ip './deploy-dev.sh'

workflows:
  version: 2
  deploy:
    jobs:
      - deploy-dev:
          filters:
            branches:
              only:
                - dev

This works, but now the problem is that the scp-command is taking a long time to copy all the files to the server. It seems that like just doing a git clone && cd backend && npm install is a a lot faster.

What is the optimal way to deploy a nodejs repo to a server with circleci? It's not a website, it's an api. There is no npm build command, just npm install and starting the server with pm2. I also have some secrets from AWS secrets manager, I have a bash script to download these from aws and add them to an .env-file. This script should also run (this is done in deploy-dev.sh).

0

There are 0 best solutions below