Automate Deployment of Angular Apps using AWS CodeBuild

Building and deploying Angular app is very time consuming, especially with large application. You also must keep track of which branch you are deploying to which environment and a little mix-up could be catastrophic. You can smoothen the building and deployment of your application using AWS CodeBuild.

“AWS CodeBuild is a fully managed build service that compiles source code, runs tests, and produces software packages that are ready to deploy.”

What we are going to use

  1. An AWS Account, if you don’t have one you can create on here. They have a 12 Month Free tier which you can learn more about here.
  2. AWS CodeCommit/Github Repository.
  3. AWS CodeBuild, CodePipeline, S3 and CloudFront for Deployment.
  4. Angular Project with GIT Enabled

NOTE: AWS charges for using the above resources, please cleanup after you are done using them.

How does it work?

  1. AWS CodePipeline will detect changes on our repository, then will initiate the process of automatically building and deploying our app to an S3 bucket.
  2. Then it will launch AWS CodeBuild to build and deploy the application on an S3 Bucket of your choice.

Preparations

AWS S3

You will need to create a new bucket and then give AWS CodeBuild permission to access and put the build files inside the S3 Bucket. If you don’t know how to create an S3 bucket, please follow this official guide. For permissions, we will cover this at the end of this post.

Getting Started

First, head over to AWS CodeCommit on AWS using the following link. Your window will probably look like the one below:

"Automate

Click on Getting Started or Create Pipeline to get started. You will be presented with the following window, where there are six steps to follow for you to create your new pipeline. Let’s go through them step by step. If you are already familiar with AWS CodePipeline you can skip this guide up to Step 3.

"Automate

Step 1: Enter Pipeline Name (Self Explanatory).

Please enter an Appropriate Name for your pipeline.

Step 2: Select Source for your Pipeline

This is the location of your Angular Source Code. It could be either AWS CodeCommit Repo, S3 Bucket Files or Github Rep. Select the source in the drop down, in our case we will use either Github or AWS CodeCommit.

If you select Github, then click on the “Connect Github” button and follow the steps to authorize AWS Access. Then select the repository and the branch you would like to automatically detect changes and build.

"Automate

If you select AWS CodeCommit, please select the appropriate repository and branch to automatically build. You can leave the rest of the settings as they are.

"Automate

Please Note: For AWS CodeCommit, the repo you wish to connect to AWS CodePipeline must be in the same region as the one you are creating the pipeline for. You can change the region you are in by clicking on the drop-down button between Your account and Support at the top right corner of your browser. The default region is North Virginia.

Step 3: Build

This is what this whole article is about. Here we are going to setup CodeBuild to automatically build our application and deploy to an S3 Bucket.

"Automate

Under Build Provider, select CodeBuild, then under configure your project, select Create a New Build Project under AWS CodeBuild.

Creating a new Build Project:
  1. Enter an appropriate name of the New Project. No spaces.
  2. Under Environment Image, select ubuntu.
  3. Then under Operating System, Select Ubuntu 14
  4. Then under Runtime, Select Base (Not NodeJS) and then Select the Appropriate Version (As at the time of writing, this was Ubuntu 14) below that.
  5. Under Build Specification, we are going to be using yaml file at the root of our project that will provide all commands to build our Angular Project. I will provide a sample for angular later in the post. You can learn more about Build Spec File here.
  6. You can leave the rest as they are.
  7. Save the Build Project.

Once the Build Project has been created successfully, let’s go ahead and get the Service Role name. We are going to need this to configure AWS CodeBuild permission to put the built project on AWS S3.

"Automate

  1. Click on the View Project Details This will open in a new window.
  2. Click on Edit Project, then scroll down to Service Role and take note of the Service Role Name.
  3. Then, head over to AWS IAM (Identity and Access Management) on the console.
  4. On the left panel, select
  5. Then search and open the role of the CodeBuild Project you took note of above.
  6. Copy the Role ARN, we will need this when configuring access to the bucket.

"Automate

Step 4 Deploy

We already took care of deployment under the last step, so select No Deployment option. This is because CodePipeline doesn’t have the option to deploy to an S3 bucket. We will automatically deploy to an S3 bucket after building the project using aws-cli – it is installed automatically in the build server.

Step 5 Service Role

Create a new Aws Service Role for CodePipeline and click on next.

Step 6 Review

Review the details of the Pipeline and click on create at the bottom.

Configuring Your Project

To build your project, we need to add the commands to install all npm packages (Dependencies).  Then it will run ng build and copy all the files inside /dist directory (or wherever the location of your build artefacts are placed) to the s3 bucket.

To do this add a new file to the root of the project known as buildspec.yaml. Then add the following content: (Read the moment for what each line of command does)

version: 0.2

env:
    variables:
        S3_BUCKET: "<S3_BUCKET_HERE>"
        APP_NAME: "<APP_NAME_HERE>"
        BUILD_ENV : "prod"

phases:
    install:
        commands:
        # Download and Install NodeJS 8.0     
        - curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
        - sudo apt-get install -y nodejs
        - echo Installing source NPM dependencies...
        # Install http drivers for node
        - sudo apt-get update -y
        - sudo apt-get install -y apt-transport-https
        # Install Yarn Package Manager (Replace the commands below if you using NPM).
        - curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
        - echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
        - sudo apt-get update -y
        - sudo apt-get install -y yarn
        # Install Angular CLI, If you are not using Angular 6, install angular/[email protected] or lower, confirm by running ng -v inside your project folder
        - yarn global add @angular/[email protected]
        # Install node dependancies.
        - yarn install

    build:
        commands:
        # Builds Angular application. You can also build using custom environment here like mock or staging
        - echo Build started on `date`
        - ng build --${BUILD_ENV}

    post_build:
        commands:
        # Clear S3 bucket.
        - aws s3 rm s3://${S3_BUCKET} --recursive
        - echo S3 bucket is cleared.
        # Copy dist folder to S3 bucket, As of Angular 6, builds are stored inside an app folder in distribution and not at the root of the dist folder
        - aws s3 cp dist s3://${S3_BUCKET}/${APP_NAME} --recursive
        - echo Build completed on `date`

artifacts:
    files:
        - '**/*'
    discard-paths: yes
    base-directory: 'dist*'

As you can see, am using Yarn Package Manager for my project, but you can replace the Yarn commands with NPM commands. And finally, we need to allow our CodeBuild permission to write and delete in to our S3 Bucket, otherwise this won’t work.

Revisiting AWS S3 Bucket Permission

Head over to AWS S3 Bucket management interface and open your bucket. Then under Permissions, you open Bucket Policy. We need to modify the policy to include the role you copied when you create the CodeBuild Project up there. Under statement, add a new object (JSON Object) and Add the following content:

        {
            "Sid": "CodeBuildPermision",
            "Effect": "Allow",
            "Principal": {
                "AWS": "< ROLE ARN HERE>"
            },
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::your-bucket-name "
        }

Replace your-bucket-name with your own bucket name and ROLE ARN from Step 3 Above.

Finally, you need to be able to access your web app over the internet, to do this configure your S3 Bucket for Web Hosting and add a domain name if need be. This guide here will help you configure your bucket for web hosting.

5 Replies to “Automate Deployment of Angular Apps using AWS CodeBuild”

  1. Thank you for your reply! After reading it i tried using yarn instead of npm, had to change
    – aws s3 cp dist s3://${S3_BUCKET} –recursive
    to
    – aws s3 cp s3://${S3_BUCKET} . –recursive
    and it worked, codeBuild claims the build was successful, but I can’t seem to find the files anywhere :c

    1. Since you are using Angular 6, the built file are inside a project folder inside the dist folder (i.e. dist/project-name), this was changed in order to support multiple projects in a single workspace (check my latest post for more information about angular workspaces). And your cp command is wrong, it needs to start with the source folder (dist/project-name) followed by the destination, in this case the S3Bucket. Also did you give CodeBuild Permission to write to your specific S3 Bucket, that is mainly the source of the problem of this command: – aws s3 cp dist/project-name s3://${S3_BUCKET} –recursive. The detailed logs regarding the exact error caused by that command can be found under cloudwatch.

  2. Hello! I tried to deploy an angular app by following your tutorial, but when running a codeBuild build I get an error on: – ng build –prod, do you perhaps have any idea why it could be? I am using npm instead of yarn but apart from that i did everything the same way your tutorial suggested.

    Another, rather silly question: when i manage to get my codeBuild running, do i have to upload any files manually to my bucket? Or will codeBuild download everything it needs from my repo?

    Thank you in advance!

    1. Please share the whole error message you received. But if i were to make a guess, it could be something to do with yarn package manager not installing successfully. Also what version of angular are you using? I haven’t tested this with Angular 6.0.0 but i will be doing a follow up post next week.

      And for your final question, yes all files under distribution will be moved to your S3 bucket automatically.

Comments are closed.