Autodeploy from GitLab to multiple aws ec2 instances
If you use gitlab to manage your repositories, you’ll love to use CI/CD Pipelines to perforom a continuous integration of your code. When your code passed all tests, the last thing to do it’s to deploy the current commit to your production server, or to multiple servers if you have a load balancer.
If you are under AWS environment, usually you log into your instance using a .pem certificate, with this little bash script, you will be able to deploy your code automatically to all your instances.
Step 1 — Create secrets variables
To run this script, you need two variables: “SSH_PRIVATE_KEY” and “DEPLOY_SERVER”. You can create variables from “settings > CI/CD Pipelines”
SSH_PRIVATE_KEY:
This is the certificate for the connection. Create first variable and past the content of your .pem certificate file used to connect to your ec2.
DEPLOY_SERVER:
Create this variabile and enter the list of ip servers separated by comma, example: 72.xxx.xxx.016,72.xxx.xxx.017
Step 2 — Create script
In the root folder of your project, at the same level of your .gitlab-ci.yml, create a file called .gitlab-deploy.sh, with this content:
#!/bin/bash#Get servers list
set -f
string=$DEPLOY_SERVER
array=(${string//,/ })#Iterate servers for deploy and pull last commit
for i in "${!array[@]}"do
echo "Deploy project on server ${array[i]}"
ssh ubuntu@${array[i]} "cd /var/www && git pull origin master"
done
This script can ssh on all servers and pull last commit, but to connect you need to pass a certificate, to do this, edit your .gitlab-ci.yml by adding or modify a production stage, like this:
Step 3 — Configure production stage
#Production stage
production:
stage: production
before_script:
#generate ssh key
- mkdir -p ~/.ssh
- echo -e "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
- chmod 600 ~/.ssh/id_rsa
- '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
script:
- bash .gitlab-deploy.sh
environment:
name: production
url: https://your.url.com
when: manual
Thats all, to run the script, commit your changes and use a link like in the image: