Autodeploy from GitLab to multiple aws ec2 instances

Luca Becchetti
Aug 7, 2017 · 2 min read

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”

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.

Create this variabile and enter the list of ip servers separated by comma, example:,

Step 2 — Create script

In the root folder of your project, at the same level of your .gitlab-ci.yml, create a file called, with this content:

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

Thats all, to run the script, commit your changes and use a link like in the image:

Luca Becchetti

Written by

I am a professional programmer with a background in software design and development, currently developing my qualitative skills on a startup company “Frind”