How to auto-deploy on ec2 with gitlab runners?

I want to automatically deploy a node.js project to gitlab.

I am currently using below config 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 correct since I go into ec2 and do all the operations?

What are other ways to do the same?

+3


source to share


1 answer


I found a way to deploy with ssm agent , with which we can deploy multiple EC2 instances using tags (no -pem switch required)

Steps:

1) Install SSM on EC2 instance, mark this instance as environment = qa

2) Use Gitlab runner to send command to these flagged 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 the above command

--targets

indicates which ec2 instances we are deploying are tagged

--parameters commands

determines which commands to run on the ec2 instance. I ran git pull

with the latest code andpm2 start

Hope this helps someone.

0


source







All Articles