Automatically Deploy Websites with GitLab to AWS S3 (CI / CD) 12 Feb, 2021

Automatically Deploy Websites with GitLab to AWS S3 (CI / CD)

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:

  • AWS Access Key
  • AWS Secret Access Key
  • S3 bucket name
  • CloudFront Distribution ID This keys can be found as followed:
  • AWS Access Key & AWS Secret Access Key: Click on your account name in the upper right corner -> My Security Credentials -> Create access key
  • S3 bucket name: The bucket name should be the same as your homepages url. Like if your homepage is https://www.example.com your buckets name should be example.com.
  • CloudFront Distribution ID: Go to Services -> Cloudfront -> Copy the ID Attribute (Identified the right distribution by the column Origin or CNAME’s.

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:

Gitlab CI Variables

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 😄

comments powered by Disqus