diff --git a/.github/scripts/build.sh b/.github/scripts/build.sh new file mode 100644 index 0000000..823a346 --- /dev/null +++ b/.github/scripts/build.sh @@ -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 + + diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..c32f050 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -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 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..5b627cf --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -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 +opensource-codeofconduct@amazon.com with any additional questions or comments. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c4b6a1c --- /dev/null +++ b/CONTRIBUTING.md @@ -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 +opensource-codeofconduct@amazon.com 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. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..1bb4f21 --- /dev/null +++ b/LICENSE @@ -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. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..4065133 --- /dev/null +++ b/README.md @@ -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//.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/. + + 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. diff --git a/appspec.yml b/appspec.yml new file mode 100644 index 0000000..267eac7 --- /dev/null +++ b/appspec.yml @@ -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 diff --git a/aws-coodedeplooy-github-action-deploymentV3.png b/aws-coodedeplooy-github-action-deploymentV3.png new file mode 100644 index 0000000..00febc5 Binary files /dev/null and b/aws-coodedeplooy-github-action-deploymentV3.png differ diff --git a/aws/scripts/after-install.sh b/aws/scripts/after-install.sh new file mode 100644 index 0000000..aefc504 --- /dev/null +++ b/aws/scripts/after-install.sh @@ -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 \ No newline at end of file diff --git a/aws/scripts/application-start.sh b/aws/scripts/application-start.sh new file mode 100644 index 0000000..7aff2f9 --- /dev/null +++ b/aws/scripts/application-start.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -xe + +# Start Tomcat, the application server. +service tomcat start \ No newline at end of file diff --git a/aws/scripts/application-stop.sh b/aws/scripts/application-stop.sh new file mode 100644 index 0000000..9589c68 --- /dev/null +++ b/aws/scripts/application-stop.sh @@ -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 \ No newline at end of file diff --git a/aws/scripts/before-install.sh b/aws/scripts/before-install.sh new file mode 100644 index 0000000..3042368 --- /dev/null +++ b/aws/scripts/before-install.sh @@ -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 diff --git a/aws/scripts/validate-service.sh b/aws/scripts/validate-service.sh new file mode 100644 index 0000000..24de7f6 --- /dev/null +++ b/aws/scripts/validate-service.sh @@ -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 \ No newline at end of file diff --git a/cloudformation/template.yaml b/cloudformation/template.yaml new file mode 100644 index 0000000..2d6de0e --- /dev/null +++ b/cloudformation/template.yaml @@ -0,0 +1,535 @@ +--- +AWSTemplateFormatVersion: 2010-09-09 +Description: 'Cloudformation for provisioning services required to setup the CI/CD using GitHub actions and CodeDeploy. +**WARNING** This template creates EC2,VPC and related resources. You will be billed for the AWS resources used if you create a stack from this template' +Metadata: + AWS::CloudFormation::Interface: + ParameterGroups: + - Label: + default: "VPC Configurations" + Parameters: + - VpcCIDR + - PublicSubnet1CIDR + - PublicSubnet2CIDR + - PrivateSubnet1CIDR + - PrivateSubnet2CIDR + - Label: + default: "Autoscaling configurations" + Parameters: + - ImageId + - InstanceType + - AutoScalingGroupMinSize + - AutoScalingGroupMaxSize + - AutoScalingGroupDesiredCapacity + - Label: + default: "Github configurations" + Parameters: + - GithubRepoName + - ThumbprintList +Parameters: + VpcCIDR: + Description: Please enter the IP range (CIDR notation) for this VPC + Type: String + Default: 10.192.0.0/16 + + PublicSubnet1CIDR: + Description: Please enter the IP range (CIDR notation) for the public subnet in the first Availability Zone + Type: String + Default: 10.192.10.0/24 + + PublicSubnet2CIDR: + Description: Please enter the IP range (CIDR notation) for the public subnet in the second Availability Zone + Type: String + Default: 10.192.11.0/24 + + PrivateSubnet1CIDR: + Description: Please enter the IP range (CIDR notation) for the private subnet in the first Availability Zone + Type: String + Default: 10.192.20.0/24 + + PrivateSubnet2CIDR: + Description: Please enter the IP range (CIDR notation) for the private subnet in the second Availability Zone + Type: String + Default: 10.192.21.0/24 + + ImageId: + Type: 'AWS::SSM::Parameter::Value' + Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2' + Description: The Amazon EC2 Linux instance Amazon Machine Image (AMI), which designates the configuration of the new instance. + InstanceType: + Type: String + Default: t2.medium + Description: The type of Amazon EC2 Linux instances that will be launched for this project. + AutoScalingGroupMinSize: + Type: Number + Default: 2 + Description: Enter the Min Size for the ASG + AutoScalingGroupMaxSize: + Type: Number + Default: 2 + Description: Enter the Max Size for the ASG + AutoScalingGroupDesiredCapacity: + Type: Number + Default: 2 + Description: Enter the Max Size for the ASG + ThumbprintList: + Type: String + Default: 6938fd4d98bab03faadb97b34396831e3780aea1 + Description: A thumbprint of an Open ID Connector is a SHA1 hash of the public certificate of the host + GithubRepoName: + Type: String + Description: GitHub repository name Ex-TestUser/TestCodeDeploy + +Resources: + VPC: + Type: AWS::EC2::VPC + Properties: + CidrBlock: !Ref VpcCIDR + EnableDnsSupport: true + EnableDnsHostnames: true + + InternetGateway: + Type: AWS::EC2::InternetGateway + + InternetGatewayAttachment: + Type: AWS::EC2::VPCGatewayAttachment + Properties: + InternetGatewayId: !Ref InternetGateway + VpcId: !Ref VPC + + PublicSubnet1: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref VPC + AvailabilityZone: !Select [ 0, !GetAZs '' ] + CidrBlock: !Ref PublicSubnet1CIDR + MapPublicIpOnLaunch: true + Tags: + - Key: Name + Value: Public Subnet (AZ1) + + PublicSubnet2: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref VPC + AvailabilityZone: !Select [ 1, !GetAZs '' ] + CidrBlock: !Ref PublicSubnet2CIDR + MapPublicIpOnLaunch: true + Tags: + - Key: Name + Value: Public Subnet (AZ2) + + PrivateSubnet1: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref VPC + AvailabilityZone: !Select [ 0, !GetAZs '' ] + CidrBlock: !Ref PrivateSubnet1CIDR + MapPublicIpOnLaunch: false + Tags: + - Key: Name + Value: Private Subnet (AZ1) + + PrivateSubnet2: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref VPC + AvailabilityZone: !Select [ 1, !GetAZs '' ] + CidrBlock: !Ref PrivateSubnet2CIDR + MapPublicIpOnLaunch: false + Tags: + - Key: Name + Value: Private Subnet (AZ2) + + NatGateway1EIP: + Type: AWS::EC2::EIP + DependsOn: InternetGatewayAttachment + Properties: + Domain: vpc + + NatGateway1: + Type: AWS::EC2::NatGateway + Properties: + AllocationId: !GetAtt NatGateway1EIP.AllocationId + SubnetId: !Ref PublicSubnet1 + + PublicRouteTable: + Type: AWS::EC2::RouteTable + Properties: + VpcId: !Ref VPC + + DefaultPublicRoute: + Type: AWS::EC2::Route + DependsOn: InternetGatewayAttachment + Properties: + RouteTableId: !Ref PublicRouteTable + DestinationCidrBlock: 0.0.0.0/0 + GatewayId: !Ref InternetGateway + + PublicSubnet1RouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: !Ref PublicRouteTable + SubnetId: !Ref PublicSubnet1 + + PublicSubnet2RouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: !Ref PublicRouteTable + SubnetId: !Ref PublicSubnet2 + + + PrivateRouteTable1: + Type: AWS::EC2::RouteTable + Properties: + VpcId: !Ref VPC + + DefaultPrivateRoute1: + Type: AWS::EC2::Route + Properties: + RouteTableId: !Ref PrivateRouteTable1 + DestinationCidrBlock: 0.0.0.0/0 + NatGatewayId: !Ref NatGateway1 + + PrivateSubnet1RouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: !Ref PrivateRouteTable1 + SubnetId: !Ref PrivateSubnet1 + + PrivateRouteTable2: + Type: AWS::EC2::RouteTable + Properties: + VpcId: !Ref VPC + + DefaultPrivateRoute2: + Type: AWS::EC2::Route + Properties: + RouteTableId: !Ref PrivateRouteTable2 + DestinationCidrBlock: 0.0.0.0/0 + NatGatewayId: !Ref NatGateway1 + + PrivateSubnet2RouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: !Ref PrivateRouteTable2 + SubnetId: !Ref PrivateSubnet2 + + WebappRole: + Type: AWS::IAM::Role + Properties: + Path: "/" + RoleName: WebappRole + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - + Effect: "Allow" + Principal: + Service: + - "ec2.amazonaws.com" + - "codedeploy.amazonaws.com" + Action: + - "sts:AssumeRole" + ManagedPolicyArns: + - 'arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore' + Policies: + - + PolicyName: "allow-webapp-deployment-bucket-policy" + PolicyDocument: + Version: "2012-10-17" + Statement: + - + Effect: "Allow" + Action: + - "s3:getObject" + Resource: !Sub arn:${AWS::Partition}:s3:::${WebappDeploymentBucket}/* + IDCProvider: + Type: AWS::IAM::OIDCProvider + Properties: + Url: "https://token.actions.githubusercontent.com" + ClientIdList: + - "sts.amazonaws.com" + ThumbprintList: + - !Ref ThumbprintList + GitHubIAMRole: + Type: AWS::IAM::Role + Properties: + Path: "/" + RoleName: CodeDeployRoleforGitHub + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Action: sts:AssumeRoleWithWebIdentity + Principal: + Federated: !Ref IDCProvider + Condition: + StringLike: + token.actions.githubusercontent.com:sub: !Sub repo:${GithubRepoName}:* + MaxSessionDuration: 3600 + Description: "Github Actions role" + Policies: + + - PolicyName: 'CodeDeployRoleforGitHub-policy' + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: + - 'codedeploy:Get*' + - 'codedeploy:Batch*' + - 'codedeploy:CreateDeployment' + - 'codedeploy:RegisterApplicationRevision' + - 'codedeploy:List*' + Resource: + - !Sub 'arn:${AWS::Partition}:codedeploy:*:${AWS::AccountId}:*' + - Effect: Allow + Action: + - 's3:putObject' + Resource: !Sub arn:${AWS::Partition}:s3:::${WebappDeploymentBucket}/* + + WebappApplication: + Type: AWS::CodeDeploy::Application + Properties: + ApplicationName: CodeDeployAppNameWithASG + WebappDeploymentGroup: + Type: AWS::CodeDeploy::DeploymentGroup + Properties: + ApplicationName: !Ref WebappApplication + ServiceRoleArn: !GetAtt CodeDeployRole.Arn + DeploymentConfigName: CodeDeployDefault.OneAtATime + DeploymentGroupName: CodeDeployGroupName + AutoRollbackConfiguration: + Enabled: true + Events: + - DEPLOYMENT_FAILURE + - DEPLOYMENT_STOP_ON_REQUEST + + AutoScalingGroups: + - Ref: AutoScalingGroup + ALBSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: allow access to ALB from internet + VpcId: !Ref VPC + SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 8080 + ToPort: 8080 + CidrIp: 0.0.0.0/0 + SecurityGroupEgress: + - IpProtocol: '-1' + CidrIp: 0.0.0.0/0 + WebappSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: allow access to Webapp from ALB + VpcId: !Ref VPC + SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 8080 + ToPort: 8080 + SourceSecurityGroupId: + Ref: ALBSecurityGroup + SecurityGroupEgress: + - IpProtocol: '-1' + CidrIp: 0.0.0.0/0 + WebappDeploymentBucket: + Type: AWS::S3::Bucket + Properties: + BucketEncryption: + ServerSideEncryptionConfiguration: + - ServerSideEncryptionByDefault: + SSEAlgorithm: AES256 + PublicAccessBlockConfiguration: + BlockPublicAcls: true + BlockPublicPolicy: true + IgnorePublicAcls: true + RestrictPublicBuckets: true + CodeDeployRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - + Effect: "Allow" + Principal: + Service: + - "codedeploy.amazonaws.com" + Action: + - "sts:AssumeRole" + Path: "/" + ManagedPolicyArns: + - arn:aws:iam::aws:policy/service-role/AWSCodeDeployRole + Policies: + - + PolicyName: allow-autoscaling + PolicyDocument: + Version: "2012-10-17" + Statement: + - + Effect: Allow + Action: + - ec2:RunInstances + - ec2:CreateTags + - iam:PassRole + Resource: + - !Sub 'arn:${AWS::Partition}:codedeploy:*:${AWS::AccountId}:*' + + WebappInstanceProfile: + Type: AWS::IAM::InstanceProfile + Properties: + Roles: + - Ref: WebappRole + WebappLaunchConfig: + Type: AWS::AutoScaling::LaunchConfiguration + Properties: + AssociatePublicIpAddress: true + ImageId: + Ref: ImageId + InstanceType: + Ref: InstanceType + SecurityGroups: + - Ref: WebappSecurityGroup + IamInstanceProfile: + Ref: WebappInstanceProfile + UserData: + "Fn::Base64": + !Sub | + #!/bin/bash + + yum install -y java-1.8.0-openjdk-devel wget + java -version + cd /usr/local + wget https://archive.apache.org/dist/tomcat/tomcat-9/v9.0.43/bin/apache-tomcat-9.0.43.zip + wget https://archive.apache.org/dist/tomcat/tomcat-9/v9.0.43/bin/apache-tomcat-9.0.43.zip.asc + wget https://archive.apache.org/dist/tomcat/tomcat-9/v9.0.43/bin/apache-tomcat-9.0.43.zip.sha512 + + # verify hash / are these two outputs the same + cat apache-tomcat-9.0.43.zip.sha512 + sha512sum apache-tomcat-9.0.43.zip + + gpg --keyserver pgpkeys.mit.edu --recv-key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7 + gpg --verify apache-tomcat-9.0.43.zip.asc apache-tomcat-9.0.43.zip + + # if hash and signature are ok: + unzip apache-tomcat-9.0.43.zip + mv apache-tomcat-9.0.43 tomcat9 + echo 'JAVA_OPTS="$JAVA_OPTS -Djava.net.preferIPv4Stack=true -Djava.net.preferIPv4Addresses=true "' > /usr/local/tomcat9/bin/setenv.sh + ls -la tomcat9/ + useradd -r tomcat + chown -R tomcat:tomcat /usr/local/tomcat9 + ls -l /usr/local/tomcat9 + + echo "[Unit] + Description=Apache Tomcat Server + After=syslog.target network.target + + [Service] + Type=forking + User=tomcat + Group=tomcat + + Environment=CATALINA_PID=/usr/local/tomcat9/temp/tomcat.pid + Environment=CATALINA_HOME=/usr/local/tomcat9 + Environment=CATALINA_BASE=/usr/local/tomcat9 + + ExecStart=/usr/local/tomcat9/bin/catalina.sh start + ExecStop=/usr/local/tomcat9/bin/catalina.sh stop + + RestartSec=10 + Restart=always + [Install] + WantedBy=multi-user.target" > /etc/systemd/system/tomcat.service + + # firewall-cmd --zone=public --permanent --add-port=8080/tcp + # firewall-cmd --zone=public --permanent --add-port=8443/tcp + # firewall-cmd --reload + cd /usr/local/tomcat9/bin && chmod +x catalina.sh + systemctl daemon-reload + systemctl start tomcat.service + systemctl enable tomcat.service + systemctl status tomcat.service + yum install ruby -y + wget https://aws-codedeploy-${AWS::Region}.s3.${AWS::Region}.amazonaws.com/latest/install + chmod +x ./install + ./install auto + cd /tmp + yum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm + systemctl enable amazon-ssm-agent + systemctl start amazon-ssm-agent + + AutoScalingGroup: + Type: AWS::AutoScaling::AutoScalingGroup + Properties: + HealthCheckType: ELB + HealthCheckGracePeriod: 300 + DesiredCapacity: !Ref AutoScalingGroupDesiredCapacity + MinSize: !Ref AutoScalingGroupMinSize + MaxSize: !Ref AutoScalingGroupMaxSize + LaunchConfigurationName: + Ref: WebappLaunchConfig + VPCZoneIdentifier: + - Ref: PrivateSubnet1 + - Ref: PrivateSubnet2 + TargetGroupARNs: + - Ref: ALBTargetGroup + Tags: + - Key: Name + Value: webapp-example + PropagateAtLaunch: true + ALBListener: + Type: AWS::ElasticLoadBalancingV2::Listener + Properties: + DefaultActions: + - + Type: forward + TargetGroupArn: + Ref: ALBTargetGroup + LoadBalancerArn: + Ref: ApplicationLoadBalancer + Port: 8080 + Protocol: HTTP + ApplicationLoadBalancer: + Type: AWS::ElasticLoadBalancingV2::LoadBalancer + DependsOn: InternetGateway + Properties: + Scheme: internet-facing + Subnets: + - Ref: PublicSubnet1 + - Ref: PublicSubnet2 + SecurityGroups: + - Ref: ALBSecurityGroup + ALBTargetGroup: + Type: AWS::ElasticLoadBalancingV2::TargetGroup + Properties: + HealthCheckIntervalSeconds: 10 + UnhealthyThresholdCount: 2 + HealthyThresholdCount: 2 + HealthCheckPath: "/" + Port: 8080 + Protocol: HTTP + VpcId: !Ref VPC +Outputs: + + WebappUrl: + Description: Webapp URL + Value: + Fn::Join: + - '' + - - http:// + - !GetAtt ApplicationLoadBalancer.DNSName + - ':8080/SpringBootHelloWorldExampleApplication' + DeploymentGroup: + Description: Webapp Deployment Group + Value: !Ref WebappDeploymentGroup + DeploymentBucket: + Description: Deployment bucket + Value: !Ref WebappDeploymentBucket + ApplicationName: + Description: CodeDeploy Application name + Value: !Ref WebappApplication + GithubIAMRoleArn: + Description: IAM role for GitHub + Value: !GetAtt GitHubIAMRole.Arn diff --git a/spring-boot-hello-world-example/.classpath b/spring-boot-hello-world-example/.classpath new file mode 100644 index 0000000..0ca1374 --- /dev/null +++ b/spring-boot-hello-world-example/.classpath @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-boot-hello-world-example/.project b/spring-boot-hello-world-example/.project new file mode 100644 index 0000000..5e7bc12 --- /dev/null +++ b/spring-boot-hello-world-example/.project @@ -0,0 +1,59 @@ + + + spring-boot-hello-world-example + + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.springframework.ide.eclipse.boot.validation.springbootbuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.springframework.ide.eclipse.core.springnature + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + + + 1638392068018 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + + diff --git a/spring-boot-hello-world-example/.settings/org.eclipse.core.resources.prefs b/spring-boot-hello-world-example/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..29abf99 --- /dev/null +++ b/spring-boot-hello-world-example/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,6 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/main/resources=UTF-8 +encoding//src/test/java=UTF-8 +encoding//src/test/resources=UTF-8 +encoding/=UTF-8 diff --git a/spring-boot-hello-world-example/.settings/org.eclipse.jdt.apt.core.prefs b/spring-boot-hello-world-example/.settings/org.eclipse.jdt.apt.core.prefs new file mode 100644 index 0000000..d4313d4 --- /dev/null +++ b/spring-boot-hello-world-example/.settings/org.eclipse.jdt.apt.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.apt.aptEnabled=false diff --git a/spring-boot-hello-world-example/.settings/org.eclipse.jdt.core.prefs b/spring-boot-hello-world-example/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..951833c --- /dev/null +++ b/spring-boot-hello-world-example/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,10 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.methodParameters=generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore +org.eclipse.jdt.core.compiler.processAnnotations=disabled +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/spring-boot-hello-world-example/.settings/org.eclipse.m2e.core.prefs b/spring-boot-hello-world-example/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/spring-boot-hello-world-example/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/spring-boot-hello-world-example/pom.xml b/spring-boot-hello-world-example/pom.xml new file mode 100644 index 0000000..766e5e0 --- /dev/null +++ b/spring-boot-hello-world-example/pom.xml @@ -0,0 +1,125 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.2.BUILD-SNAPSHOT + + + com.springtest + SpringBootHelloWorldExampleApplication + 1 + SpringBootHelloWorldExampleApplication + Demo project for Spring Boot + war + + 1.8 + + + + + + org.springframework.boot + + spring-boot-starter-tomcat + + provided + + + + org.springframework.boot +spring-boot-starter-parent +2.2.1.RELEASE +pom + + +org.springframework.boot +spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + + + org.apache.maven.plugins + + maven-war-plugin + + 3.2.3 + + SpringBootHelloWorldExampleApplication + + + + + + default-war + + prepare-package + + + + false + + + + + + + + + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + + + + + + diff --git a/spring-boot-hello-world-example/src/main/java/com/helloworld/SpringBootHelloWorldExampleApplication.java b/spring-boot-hello-world-example/src/main/java/com/helloworld/SpringBootHelloWorldExampleApplication.java new file mode 100644 index 0000000..139e90e --- /dev/null +++ b/spring-boot-hello-world-example/src/main/java/com/helloworld/SpringBootHelloWorldExampleApplication.java @@ -0,0 +1,21 @@ +package com.helloworld; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +@SpringBootApplication +public class SpringBootHelloWorldExampleApplication extends SpringBootServletInitializer +{ + @Override + + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + + return application.sources(SpringBootHelloWorldExampleApplication.class); + } + public static void main(String[] args) +{ +SpringApplication.run(SpringBootHelloWorldExampleApplication.class, args); +} +} \ No newline at end of file diff --git a/spring-boot-hello-world-example/src/main/java/com/helloworld/controller/HelloWorldController.java b/spring-boot-hello-world-example/src/main/java/com/helloworld/controller/HelloWorldController.java new file mode 100644 index 0000000..ffe0f80 --- /dev/null +++ b/spring-boot-hello-world-example/src/main/java/com/helloworld/controller/HelloWorldController.java @@ -0,0 +1,12 @@ +package com.helloworld.controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +@RestController +public class HelloWorldController +{ +@RequestMapping("/") +public String hello() +{ +return "

Congratulations. You have successfully deployed the sample Spring Boot Application.

"; +} +}