Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
kshitij-002 committed Dec 12, 2023
0 parents commit d25ff3e
Show file tree
Hide file tree
Showing 23 changed files with 1,166 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .github/scripts/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/bin/bash
set -xe

# Maven is used to build and create a war file.
mvn -Dmaven.test.skip=true clean install


63 changes: 63 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
name: Build and Deploy

on:
workflow_dispatch: {}

env:
applicationfolder: spring-boot-hello-world-example
AWS_REGION: ##region##
S3BUCKET: ##s3-bucket##


jobs:
build:
name: Build and Package
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v2
name: Checkout Repository

- uses: aws-actions/configure-aws-credentials@v1
with:
role-to-assume: ${{ secrets.IAMROLE_GITHUB }}
role-session-name: GitHub-Action-Role
aws-region: ${{ env.AWS_REGION }}

- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8

- name: chmod
run: chmod -R +x ./.github

- name: Build and Package Maven
id: package
working-directory: ${{ env.applicationfolder }}
run: $GITHUB_WORKSPACE/.github/scripts/build.sh

- name: Upload Artifact to s3
working-directory: ${{ env.applicationfolder }}/target
run: aws s3 cp *.war s3://${{ env.S3BUCKET }}/

deploy:
needs: build
runs-on: ubuntu-latest
environment: Dev
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v2
- uses: aws-actions/configure-aws-credentials@v1
with:
role-to-assume: ${{ secrets.IAMROLE_GITHUB }}
role-session-name: GitHub-Action-Role
aws-region: ${{ env.AWS_REGION }}
- run: |
echo "Deploying branch ${{ env.GITHUB_REF }} to ${{ github.event.inputs.environment }}"
commit_hash=`git rev-parse HEAD`
aws deploy create-deployment --application-name CodeDeployAppNameWithASG --deployment-group-name CodeDeployGroupName --github-location repository=$GITHUB_REPOSITORY,commitId=$commit_hash --ignore-application-stop-failures
4 changes: 4 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
## Code of Conduct
This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
[email protected] with any additional questions or comments.
59 changes: 59 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Contributing Guidelines

Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional
documentation, we greatly value feedback and contributions from our community.

Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
information to effectively respond to your bug report or contribution.


## Reporting Bugs/Feature Requests

We welcome you to use the GitHub issue tracker to report bugs or suggest features.

When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already
reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:

* A reproducible test case or series of steps
* The version of our code being used
* Any modifications you've made relevant to the bug
* Anything unusual about your environment or deployment


## Contributing via Pull Requests
Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:

1. You are working against the latest source on the *main* branch.
2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already.
3. You open an issue to discuss any significant work - we would hate for your time to be wasted.

To send us a pull request, please:

1. Fork the repository.
2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change.
3. Ensure local tests pass.
4. Commit to your fork using clear commit messages.
5. Send us a pull request, answering any default questions in the pull request interface.
6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation.

GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
[creating a pull request](https://help.github.com/articles/creating-a-pull-request/).


## Finding contributions to work on
Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start.


## Code of Conduct
This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
[email protected] with any additional questions or comments.


## Security issue notifications
If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.


## Licensing

See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution.
15 changes: 15 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

111 changes: 111 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
## Integrating with GitHub Actions – CICD pipeline to Deploy a Web App to Amazon EC2

Many Organizations adopt [DevOps Practices](https://aws.amazon.com/devops/what-is-devops/) to innovate faster by automating and streamlining the software development and infrastructure management processes. Beyond cultural adoption, DevOps also suggests following certain best practices and Continuous Integration and Continuous Delivery (CI/CD) is among the important ones to start with. CI/CD practice reduces the time it takes to release new software updates by automating deployment activities. Many tools are available to implement this practice. Although AWS has a set of native tools to help achieve your CI/CD goals, it also offers flexibility and extensibility for integrating with numerous third party tools.

In this post, you will use [GitHub Actions](https://help.github.com/en/actions) to create a CI/CD workflow and [AWS CodeDeploy](https://aws.amazon.com/codedeploy/) to deploy a sample Java SpringBoot application to Amazon Elastic Compute Cloud ([Amazon EC2](https://docs.aws.amazon.com/ec2/index.html?nc2=h_ql_doc_ec2#amazon-ec2)) instances in an Autoscaling group.


GitHub Actions is a feature on GitHub’s popular development platform that helps you automate your software development workflows in the same place that you store code and collaborate on pull requests and issues. You can write individual tasks called actions, and then combine them to create a custom workflow. Workflows are custom automated processes that you can set up in your repository to build, test, package, release, or deploy any code project on GitHub.

AWS CodeDeploy is a deployment service that automates application deployments to Amazon EC2 instances, on-premises instances, serverless AWS Lambda functions, or Amazon Elastic Container Service (Amazon ECS) services.


## Solution Overview

The solution utilizes following services:

1. [GitHub Actions](https://docs.github.com/en/actions) : Workflow Orchestration tool that will host the Pipeline.
2. [AWS CodeDeploy](https://aws.amazon.com/codedeploy/) : AWS service to manage deployment on Amazon EC2 Autoscaling Group.
3. [AWS Auto Scaling](https://aws.amazon.com/ec2/autoscaling/) : AWS Service to help maintain application availability and elasticity by automatically adding or removing EC2 instances.
4. [Amazon EC2](https://docs.aws.amazon.com/ec2/index.html?nc2=h_ql_doc_ec2#amazon-ec2) : Destination Compute server for the application deployment.
5. [AWS CloudFormation](https://aws.amazon.com/cloudformation/) : AWS infrastructure as code (IaC) service used to spin up the initial infrastructure on AWS side.
6. [IAM OIDC identity provider](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html) : Federated authentication service to establish trust between GitHub and AWS to allow GitHub Actions to deploy on AWS without maintaining AWS Secrets and credentials.
7. [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) : Amazon S3 to store the deployment artifacts.

The following diagram illustrates the architecture for the solution:
![Alt Text](aws-coodedeplooy-github-action-deploymentV3.png?raw=true "Title")

## Prerequisites
Before you begin, you need to complete the following prerequisites:

* An AWS account with permissions to create the necessary resources.
* A [Git Client](https://git-scm.com/downloads) to clone the provided source code.
* A [GitHub account](https://github.com/) with permissions to configure GitHub repositories, create workflows, and configure GitHub secrets.

## Walkthrough
The following steps provide a high-level overview of the walkthrough:

1. Clone the project from the AWS code samples repository.
2. Deploy the AWS CloudFormation template to create the required services.
3. Update the source code.
4. Setup GitHub secrets.
5. Integrate CodeDeploy with GitHub
6. Trigger the GitHub Action to build and deploy the code.
7. Verify the deployment.

## Download the source code

Clone this repository aws-codedeploy-github-actions-deployment

git clone https://github.com/aws-samples/aws-codedeploy-github-actions-deployment.git

Create an empty repository in your personal GitHub account.

git clone https://github.com/<username>/<repoName>.git

Copy the code. We need contents from the hidden .github folder for the GitHub actions to work.

cp -r aws-codedeploy-github-actions-deployment/. <new repository>

e.g. GitActionsDeploytoAWS

## Deploying the CloudFormation template
To deploy the CloudFormation template, complete the following steps:

1. Open AWS CloudFormation console. Enter your account ID, user name and Password.
2. Check your region, this solution uses us-east-1.
3. If this is new AWS CloudFormation account, click Create New Stack. Otherwise, select Create Stack.
4. Select Template is Ready
5. Click Upload a template file
6. Click Choose File. Navigate to template.yml file in your cloned repository at “aws-codedeploy-github-actions-deployment/cloudformation/template.yaml”
7. Select the template.yml file and select next.
8. In Specify Stack Details, add or modify values as needed.
- Stack name = CodeDeployStack.
- VPC and Subnets = (these are pre-populated for you) you can change these values if you prefer to use your own Subnets)
- GitHubThumbprintList = 6938fd4d98bab03faadb97b34396831e3780aea1
- GitHubRepoName – Name of your GitHub personal repository which you created.
9. On the Options page, click Next.
10. Select the acknowledgement box to allow the creation of IAM resources, and then select Create.
It will take CloudFormation about 5 minutes to create all the resources. This stack would create below resources.
- Two EC2 Linux instances with Tomcat server and CodeDeploy agent installed
- Autoscaling group with Internet Application load balancer
- CodeDeploy application name and deployment group
- S3 bucket to store build artifacts
- Identity and Access Management (IAM) OIDC identity provider
- Instance profile for Amazon EC2
- Service role for CodeDeploy
- Security groups for ALB and Amazon EC2

## GitHub configuration and Testing

Please follow the [blog post](https://aws.amazon.com/blogs/devops/integrating-with-github-actions-ci-cd-pipeline-to-deploy-a-web-app-to-amazon-ec2/) to setup GitHub actions and test the CICD flow.

## Clean up

To avoid incurring future changes, you should clean up the resources that you created.

1. Empty the Amazon S3 bucket:
2. Delete the CloudFormation stack (CodeDeployStack) from the AWS console.
3. Delete the GitHub Secret (‘IAMROLE_GITHUB’)
1. Go to the repository settings on GitHub Page.
2. Select Secrets under Actions.
3. Select IAMROLE_GITHUB, and delete it.


## Security

See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.

## License

This library is licensed under the MIT-0 License. See the LICENSE file.
26 changes: 26 additions & 0 deletions appspec.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
version: 0.0
os: linux
files:
- source: /aws
destination: /usr/local/codedeployresources
hooks:
ApplicationStop:
- location: aws/scripts/application-stop.sh
timeout: 300
runas: root
BeforeInstall:
- location: aws/scripts/before-install.sh
timeout: 300
runas: root
AfterInstall:
- location: aws/scripts/after-install.sh
timeout: 300
runas: root
ApplicationStart:
- location: aws/scripts/application-start.sh
timeout: 300
runas: root
ValidateService:
- location: aws/scripts/validate-service.sh
timeout: 300
runas: root
Binary file added aws-coodedeplooy-github-action-deploymentV3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions aws/scripts/after-install.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/bin/bash
set -xe


# Copy war file from S3 bucket to tomcat webapp folder
aws s3 cp s3://##s3-bucket##/SpringBootHelloWorldExampleApplication.war /usr/local/tomcat9/webapps/SpringBootHelloWorldExampleApplication.war


# Ensure the ownership permissions are correct.
chown -R tomcat:tomcat /usr/local/tomcat9/webapps
5 changes: 5 additions & 0 deletions aws/scripts/application-start.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/bin/bash
set -xe

# Start Tomcat, the application server.
service tomcat start
8 changes: 8 additions & 0 deletions aws/scripts/application-stop.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/bin/bash
set -x

# System control will return either "active" or "inactive".
tomcat_running=$(systemctl is-active tomcat)
if [ "$tomcat_running" == "active" ]; then
service tomcat stop
fi
9 changes: 9 additions & 0 deletions aws/scripts/before-install.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash
set -xe

# Delete the old directory as needed.
if [ -d /usr/local/codedeployresources ]; then
rm -rf /usr/local/codedeployresources/
fi

mkdir -vp /usr/local/codedeployresources
20 changes: 20 additions & 0 deletions aws/scripts/validate-service.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/bin/bash
set -x

NUMBER_OF_ATTEMPTS=10
SLEEP_TIME=3

# Ensure Tomcat is running by making an HTTPS GET request to the default page.
# Don't try and verify the certificate; use the --insecure flag.
for i in `seq 1 $NUMBER_OF_ATTEMPTS`;
do
HTTP_CODE=`curl --insecure --write-out '%{http_code}' -o /dev/null -m 10 -q -s http://localhost:8080`
if [ "$HTTP_CODE" == "200" ]; then
echo "app server is running."
exit 0
fi
echo "Attempt to curl endpoint returned HTTP Code $HTTP_CODE. Backing off and retrying."
sleep $SLEEP_TIME
done
echo "Server did not come up after expected time. Failing."
exit 1
Loading

0 comments on commit d25ff3e

Please sign in to comment.