September 12, 2021

Git Actions for continuous deployments {frontend}

Git Actions for continuous deployments {frontend}
git action + aws sdk

Ever since git actions were introduced, creating workflows, publishing, testing has become really simple for developers. Last year I published a website gettweet.in whose frontend deployment is done by git actions.

Why am I writing this article? To demonstrate how to use git actions to conditionally deploy when both your frontend and backend code of your dynamic website is present in the same repository.


Frontend Deployment Design

So the website is served almost entirely by AWS CloudFront, behind which the codebase sits in a folder present in a bucket in AWS S3. Contents of the bucket/folder are populated by the gitAction.


Workflow File

Location of the file <repository>/.github/workflows/frontend_deploy.yml

  1. Workflow is triggered right after there is a code pushed in the master branch.
  2. Here I have used Checkout V2 gitAction which checks out your code so that your workflow can access your git commits.
  3. Fetch depth 2 means to pull the last two commits. One will be HEAD itself, another one will be a commit just before that, which can also be denoted as HEAD^.
  4. git diff-tree --name-only -r HEAD^ HEAD will print all the files modified between last two commits. Output of this comes in a single line so can be converted into multiple lines by using translate command in linux tr " " "\n".
  5. All of my frontend code is present in src/ and public/ directories, which I check by using grep -Ec "^src\/|^public\/". Flag -E is for extended grep and -c is to print the count of matched lines.
  6. ||true ? This is used just so to prevent gitAction from failing as grep returns a non zero exit code if none of the lines were matched. gitAction stops execution if any step results in a non-zero exit code.
  7. Finally after an if check, code can be built using the npm commands, post which it will be uploaded to the S3 bucket using the command aws s3 sync ./build s3://$FRONTEND_BUCKET_NAME . Creating invalidation was optional, I did it to get the site updated as quick as possible with the latest update.