Repository Cleanup for project

This commit is contained in:
JustFiesta 2024-07-05 16:03:47 +02:00
parent c077a8c67a
commit 60d7c06280
12 changed files with 53 additions and 826 deletions

View file

@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -1,43 +0,0 @@
# Code configuration
For capstone project I made some changes in this code base. Mainly in: Dockerfile, Jenkinsfile and build.gradle.
Also I learned how to use MySQL for spring petclinic - it reqiures some enviroment variables:
* MYSQL_USER
* MYSQL_PASSWORD
* MYSQL_ROOT_PASSWORD
* MYSQL_DATABASE
* MYSQL_URL
They are needed for conenction to RDS. One can use it via `docker -e MYSQL_...` or `export MYSQL_...` (for `java -jar` usage).
<hr>
## Pipeline configuration
### Build
* Application is built with Gradle 8.X
* Checkstyle is provided via Gradle plugin
<hr>
### CI/CD
Agent is configured via command got from main Controller
and to be initilized manually (user, password, plugins, connection, etc.)
For the pipeline to work correctly one needs to setup credentials for Docker Hub and GitHub in Jenkins controller server.
The Github credentials are used to push tags to repository.
Also one needs to configure repository webhook for build server.
<hr>
### Dockerfile
For image creation basic gradle image is used for build purposes, with addition of distroless layer for application. Image is split into layers according to (at time of creation and my knowlage) current standards, and optimalized for minimal size.
<hr>

View file

@ -1,5 +0,0 @@
# Checkstyle info
[Great video about how iut works and how to configure this plugin](https://www.youtube.com/watch?v=zo3zyyo7Vkw&ab_channel=LeanStacks)
Reports are at: /build/reports/checkstyle/*

View file

@ -1,8 +0,0 @@
# Steps to creaet jenkins pipeline
1. Set credentials for Github/Docker/Nexus etc. **GitHub Tokens** shloud have premissions to hooks and commit status
2. If publish servers are needed - install publish over SSH plugin
3. Configure SSH Servers in Jenkins configuration (from Publish Over SSH plugin) to prod/test etc. **Name** is important for pipeline script!
4. Set credentials for these servers - ssh-keygen, then copy private key to jenkins/username + password. **ID** is importat for pipeline script!
5. Configure MultiBranch Pipeline to watch over code commits with GitHub creds on certain branches.
6. Configure Jenkinsfile pipeline

View file

@ -1,2 +0,0 @@
rules:
- pattern: ".*"

View file

@ -1,253 +0,0 @@
#!/usr/bin/env bash
# -------------------
# This script sets up basic AWS environment for pushing docker images into the cloud
# It creates: VPC, Subnet, Elastic Container Registry (ECR), EC2 instance with a public IP, Security Groups
#
# Required: Docker, configured AWS CLI, EC2 key pair created from AWS
# Global data
REGION="eu-west-1"
VPC_ID=""
SUBNET_ID=""
SECURITY_GROUP_ID=""
ECR_REPO_URI=""
INSTANCE_ID=""
# Get data from user - set it as env to be used in later scripts
echo "---------------------------------------"
echo ""
read -p "Enter owner name: " OWNER && export OWNER
read -p "Enter project name: " PROJECT && export PROJECT
read -p "Enter VPC name: " VPC_NAME && export VPC_NAME
read -p "Enter security group name: " SECURITY_GROUP_NAME && export SECURITY_GROUP_NAME
read -p "Enter internet gateway name: " INTERNERT_GATEWAY_NAME && export INTERNERT_GATEWAY_NAME
read -p "Enter ECR repository name: " ECR_NAME && export ECR_NAME
read -p "Enter EC2 instance name: " INSTANCE_NAME && export INSTANCE_NAME
read -p "Enter key pair name: " KEY_PAIR_NAME && export KEY_PAIR_NAME
read -p "Enter Elastic IP name: " EIP_NAME && export EIP_NAME
echo ""
echo "---------------------------------------"
echo ""
echo "Creating VPC..."
VPC_ID=$(aws ec2 create-vpc \
--cidr-block 10.0.0.0/16 \
--region "$REGION" \
--tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value='"$VPC_NAME"'},{Key=Owner,Value='"$OWNER"'},{Key=Project,Value='"$PROJECT"'}]' \
--query 'Vpc.VpcId' \
--output text)
if [ -z "$VPC_ID" ]; then
echo "Error during VPC creation."
exit 1
fi
echo "VPC with ID $VPC_ID has been created and tagged."
echo "VPC is now correctly configured."
echo ""
echo "---------------------------------------"
echo ""
# Create Subnet
echo "Creating Subnet..."
SUBNET_ID=$(aws ec2 create-subnet \
--vpc-id "$VPC_ID" \
--cidr-block 10.0.0.0/24 \
--availability-zone "$REGION"a \
--tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value='"$VPC_NAME"'},{Key=Owner,Value='"$OWNER"'},{Key=Project,Value='"$PROJECT"'}]' \
--query 'Subnet.SubnetId' \
--output text)
if [ -z "$SUBNET_ID" ]; then
echo "Error during Subnet creation."
exit 1
fi
echo "Subnet with ID $SUBNET_ID has been created and tagged."
echo "Subnet is now correctly configured."
echo ""
echo "---------------------------------------"
echo ""
# Create Security Group
echo "Creating Security Group..."
SECURITY_GROUP_ID=$(aws ec2 create-security-group \
--group-name "$SECURITY_GROUP_NAME" \
--description "Security group for devOps internship assesment" \
--vpc-id "$VPC_ID" \
--tag-specifications 'ResourceType=security-group,Tags=[{Key=Name,Value='"$SECURITY_GROUP_NAME"'},{Key=Owner,Value='"$OWNER"'},{Key=Project,Value='"$PROJECT"'}]' \
--region "$REGION" \
--query 'GroupId' \
--output text)
echo "Security Group ID: $SECURITY_GROUP_ID"
if [ -z "$SECURITY_GROUP_ID" ]; then
echo "Error during Security Group creation."
exit 1
fi
echo "Security Group with ID $SECURITY_GROUP_ID has been created."
echo "Security Group is now correctly configured."
# Allow inbound SSH access (port 22) from anywhere
aws ec2 authorize-security-group-ingress \
--group-id "$SECURITY_GROUP_ID" \
--protocol tcp \
--port 22 \
--cidr 0.0.0.0/0 \
--region "$REGION"
echo "Inbound SSH access has been allowed for Security Group."
echo ""
echo "---------------------------------------"
echo ""
echo "Creating Internet Gateway..."
INTERNET_GATEWAY_ID=$(aws ec2 create-internet-gateway \
--tag-specifications 'ResourceType=internet-gateway,Tags=[{Key=Name,Value='"$VPC_NAME"'},{Key=Owner,Value='"$OWNER"'},{Key=Project,Value='"$PROJECT"'}]' \
--region "$REGION" \
--query 'InternetGateway.InternetGatewayId' \
--output text)
if [ -z "$INTERNET_GATEWAY_ID" ]; then
echo "Error during Internet Gateway creation."
exit 1
fi
echo "Internet Gateway with ID $INTERNET_GATEWAY_ID has been created and tagged."
# Attach Internet Gateway to VPC
aws ec2 attach-internet-gateway --internet-gateway-id "$INTERNET_GATEWAY_ID" --vpc-id "$VPC_ID" --region "$REGION"
if [ $? -ne 0 ]; then
echo "Error during attaching Internet Gateway to VPC."
exit 1
fi
echo "Internet Gateway has been attached to VPC."
echo ""
echo "---------------------------------------"
echo ""
# Create Elastic Container Registry (ECR)
echo "Creating Elastic Container Registry (ECR)..."
ECR_REPO_JSON=$(aws ecr create-repository \
--repository-name "$ECR_NAME" \
--region "$REGION" \
--query 'repository' \
--output json)
ECR_REPO_URI=$(echo "$ECR_REPO_JSON" | jq -r '.repositoryUri')
ECR_REPO_ARN=$(echo "$ECR_REPO_JSON" | jq -r '.repositoryArn')
if [ -z "$ECR_REPO_URI" ] || [ -z "$ECR_REPO_ARN" ]; then
echo "Error during ECR creation."
exit 1
fi
echo "ECR repository created: $ECR_REPO_URI"
# Adding tags to the ECR repository
aws ecr tag-resource \
--resource-arn "$ECR_REPO_ARN" \
--tags Key=Name,Value="$ECR_NAME" Key=Owner,Value="$OWNER" Key=Project,Value="$PROJECT"
echo "Tags added to ECR repository."
echo ""
echo "---------------------------------------"
echo ""
# Create EC2 instance
echo "Creating EC2 instance..."
# UserData script to install Docker and run it
USER_DATA_SCRIPT=$(cat <<EOF
#!/bin/bash
sudo yum update -y
sudo yum install -y docker
sudo systemctl enable docker
sudo systemctl start docker
sudo usermod -aG docker $USER
newgrp docker
EOF
)
INSTANCE_ID=$(aws ec2 run-instances \
--image-id ami-0ac67a26390dc374d \
--count 1 \
--instance-type t3.micro \
--key-name "$KEY_PAIR_NAME" \
--security-group-ids "$SECURITY_GROUP_ID" \
--subnet-id "$SUBNET_ID" \
--region "$REGION" \
--user-data "$USER_DATA_SCRIPT" \
--iam-instance-profile Name=allow_ec2_ecr \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value='"$VPC_NAME"'},{Key=Owner,Value='"$OWNER"'},{Key=Project,Value='"$PROJECT"'}]' \
--query 'Instances[0].InstanceId' \
--output text)
export INSTANCE_ID
if [ -z "$INSTANCE_ID" ]; then
echo "Error during EC2 instance creation."
exit 1
fi
echo "EC2 instance with ID $INSTANCE_ID has been created."
echo "EC2 instance is now correctly configured."
echo ""
echo "---------------------------------------"
echo ""
# Allocate and associate public IP address with EC2 instance
echo "Allocating and associating public IP address with EC2 instance..."
EIP_ALLOCATION_JSON=$(aws ec2 allocate-address \
--domain vpc \
--region "$REGION" \
--tag-specifications 'ResourceType=elastic-ip,Tags=[{Key=Name,Value='"$VPC_NAME"'},{Key=Owner,Value='"$OWNER"'},{Key=Project,Value='"$PROJECT"'}]' \
--output json)
# Check if the allocation was successful
if [ $? -ne 0 ]; then
echo "Error during EIP allocation."
exit 1
fi
# Extract the AllocationId and PublicIp using jq
EIP_ALLOCATION_ID=$(echo "$EIP_ALLOCATION_JSON" | jq -r '.AllocationId')
PUBLIC_IP=$(echo "$EIP_ALLOCATION_JSON" | jq -r '.PublicIp')
if [ -z "$EIP_ALLOCATION_ID" ] || [ -z "$PUBLIC_IP" ]; then
echo "Error: Unable to retrieve EIP details."
exit 1
fi
echo "Public IP allocated: $PUBLIC_IP with Allocation ID: $EIP_ALLOCATION_ID"
# Associate the allocated Elastic IP with the EC2 instance
aws ec2 associate-address --instance-id "$INSTANCE_ID" --allocation-id "$EIP_ALLOCATION_ID" --region "$REGION"
if [ $? -ne 0 ]; then
echo "Error during EIP association."
exit 1
fi
echo "Public IP address has been associated with EC2 instance: $PUBLIC_IP"
echo "Tags added to Elastic IP."
echo "EC2 instance, public IP address, and Security Group have been successfully created."
./send_image_to_aws.sh

View file

@ -1,60 +1,68 @@
# DevOps excercises # Sprint-petclinic codebase
This repository contains sample spring-boot app - [spring-petclinic](https://github.com/spring-projects/spring-petclinic). It is a starting point for excercises with: This repository contains codebase for capstone project.
* Gradle/Maven - build tools For capstone project I made some changes in this code base. Mainly in: Dockerfile, Jenkinsfile and build.gradle.
* Nexus - artifact management, private repositories
* Docker - containerisation Also I learned how to use MySQL for spring petclinic - it reqiures some enviroment variables:
* Jenkins - CI + CD
* AWS - cloud * MYSQL_USER
* MYSQL_PASSWORD
* MYSQL_ROOT_PASSWORD
* MYSQL_DATABASE
* MYSQL_URL
They are needed for conenction to RDS. One can use it via `docker -e MYSQL_...` or `export MYSQL_...` (for `java -jar` usage).
<hr> <hr>
## Build tools ## Overwiev
1. Getting familiar with wrappers ### Build
2. Setting up with build.gradle/pom.xml
3. Getting familiar with test/build/package/checkstyle/install/cleanup processes
4. Adding source control management (SCM)
5. Versioning with release plugin
6. Plugin management
7. Custom jobs (Gradle)
8. Adding custom repositories
## Nexus * Application is built with Gradle 8.X
* Checkstyle is provided via Gradle plugin
1. Setting up proxy and private repositories <hr>
2. Releasing artifacts to private repository
3. Integration with maven via Nexus Repository Maven Plugin
## Docker ### CI/CD
1. Containers vs VM Jenkins server can be used in two ways:
2. How container works
3. Dockerfile and its (best practices)[https://docs.docker.com/develop/develop-images/dockerfile_best-practices/]
4. Multi-stage builds
5. Usage in (local development)[https://docs.docker.com/language/java/develop/]
6. (How to make images smaller)[https://learnk8s.io/blog/smaller-docker-images] - distroless/slim base images + multi-stage + less layers
7. (Vulnerability scanning)[https://docs.docker.com/scout/]
8. Basics of docker compose
## Jenkins * As agent
* As separete build server
1. Core principals of CI/CD Each will change a bit in configuration.
2. Credentials management
3. Plugins
4. Distributed builds using agents
5. Integrate source code management, build tools, and test reports in Jenkins. (>Tools)
6. Manage builds
7. Enviroment variables and parametrised builds
8. Integration with docker
9. Creating basic pipeline
## AWS <hr>
1. Console + CLI operations ### Dockerfile
2. Credential management for CLI
3. Creation and usage of basic components: S3, EC2, VPC, ECR, Security Groups, IAM.
4. Some automation with bash scripts
Note: run scripts using `source` command, eg. `source prepare_aws_enviroment.sh` Dockerfile is provided, also compose file for testing is present. Additionally, there is compose file with provided sample connection string - one needs to change it accoring to RDS endpoint and user data.
## Explanation of components
### CI/CD
Agent is configured via command got from main Controller (Or used as a separete server - then Jenkins file agent need to be updated) and to be initilized manually (user, password, plugins, connection, etc.)
Agent usage:
* Add agent via commend given from Controller.
* Ensure all needed credentials are added in Controller (DockerHub, GitHub, AWS, etc.) - check infrastructure README
* Configure repository webhook for server
Separete server usage:
* For the pipeline to work correctly one needs to setup credentials for Docker Hub and GitHub in Jenkins server
* Configure repository webhook for server
<hr>
### Dockerfile
For image creation basic Gradle image is used for build purposes, with addition of distroless layer for application. Image is split into layers according to (at time of creation and my knowlage) current standards, and optimalized for minimal size.
Two compose files are present - one for testing connection string, other for providing container that connects to RDS.
<hr>

View file

@ -1,124 +0,0 @@
#!/usr/bin/env bash
# -------------------
# This script removes AWS environment from previous scripts
# It removes: VPC, Subnet, Elastic Container Registry (ECR), EC2 instance with a public IP, Security Groups
#
# Required: configured AWS CLI
# Global variable
ERR=0
# User info
read -p "Enter region remove resources from: " REGION
read -p "Enter tag key to remove resources from: " TAG_KEY
read -p "Enter tag value to remove resources from: " TAG_VALUE
read -p "Enter ECR name to remove it from AWS: " ECR_NAME
echo "---------------------------------------"
echo ""
# Deleting EC2 Instance
echo "Deleting EC2 Instances..."
instances=$(aws ec2 describe-instances --region "$REGION" --query "Reservations[].Instances[?Tags[?Key=='$TAG_KEY'&&Value=='$TAG_VALUE']].InstanceId" --output text)
if [ -z "$instances" ]; then
echo "There are no EC2 instances for tag $TAG_KEY:$TAG_VALUE."
else
for instance_id in $instances; do
aws ec2 terminate-instances --region "$REGION" --instance-ids "$instance_id"
if [ $? -eq 0 ]; then
echo "Instance $instance_id terminated successfully."
else
echo "Error terminating instance $instance_id."
ERR=$((ERR+1))
fi
done
fi
echo ""
echo "---------------------------------------"
echo ""
# Deleting Elastic Container Registry (ECR)
echo "Deleting Elastic Container Registries (ECR)..."
if aws ecr describe-repositories --repository-names "$ECR_NAME" --region "$REGION" > /dev/null 2>&1; then
aws ecr delete-repository --region "$REGION" --repository-name "$ECR_NAME" --force
if [ $? -eq 0 ]; then
echo "ECR repository $ECR_NAME deleted successfully."
else
echo "Error deleting ECR repository $ECR_NAME."
ERR=$((ERR+1))
fi
else
echo "ECR repository $ECR_NAME does not exist."
fi
echo ""
echo "---------------------------------------"
echo ""
# Deleting VPC
echo "Deleting VPCs..."
for vpc_id in $(aws ec2 describe-vpcs --region "$REGION" --query "Vpcs[?Tags[?Key=='$TAG_KEY'&&Value=='$TAG_VALUE']].VpcId" --output text); do
echo "Deleting VPC: $vpc_id..."
# Delete security groups
sec_groups_ids=$(aws ec2 describe-security-groups --region "$REGION" --filters "Name=vpc-id,Values=$vpc_id" --query "SecurityGroups[].GroupId" --output text)
if [ -n "$sec_groups_ids" ]; then
for sg_id in $sec_groups_ids; do
aws ec2 delete-security-group --group-id "$sg_id" --region "$REGION"
done
fi
# Delete network ACLs
nacl_ids=$(aws ec2 describe-network-acls --region "$REGION" --filters "Name=vpc-id,Values=$vpc_id" --query "NetworkAcls[].NetworkAclId" --output text)
if [ -n "$nacl_ids" ]; then
for nacl_id in $nacl_ids; do
aws ec2 delete-network-acl --network-acl-id "$nacl_id" --region "$REGION"
done
fi
# Delete subnets
subnets_ids=$(aws ec2 describe-subnets --region "$REGION" --filters "Name=vpc-id,Values=$vpc_id" --query "Subnets[].SubnetId" --output text)
if [ -n "$subnets_ids" ]; then
for subnet_id in $subnets_ids; do
aws ec2 delete-subnet --subnet-id "$subnet_id" --region "$REGION"
done
fi
# Delete route table associations and route tables
route_tables_ids=$(aws ec2 describe-route-tables --region "$REGION" --filters "Name=vpc-id,Values=$vpc_id" --query "RouteTables[].RouteTableId" --output text)
if [ -n "$route_tables_ids" ]; then
for rtb_id in $route_tables_ids; do
aws ec2 disassociate-route-table --association-id "$(aws ec2 describe-route-tables --region "$REGION" --route-table-id "$rtb_id" --query "RouteTables[?VpcId=='$vpc_id'].Associations[].RouteTableAssociationId" --output text)" --region "$REGION"
aws ec2 delete-route-table --route-table-id "$rtb_id" --region "$REGION"
done
fi
# Delete internet gateway
igw_id=$(aws ec2 describe-internet-gateways --region "$REGION" --filters "Name=attachment.vpc-id,Values=$vpc_id" --query "InternetGateways[].InternetGatewayId" --output text)
if [ -n "$igw_id" ]; then
aws ec2 detach-internet-gateway --internet-gateway-id "$igw_id" --vpc-id "$vpc_id" --region "$REGION"
aws ec2 delete-internet-gateway --internet-gateway-id "$igw_id" --region "$REGION"
fi
# Finally, delete VPC
aws ec2 delete-vpc --vpc-id "$vpc_id" --region "$REGION"
if [ $? -eq 0 ]; then
echo ""
echo "VPC $vpc_id deleted successfully."
else
echo "Error deleting VPC $vpc_id."
ERR=$((ERR+1))
fi
done
echo ""
echo "---------------------------------------"
echo ""
if [ $ERR -gt 0 ]; then
echo "Not all resources were deleted successfully. Please check them manually."
else
echo "All resources with tag $TAG_KEY:$TAG_VALUE have been successfully deleted from AWS."
fi

View file

@ -1,76 +0,0 @@
#!/usr/bin/env bash
# -------------------
# This script sets authenthicates and pulls docker image. Then runs it on host
#
# Reqiured: configured AWS CLI, EC2 key pair created from AWS
# Global data
IMAGE_NAME="$ECR_NAME:latest"
FULL_KEY_PATH=""
echo "---------------------------------------"
echo ""
read -p "Enter your SSH AWS Key absolute path: " FULL_KEY_PATH
# Get the public IP of EC2 instance from previus script
echo "Getting public IP address of EC2 instance..."
PUBLIC_IP=$(aws ec2 describe-instances --instance-ids "$INSTANCE_ID" --query 'Reservations[0].Instances[0].PublicIpAddress' --output text --region "$REGION")
if [ -z "$PUBLIC_IP" ]; then
echo "Error: Failed to get public IP address of EC2 instance."
exit 1
fi
echo "Public IP address of EC2 instance: $PUBLIC_IP"
# Authorize ECR in docker
echo "Getting authentication token for ECR..."
DOCKER_LOGIN_CMD=$(aws ecr get-login-password --region "$REGION" | docker login --username AWS --password-stdin "$AWS_ACCOUNT_ID".dkr.ecr."$REGION".amazonaws.com 2>&1)
if [[ $DOCKER_LOGIN_CMD == *"Login Succeeded"* ]]; then
echo "Authentication with ECR successful."
else
echo "Error: Failed to authenticate with ECR."
exit 1
fi
# SSH to EC2 and run instance
echo "SSH-ing to EC2 instance and running Docker image from ECR..."
ssh -i "$FULL_KEY_PATH" ec2-user@"$PUBLIC_IP" <<EOF
# Ensure Docker is installed and running
echo "Updating packages and starting Docker..."
sudo yum update -y
sudo yum install -y docker
sudo service docker start
echo "---------------------------------------"
echo "Authorising ECR..."
# Authorize ECR in Docker using IAM role
aws ecr get-login-password --region "$REGION" | docker login --username AWS --password-stdin "$AWS_ACCOUNT_ID".dkr.ecr."$REGION".amazonaws.com
echo "---------------------------------------"
echo "Pulling Docker image from ECR..."
# Pull the Docker image
docker pull "$AWS_ACCOUNT_ID".dkr.ecr."$REGION".amazonaws.com/"$IMAGE_NAME"
echo "---------------------------------------"
echo "Running spring-petclinic container..."
# Run the Docker image
docker run -d --name spring-pertlinic \
-p 8080:8080 "$AWS_ACCOUNT_ID".dkr.ecr."$REGION".amazonaws.com/"$IMAGE_NAME"
# Check if the docker run command was successful
if [ \$? -eq 0 ]; then
echo "Docker container started successfully."
else
echo "Error: Failed to start Docker container."
exit 1
fi
EOF
if [ $? -eq 0 ]; then
echo "Docker image has been successfully deployed on EC2 instance."
else
echo "Failed to deploy Docker image on EC2 instance."
fi

View file

@ -1,67 +0,0 @@
#!/usr/bin/env bash
# -------------------
# This script sets builds and pushes image to previously made ECR
#
# Reqiured: Docker, configured AWS CLI, EC2 key pair created from AWS
# Global data
AWS_ACCOUNT_ID=""
# Get data from user
echo "---------------------------------------"
echo ""
read -p "Enter your AWS account ID: " AWS_ACCOUNT_ID
# Build docker image locally
echo "---------------------------------------"
echo "Building Docker image..."
if docker build -t spring-petclinic .; then
echo "Docker image built successfully."
else
echo "Error: Failed to build Docker image."
exit 1
fi
# Log in to ECR
echo "---------------------------------------"
echo "Logging in to Amazon ECR..."
DOCKER_LOGIN_CMD=$(aws ecr get-login-password --region "$REGION")
if [ -n "$DOCKER_LOGIN_CMD" ]; then
echo "Got credentials from AWS CLI."
else
echo "Error: Failed to get credentials from AWS CLI."
exit 1
fi
if echo "$DOCKER_LOGIN_CMD" | docker login --username AWS --password-stdin "$AWS_ACCOUNT_ID".dkr.ecr."$REGION".amazonaws.com; then
echo "Logged in to ECR successfully."
else
echo "Error: Failed to log in to ECR."
exit 1
fi
# Tag the image
echo "---------------------------------------"
echo "Tagging Docker image..."
if docker tag spring-petclinic:latest "$AWS_ACCOUNT_ID".dkr.ecr."$REGION".amazonaws.com/"$ECR_NAME":latest; then
echo "Docker image tagged successfully."
else
echo "Error: Failed to tag Docker image."
exit 1
fi
# Push image to ECR
echo "---------------------------------------"
echo "Pushing Docker image to ECR..."
if docker push "$AWS_ACCOUNT_ID".dkr.ecr."$REGION".amazonaws.com/"$ECR_NAME":latest; then
echo "Docker image pushed to ECR successfully."
else
echo "Error: Failed to push Docker image to ECR."
exit 1
fi
echo "Docker image has been successfully pushed to ECR."
./run_container_on_EC2.sh

View file

@ -1 +0,0 @@
test webhook