Deploy an angular application on EC2 public instance using AWS CodePipeline.(codecommit, codebuild and codedeploy).

DevFunOps With Pradeep
13 min readMar 15, 2024

--

In this exciting article, we’re embarking on a journey to deploy an Angular application from AWS CodeCommit to an EC2 public instance, complete with an Apache (httpd) web server. Let’s dive in and unleash the power of deployment!

This process will be fully automated using AWS CodePipeline, leveraging CodeCommit, CodeBuild, and CodeDeploy services. We’ll ensure seamless deployment by installing the CodeDeploy Agent for Amazon Linux or RHEL. Let’s streamline the deployment process together!

Absolutely! 🤩🤩 Following the CI/CD (Continuous Integration/Continuous Deployment) process is essential for deploying Angular code onto a server efficiently. CI/CD practices have become the cornerstone of modern software development, drastically reducing cycle time and enhancing delivery speed.

“The file/folder structure of the Angular app can be found in the provided GitLab repository Link.👈👈👈”

Feel free to create your own repository, but ensure that you include all the required files and folders listed below.

Attention! 👹👹 Here’s the rundown of required files and folders you’ll need to include.

  1. buildspec.yml
version: 0.2
env:
variables:
APP_NAME: "myapp"
phases:
install:
runtime-versions:
nodejs: 20
commands:
- echo install process started
- npm install && npm install -g @angular/cli
build:
commands:
- echo build process started now
- npm install
- ng build --configuration=production
post_build:
commands:
- echo build process finished, we should uplload to S3 now
- cp -r scripts dist/$APP_NAME
- cp appspec.yml dist/$APP_NAME
- cd dist/$APP_NAME
- ls -la
# - aws s3 sync . s3://prdpfirstbucket --delete
artifacts:
files:
- dist/**/*
discard-paths: yes

2. appspec.yml

version: 0.0
os: linux
files:
- source: /
destination: /var/www/html/
hooks:
BeforeInstall:
- location: install_dependencies.sh
timeout: 300
runas: root
ApplicationStart:
- location: start_server.sh
timeout: 300
runas: root
ApplicationStop:
- location: stop_server.sh
timeout: 300
runas: root

3. Below are the scripts that you need to include within the “scripts” folder.

install_dependencies.sh

#!/bin/bash
sudo yum install httpd -y

remove_root_dir.sh

#!/bin/bash
sudo rm -rf /var/www/html/

start_server.sh

#!/bin/bash
sudo service httpd start

stop_server.sh

#!/bin/bash
isExistApp = `pgrep httpd`
if [[ -n $isExistApp ]]; then
sudo service httpd stop
fi

To run and test the Angular application locally, execute the following command in your terminal:

ng serve

Get ready for an exhilarating experience! If all goes according to plan, your project will spring to life right before your eyes in your browser, accessible via the following URL.🚀🚀🚀

http://localhost:4200/

Then, you’ll be greeted by the following page…

Create a Repository In CodeCommit And Explore Its Features.

Get ready for the next step in our adventure! We’re about to create a repository on AWS CodeCommit and push the source code to unleash its potential.🚀🚀

Prepare for the next exciting step! Click on “Create Repository” to kickstart the repository creation process. You’ll then have the opportunity to add a Repository Name and Description. Once filled out, hit “Create” to forge ahead.😍😍

Stay tuned for the confirmation! A success message will pop up at the top of the page, signaling the successful creation of your repository.

Once you've completed the repository creation process, there are two ways to connect or clone your repository.

1. SSH
2. HTTPS

👉 👉👉 Discover more insights in our dedicated blog post. 👈👈👈

  1. When you create a repository on AWS CodeCommit, it’s always empty initially.

Copy the SSH URL from the “Clone SSH” dropdown menu.

“Let’s take the next step and clone our empty repository from AWS CodeCommit using the trusty ‘git clone’ command in your terminal.”

“Grab the SSH repository URL from the AWS console by clicking on the ‘Clone SSH’ option, 👆 then paste it into your terminal and execute the following command.”

git clone codecommit-ssh-repo-url

You can verify the successful cloning by using the “ls” command in your terminal to list the files and directories, and then navigate into the cloned repository using the “cd” command. Alternatively, you can also check it from your file explorer. Happy exploring! 🌟🚀

Let’s navigate into the “angular-project”(your angular project repository which you want to deploy) directory using your terminal. You can do this by using the “cd” command followed by the path to the directory. For example:

If your local project folder is not a Git repository, you’ll need to initialize it as a Git repository first. You can do this with the following commands:

Make sure to use your AWS CodeCommit SSH repository URL from the AWS console by clicking on the “Clone SSH” option. This URL will be used to configure your local repository to push changes to AWS CodeCommit.

git init
git remote add origin ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/Your-AWS-CodeCommit-SSH-repo-URL
git checkout -b develop
git add .
git commit -m "Initial Commit"
git push

If your local folder is already a Git repository, you can proceed with the following commands to set up your repository to push changes to AWS CodeCommit:

git init
git remote set-url origin ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/Your-AWS-CodeCommit-SSH-repo-URL
git checkout -b develop
git add .
git commit -m "Initial Commit"
git push

Once you’ve executed the commands to push your changes to AWS CodeCommit, you’ll be able to see your project files and folders reflected in the AWS CodeCommit repository on the AWS console. This confirms that your changes have been successfully pushed to AWS CodeCommit.

Exciting times ahead! Now that AWS CodeCommit is up and running, it’s time to explore the realms of AWS S3, CodeBuild, CodeDeploy, and CodePipeline. Get ready for an adventure in cloud development!😍😍

Create a bucket:

Just provide the Bucket name, and we’ll stick to all other default settings. (Once you’ve completed setting up the end-to-end pipeline, you can delve into the settings and discover more advanced features.)

Please follow the steps outlined in the screenshot to create the AWS bucket.

Exciting progress! We’re moving steadily closer to achieving our end-to-end pipeline goal.😍😍

Get ready for the next phase! We’re about to dive into creating the CodeBuild project.😍

Create a CodeBuild Project:

Simply navigate to the AWS Management Console and search for “CodeBuild” to access the CodeBuild service.

Please follow the steps outlined in the screenshot to create the AWS CodeBuild Project.

You’ll be redirected to the AWS CodeBuild service, where you need to click on the “Create Project” button. That’s all there is to it!

Next, a new page will open where you’ll need to enter a few details. Follow the instructions exactly as shown in the image below.

  1. First enter the Project name

2. In the “Source” section, select “AWS CodeCommit” as our project repository is hosted on AWS CodeCommit. This will list out all the repositories available on CodeCommit.

3. Continue by selecting your project repository from the list, specifying the reference type as “Branch,” and choosing your branch name from the dropdown menu provided below.

4. Now, let’s proceed directly to the “Service role” section, leaving all other settings as default. Here, you have the option to either create a new service role or select an existing one.

You’ll require an AWS CodeBuild service role, allowing CodeBuild to interact with dependent AWS services on your behalf.

5. Keep the “Use a buildspec file” option selected as it is. This option will point to the buildspec file we added at the root level of our project.

6. The next step is to select the bucket where we’ll upload our project artifact.

7. Keep the “Zip” option selected as it is, and then hit the “Create build” button.

Celebrate your achievement! We’ve successfully completed the CodeBuild creation process, marking a significant milestone in our project journey.

Please refer to this document for the manual process of creating the service role: 👉👉 [link]

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Resource": [
"arn:aws:logs:us-east-1:your-account-id:log-group:/aws/codebuild/your-codebuild-project-name",
"arn:aws:logs:us-east-1:your-account-id:log-group:/aws/codebuild/your-codebuild-project-name:*"
],
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
]
},
{
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::codepipeline-us-east-1-*"
],
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:GetObjectVersion",
"s3:GetBucketAcl",
"s3:GetBucketLocation"
]
},
{
"Effect": "Allow",
"Resource": [
"arn:aws:codecommit:us-east-1:your-account-id:your-codecommit-project-name"
],
"Action": [
"codecommit:GitPull"
]
},
{
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::prdpfirstbucket",
"arn:aws:s3:::prdpfirstbucket/*"
],
"Action": [
"s3:PutObject",
"s3:GetBucketAcl",
"s3:GetBucketLocation"
]
},
{
"Effect": "Allow",
"Action": [
"codebuild:CreateReportGroup",
"codebuild:CreateReport",
"codebuild:UpdateReport",
"codebuild:BatchPutTestCases",
"codebuild:BatchPutCodeCoverages"
],
"Resource": [
"arn:aws:codebuild:us-east-1:your-account-id:report-group/your-codebuild-project-name-*"
]
}
]
}

Here is the build spec file code.

Note: Here, we’re copying the “scripts” folder and “appspec” file to the “dist” directory, and then uploading the artifact (in our case, it’s the “dist” folder) to S3. The rationale behind this will become clear when we use the CodeDeploy project.

version: 0.2
env:
variables:
APP_NAME: "myapp"
phases:
install:
runtime-versions:
nodejs: 20
commands:
- echo install process started
- npm install && npm install -g @angular/cli
build:
commands:
- echo build process started now
- npm install
- ng build --configuration=production
post_build:
commands:
- echo build process finished, we should uplload to S3 now
- cp -r scripts dist/$APP_NAME
- cp appspec.yml dist/$APP_NAME
- cd dist/$APP_NAME
- ls -la
# - aws s3 sync . s3://prdpfirstbucket --delete
artifacts:
files:
- dist/**/*
discard-paths: yes

Create a Amazon EC2 Instance for CodeDeploy Project:

Before creating the codedeploy project we will prepare our ec2 instance so that we will use it to deploy our s3 artifact on it.

Go ahead and refer below screenshot and start creating it as it is, below are the few steps which I would like to point out.

So while creating the ec2 public instance below three steps are very important

  1. Key Pair — We need a key pair securely SSH into your instance

When you create a key pair using Amazon EC2, the public key is stored in Amazon EC2, and you store the private key, For Linux instances, the private key allows you to securely SSH into your instance.

2. Installing the Code Deploy agent on our ec2 instance.

Sign in to the instance, and run the following commands, one at a time or else we can provide these commands while creating the ec2 instance from aws console itself(refer below screenshot)

👉 👉👉 Explore our blog post on EC2 instance sign-in for insights.👈👈👈

👉 👉👉 Discover insights on CodeDeploy Agent in our blog post. 👈👈👈

Note: Make sure you are adding bucket name and region-identifier correctly.see Resource kit bucket names by Region.

Refer below screenshot to enter/add the code deploy installation commands/script

#!/bin/bash
sudo yum update -y
sudo yum install ruby -y
sudo yum install wget -y
cd /home/ec2-user
wget https://aws-codedeploy-us-east-1.s3.us-east-1.amazonaws.com/latest/install
chmod +x ./install
chmod +x ./install
systemctl status codedeploy-agent
systemctl start codedeploy-agent
systemctl start codedeploy-agent

3. Creating the IAM Instance profile and attaching it to our ec2 instance.

This role gives the CodeDeploy agent permission to access the Amazon S3 buckets or GitHub repositories where your applications are stored.

{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:Get*",
"s3:List*"
],
"Effect": "Allow",
"Resource": "*"
}
]
}

Select the “Create security group” option and configure it to allow SSH traffic from and HTTP traffic from the internet.

Please follow the steps outlined in the screenshot to create the Amazon EC2 Instance for CodeDeploy Project

Congratulations 🍾 🙌 🎉, We have just created the ec2 instance for code deploy.

Create a CodeDeploy Project:

Simply navigate to the AWS Management Console and search for “CodeDeploy” to access the CodeDeploy service.

Please follow the steps outlined in the screenshot to create the CodeDeploy Project

After selecting “Create application,” the following screen will appear.

Enter the Application name and select the compute platform as EC2/on-premises.

Create a Deployment Group:

Once we’ve completed the “Create CodeDeploy project” activity, we’ll need to create the deployment group.

Upon selecting the “Create deployment group” button, the following screen will be displayed.

Please follow the steps outlined in the screenshot to create the Create deployment group

Create a Service role : The service role you create for CodeDeploy must be granted the permissions required for your compute platform.

You should see the following policy, which provides the service role permission to access all supported endpoints:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": [
"codedeploy.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}

To grant the service role access to only some supported endpoints, replace the contents of the trust policy text box with the following policy. Remove the lines for the endpoints you want to prevent access to, and then choose Update policy.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": [

"codedeploy.us-east-1.amazonaws.com",
"codedeploy.us-east-2.amazonaws.com",
"codedeploy.us-west-1.amazonaws.com",
"codedeploy.us-west-2.amazonaws.com",
"codedeploy.ca-central-1.amazonaws.com",
"codedeploy.ap-east-1.amazonaws.com",
"codedeploy.ap-northeast-1.amazonaws.com",
"codedeploy.ap-northeast-2.amazonaws.com",
"codedeploy.ap-northeast-3.amazonaws.com",
"codedeploy.ap-southeast-1.amazonaws.com",
"codedeploy.ap-southeast-2.amazonaws.com",
"codedeploy.ap-southeast-3.amazonaws.com",
"codedeploy.ap-southeast-4.amazonaws.com",
"codedeploy.ap-south-1.amazonaws.com",
"codedeploy.ap-south-2.amazonaws.com",
"codedeploy.ca-central-1.amazonaws.com",
"codedeploy.eu-west-1.amazonaws.com",
"codedeploy.eu-west-2.amazonaws.com",
"codedeploy.eu-west-3.amazonaws.com",
"codedeploy.eu-central-1.amazonaws.com",
"codedeploy.eu-central-2.amazonaws.com",
"codedeploy.eu-north-1.amazonaws.com",
"codedeploy.eu-south-1.amazonaws.com",
"codedeploy.eu-south-2.amazonaws.com",
"codedeploy.il-central-1.amazonaws.com",
"codedeploy.me-central-1.amazonaws.com",
"codedeploy.me-south-1.amazonaws.com",
"codedeploy.sa-east-1.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}

View log data for CodeDeploy EC2/On-Premises deployments

👉 👉👉 Discover insights on CodeDeploy Agent in our blog post. 👈👈👈

Create CodePipeline Project

Simply navigate to the AWS Management Console and search for “CodePipeline” to access the CodePipeline service.

Please follow the steps outlined in the screenshot to create the CodePipeline Project

You’ll be redirected to the AWS CodePipeline service, where you’ll need to click on the “Create Pipeline” button.

Enter the pipeline name and keep all other settings as default.

In the source stage, select the source provider as AWS CodeCommit, and specify the Repository Name and Branch Name accordingly.

Enter the Repository Name, Branch Name and keep all other settings as default.

In the build stage, select the build provider as AWS CodeBuild, and specify the Project Name accordingly.

In the deploy stage, select the Deploy Provider as AWS CodeDeploy, and specify the Application Name and Deployment Group that we have created in the CodeDeploy project.

Review the settings once, and if everything looks correct, click on the “Create Pipeline” button.

You’ll be redirected to the next page, and your pipeline will begin its execution.

After the pipeline successfully runs, we’ll navigate to the browser using the EC2 instance’s IP address.

Then, you’ll be able to see the page below…

Cheers! 🥂👏🍾 Congratulations on successfully setting up the AWS CodePipeline! 🎉🚀 It’s time to embark on your development journey and unleash your creativity with the streamlined automation provided by CodePipeline

Conclusion

By following the steps outlined above, we have successfully set up a continuous integration and continuous deployment (CI/CD) pipeline for our application. This pipeline automatically builds, tests, and deploys our code changes whenever there’s a new commit to our repository. With this streamlined workflow, we can confidently deliver updates to our application with ease and efficiency, ensuring a seamless user experience.

If you encounter any issues or need further assistance, feel free to ask for help. Your feedback and questions are always welcome in the comments section below. We’re here to support you on your AWS journey!🚀🚀

As we draw our journey through AWS CodePipeline to a close, remember that the power to innovate lies within your grasp. With this dynamic tool at your disposal, the possibilities are boundless. Whether you’re advancing on a solo project or collaborating with a team, embrace the opportunities that AWS CodePipeline offers to revolutionize your development process. So, forge ahead, unleash your creativity, and let AWS CodePipeline propel you toward your next breakthrough. Until next time, happy coding! 🚀🚀

--

--