GitLab (CI) and AWS is a great team to automatically build and deploy your code. Especially for static websites its very easy to do this. In this article i will tell you how.
First of all you need a existing S3 Bucket where the website content, a CloudFront Delivery, a Route53 Record and a SSL Certificate for this domain would also be great to have. To create this things have a look at my first article Create a static Website using AWS and Terraform (Infrastructure as Code). When you get all of these you can start collecting the following the following informations:
Setup the GitLab Project: Create the GitLab Project (If it not already exists). Make sure this project is marked as private because it will contain some credentials to your AWS Account.
Next we create some environment variables for the .gitlab-ci.yaml file. This can be done by going to project settings -> CI/CD -> Variables and should look like this:
Now for the exciting part: Create a file named .gitlab-ci.yaml or .gitlab-ci.yml inside the root of your project and put the following code in your project:
deploy:
image: python:latest
stage: deploy
when: always
before_script:
- pip install awscli
script:
- aws s3 sync . s3://${BUCKET_NAME} --delete --exclude "*" --include "*.html" --include "*.css" --include "*.js" --include "*.jpg" --include "*.png"
- aws cloudfront create-invalidation --distribution ${CLOUDFRONT_DISTRIBUTION_ID} --paths "/*"
environment:
name: ${CI_COMMIT_REF_SLUG}
url: https://${BUCKET_NAME}
only:
- master
You can edit the branches where it should deployed or what files should be published. Also you can add some tools like NPM or Yarn for Angular or React Native. If you want to deploy all files of the directory to S3, remember to exclude the .gitlab-ci.yaml file 😄