AWS Angular and React Apps

From bibbleWiki
Jump to navigation Jump to search

Introduction

This page is about using AWS and Angular and how to provision the apps in AWS

S3

This is a easy approach for simple all in one app. I.E. no database or other communication. Steps to do this are

  • Create a bucket
  • Enable Web Static Hosting
  • Grant Permissions
  • Upload Bucket

Create Bucket

Nothing special except the naming of the bucket as it determines the URL of the app. So a bucket named bill-angular-prod-app will have a URL of http://bill-angular-prod-app.s3-website-ap-southeast-2.amazonaws.com where ap-southeast-2 is the region.

Enable Web Static Hosting

You will need to enable Static website hosting under properties for this to work and set the index and error document.

Grant Permissions

To allow public access you will need to disable Block public access which is on by default. Additionally you will need to add a Bucket policy. I did not have permission for mine but was able to on another account. <syntaxhightlight lang="json"> {

   "Version": "2012-10-17",
   "Statement": [
       {
           "Sid": "AddPermission",
           "Effect": "Allow",
           "Principal": "*",
           "Action": "s3:GetObject",
           "Resource": "arn:aws:s3:::bill-angular-prod-app/*"
       }
   ]

} </syntaxhightlight>

Upload Bucket

No issues here just point you upload folder. Here is a picture to help.

EKS Elastic Kubernetes Service

This is probably the better approach. AWS offer it's own Kubernetes which provides service on top of the standard offering. For this example I have used a sample project from GitHub to show the steps. This is end-to-end so includes parts not necessarily AWS.

  • Prerequisites
    • Create key pair
    • Install AWS CLI
    • Install eksctl
    • Install kubectl
    • Install aws-iam-authenticator
  • AWS CLI and MFA
  • Create Test Project
    • Clone Project
    • Build Project
  • Dockerize Project
    • Define Dockfile
    • Build Docker Project
  • Store Docker Image
    • Login to ecr (Elastic Container Registry)
    • Create Repository
    • Tag and Push Image
  • Create Cluster
    • Create Cluster Role
    • Create Cluster
    • Add VPC CNI
    • Update Cluster config
  • Create Node Group
    • Create Managed Node IAM Role
    • Create Managed Node Group

Prerequisites

Create Key Pair

We need this when creating node groups.

 
aws ec2 create-key-pair \
    --key-name bills-key-pair \
    --key-type rsa \
    --key-format pem \
    --query "KeyMaterial" \
    --output text > bills-key-pair.pem

Install AWS CLI

Ezzy pezzy lemon Squezzy

 
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

Install eksctl

Ezzy pezzy lemon Squezzy 2

 
curl --silent --location "https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz" | tar xz -C /tmp
sudo mv /tmp/eksctl /usr/local/bin

Install kubectl

Ezzy pezzy lemon Squezzy 3

 
sudo apt-get install -y apt-transport-https ca-certificates curl
sudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg
echo "deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kubernetes.list
sudo apt-get update
sudo apt-get install -y kubectl

Install aws-iam-authenticator

For me ~/bin is already in the path

 
curl -o aws-iam-authenticator https://s3.us-west-2.amazonaws.com/amazon-eks/1.21.2/2021-07-05/bin/linux/amd64/aws-iam-authenticator
chmod +x ./aws-iam-authenticator
mkdir -p $HOME/bin && cp ./aws-iam-authenticator $HOME/bin/aws-iam-authenticator && export PATH=$PATH:$HOME/bin
echo 'export PATH=$PATH:$HOME/bin' >> ~/.bashrc

AWS CLI and MFA

This was possibly the thing that took the most time. Not clearly specified with the error message so here is how you do it.

  • Get MFA Device Number (MFA_NUM)
  • Get Code from Device (CODE_FROM_MFA)
  • Get Values for environment variables
  • Set config and credential files

Get MFA Device Number (MFA_NUM)

We need to get this number to use in subsequent steps. MFA_NUM is the number of the MFA device on your AWS profile.

Get Code from Device (CODE_FROM_MFA)

The is the code you use when you sign into the console. CODE_FROM_MFA is taken from the authenticator app

Get Values for environment variables

We need to have the three environment variables. aws_access_key_id, aws_secret_access_key, aws_session_token. These are used in .aws/config and .aws/credentials. To get the values use the following command.

 aws sts get-session-token --serial-number MFA_NUM --token-code CODE_FROM_MFA

This returns

 
{
    "Credentials": {
        "AccessKeyId": blahblah_ID,
        "SecretAccessKey": blahblah_KEY,
        "SessionToken": blahblah_TOKEN,
        "Expiration": "2019-07-12T01:14:07Z"
    }
}

Set config and credential files

For using the AWs cli we have .aws/config and .aws/credentials.

.aws/credentials:

 
[mfa]
aws_access_key_id = ID_FROM_ABOVE
aws_secret_access_key = KEY_FROM_ABOVE
aws_session_token = TOKEN_FROM_ABOVE

.aws/config:

 
[mfa]
output = json
region = us-east-1

[profile secondaccount]
role_arn = arn:aws:iam::<SECOND_ACCOUNT_ID>:role/admin
source_profile = mfa

Finally

 export AWS_PROFILE=secondaccount

Now when running

 aws sts get-caller-identity

Should return the assumed role.

Create Test Project

Clone Project

Clone the project

 
git clone https://github.com/bbachi/angular-nginx-example.git

Build Project

install Angular dependencies and start

 
cd my-app
npm install
npm start

Dockerize Project

Define Dockfile

In the root of the clone, not my-app but the one before add a Dockerfile.

 

FROM node:10 AS ui-build
WORKDIR /usr/src/app
COPY my-app/ ./my-app/
RUN cd my-app && npm install @angular/cli && npm install && npm run build


FROM nginx:alpine

#!/bin/sh

COPY ./.nginx/nginx.conf /etc/nginx/nginx.conf

## Remove default nginx index page
RUN rm -rf /usr/share/nginx/html/*

# Copy from the stahg 1
COPY --from=ui-build /usr/src/app/my-app/dist/angular-nodejs-example/ /usr/share/nginx/html

EXPOSE 4200 80

ENTRYPOINT ["nginx", "-g", "daemon off;"]

Build Docker Project

You only need the first command, other commands for information only.

 
# build the image
docker build -t ang-nginx-ui .
# run the image
docker run -d --name ang-nginx-webapp -p 80:80 ang-nginx-ui
#list the image you just built
docker images
# list the container
docker ps

Store Docker Image

Login to ecr (Elastic Container Registry)

We are going to create a repository to store our container. This is the equivalent of dockerhub but an AWS version. Before doing this we need to authenticate. This can be done with the following.

 aws ecr get-login-password --region ap-southeast-2 | docker login --username AWS --password-stdin aws_account_id.dkr.ecr.ap-southeast-2.amazonaws.com

The ap-southeast-2 is the region and the aws_account_id is the id from the console.

Create Repository

And to create the repository we can now do:

 aws ecr create-repository \     
      --repository-name bill/angular-app \     
      --image-scanning-configuration scanOnPush=true \
      --image-tag-mutability IMMUTABLE \    
      --region ap-southeast-2

Tag and Push Image

First we tag the image with

 docker tag ang-nginx-ui:latest aws_account_id.dkr.ecr.ap-southeast-2.amazonaws.com/bill/angular-app:v1

Now we can push the image as we would with dockerhub

 docker push aws_account_id.dkr.ecr.ap-southeast-2.amazonaws.com/bill/angular-app:v1

Create Cluster

Create Cluster Role

Next create the role to manage the cluster we do this with the following file and two commands (copied from docs [1])

 
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "eks.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
 aws iam create-role --role-name eksBillsClusterRole  --assume-role-policy-document file://"cluster-trust-policy.json"
 aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AmazonEKSClusterPolicy --role-name eksBillsClusterRole

Create Cluster

To create the cluster I need to create a VPC. To do this I followed the documentation at [2]

For the cluster I again looked at the documentation [3] which showed the following command.

 aws eks create-cluster \
    --region ap-southeast-2 \
    --name bills-cluster \
    --kubernetes-version 1.22 \
    --role-arn arn:aws:iam::xxxxxxxxxxxxx:role/eksBillsClusterRole \
    --resources-vpc-config subnetIds=subnet-xxxxxxxx,subnet-xxxxxxxxx,securityGroupIds=sg-xxxxxxx

Add VPC CNI

This is required otherwise

aws eks create-addon \
    --cluster-name bills-cluster \
    --addon-name vpc-cni \
    --addon-version v1.11.0-eksbuild.1 \
    --service-account-role-arn arn:aws:iam::xxxxxxxxx:role/eksBillsClusterRole \
    --resolve-conflicts OVERWRITE

Update Cluster config

This command creates a .kube/config for the cluster

aws eks update-kubeconfig --name bills-cluster

Create Node

Create Managed Node IAM Role

We need to create a role for our nodes we do this with the following file and commands

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
 aws iam create-role \
   --role-name AmazonEKSNodeRole \
   --assume-role-policy-document file://"node-role-trust-relationship.json"
 aws iam attach-role-policy \
   --policy-arn arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy \
   --role-name AmazonEKSNodeRole
  aws iam attach-role-policy \
    --policy-arn arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly \
    --role-name AmazonEKSNodeRole
  aws iam attach-role-policy \
     --policy-arn arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy \
     --role-name AmazonEKSNodeRole

Create Managed Node Group

Now we can create the managed node group. Make sure you have created a key pair and cluster first.

 eksctl create nodegroup \
   --cluster bills-cluster \
   --region ap-southeast-2 \
   --name bills-mng \
   --node-type m5.large \
   --nodes 3 \
   --nodes-min 2 \
   --nodes-max 4 \
   --ssh-access \
   --ssh-public-key bills-key

Deleting EKS

To delete the deployment

kubectl delete deployment nginx-webapp
kubectl delete svc nginx-webapp


To delete the node group

 eksctl delete nodegroup \
   --cluster bills-cluster \
   --region ap-southeast-2 \
   --name bills-mng