4

I want to auto deploy node.js project on gitlab.

Currently I'm using below configuration on .gitlab-ci.yml

deploy_to_dev_aws:
  only:
    - development
  script:
    - echo "$EC2_SSH_KEY" >> "key.pem"
    - chmod 600 key.pem
    - ssh -T -i key.pem -o StrictHostKeyChecking=no ubuntu@$EC2_HOST_IP <<EOF
    - cd ~/projects
    - rm myproject
    - git checkout git://myprojectpath
    - cd myproject
    - pm2 delete all
    - pm2 start app.js
    - logout
    - EOF
  stage: build

Is this right way, as I'm log in into ec2 and performing all operations?

What are other ways to do the same?

Jagdish Idhate
  • 7,513
  • 9
  • 35
  • 51
  • Did you find anything? looking for the same. – viggy28 Jan 27 '18 at 22:36
  • https://stackoverflow.com/questions/36437278/automate-code-deploy-from-git-lab-to-aws-ec2-instance. Just scary that how deeply we need to integrate with AWS to achieve. I hope a simpler solution is available. – viggy28 Jan 27 '18 at 22:42

1 Answers1

1

I found a way to deploy using ssm agent by which we can deploy to multiple EC2 instances using tags(.pem key not required)

Steps:

1) Install SSM on EC2 instance, tag that instance as environment=qa

2) Use Gitlab runner to send command to this tagged instances

deploy_to_prod_dev_aws:
  image: python:latest
  only:
    - qa
  script:
    - pip install awscli
    - export AWS_ACCESS_KEY_ID=$AWS_KEY_ID
    - export AWS_SECRET_ACCESS_KEY=$AWS_SECRET
    - export AWS_DEFAULT_REGION=$AWS_REGION
    - aws ssm send-command --targets "Key=tag:environment,Values=qa" --document-name "AWS-RunShellScript" --comment "Deployment" --parameters commands="cd /project && git clean -fd && git fetch && git checkout qa && git pull origin qa && npm install && pm2 delete all && pm2 start app.js" --output text
  stage: build
  environment:
    name: qa

In above command

--targets specifies which ec2 instances to which we are be deploying defined by tags

--parameters commands defines which commands to run on ec2 instance.I ran git pull with latest code & pm2 start

Hope this will help someone.

Jagdish Idhate
  • 7,513
  • 9
  • 35
  • 51