diff --git a/.gitignore b/.gitignore index 549e00a2..54577eb6 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,9 @@ build/ ### VS Code ### .vscode/ +terraform/.terraform.lock.hcl +terraform/bankapp-automate-key +terraform/terraform.tfstate +terraform/terraform.tfstate.backup +terraform/.terraform/providers/registry.terraform.io/hashicorp/aws/5.65.0/windows_amd64/terraform-provider-aws_v5.65.0_x5.exe +terraform/variables.tf diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..adc16701 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +# ----- Stage 1 ----------- +FROM maven:3.8.3-openjdk-17 as builder + +WORKDIR /src + +COPY . /src + +RUN mvn clean install -DskipTests=true + +# ----- Stage 2 ----------- + +FROM openjdk:17-alpine + +COPY --from=builder /src/target/*.jar /src/target/bankapp.jar + +EXPOSE 8080 + +CMD ["java","-jar","/src/target/bankapp.jar"] \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 00000000..96e1e341 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,87 @@ +@Library('Shared') _ +pipeline { + agent any + + environment{ + SONAR_HOME = tool "Sonar" + } + + parameters { + string(name: 'DOCKER_TAG', defaultValue: '', description: 'Setting docker image for latest push') + } + + stages { + + stage("Workspace cleanup"){ + steps{ + script{ + cleanWs() + } + } + } + + stage('Git: Code Checkout') { + steps { + script{ + code_checkout("https://github.com/LondheShubham153/Springboot-BankApp.git","DevOps") + } + } + } + + stage("Trivy: Filesystem scan"){ + steps{ + script{ + trivy_scan() + } + } + } + + stage("OWASP: Dependency check"){ + steps{ + script{ + owasp_dependency() + } + } + } + + stage("SonarQube: Code Analysis"){ + steps{ + script{ + sonarqube_analysis("Sonar","bankapp","bankapp") + } + } + } + + stage("SonarQube: Code Quality Gates"){ + steps{ + script{ + sonarqube_code_quality() + } + } + } + + stage("Docker: Build Images"){ + steps{ + script{ + docker_build("bankapp","${params.DOCKER_TAG}","madhupdevops") + } + } + } + + stage("Docker: Push to DockerHub"){ + steps{ + script{ + docker_push("bankapp","${params.DOCKER_TAG}","madhupdevops") + } + } + } + } + post{ + success{ + archiveArtifacts artifacts: '*.xml', followSymlinks: false + build job: "BankApp-CD", parameters: [ + string(name: 'DOCKER_TAG', value: "${params.DOCKER_TAG}") + ] + } + } +} diff --git a/README.md b/README.md new file mode 100644 index 00000000..4db1d8b8 --- /dev/null +++ b/README.md @@ -0,0 +1,245 @@ +# End-to-End Setup for Deploying Applications with ArgoCD and EKS + +This README provides a complete step-by-step guide with all the commands required to set up ArgoCD on an AWS EKS cluster, deploy your applications, and configure GitOps. + +--- + +## **1. Create an EKS Cluster** + +### **Create the Cluster Without a Node Group** +```bash +eksctl create cluster --name=bankapp \ + --region=ap-south-1 \ + --version=1.31 \ + --without-nodegroup +``` + +### **Associate IAM OIDC Provider** +```bash +eksctl utils associate-iam-oidc-provider \ + --region ap-south-1 \ + --cluster bankapp \ + --approve +``` + +### **Create a Node Group** +```bash +eksctl create nodegroup --cluster=bankapp \ + --region=ap-south-1 \ + --name=bankapp \ + --node-type=t2.medium \ + --nodes=2 \ + --nodes-min=2 \ + --nodes-max=2 \ + --node-volume-size=29 \ + --ssh-access \ + --ssh-public-key=k8s-in-one-shot +``` + +--- + +## **2. Deploy ArgoCD** + +### **Create the ArgoCD Namespace** +```bash +kubectl create namespace argocd +``` + +### **Install ArgoCD Using Official Manifests** +```bash +kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml +``` + +### **Verify ArgoCD Pods** +```bash +watch kubectl get pods -n argocd +``` + +### **Install ArgoCD CLI** +```bash +curl --silent --location -o /usr/local/bin/argocd https://github.com/argoproj/argo-cd/releases/download/v2.4.7/argocd-linux-amd64 +chmod +x /usr/local/bin/argocd +argocd version +``` + +### **Change ArgoCD Server Service Type to NodePort** +```bash +kubectl patch svc argocd-server -n argocd -p '{"spec": {"type": "NodePort"}}' +``` + +### **Verify the NodePort Service** +```bash +kubectl get svc -n argocd +``` + +### **Expose the Port on Security Groups** +- In the AWS Console, update the security group for your EKS worker nodes to allow inbound traffic on the NodePort assigned to the `argocd-server` service. + +### **Access the ArgoCD Web UI** +- Open your browser and navigate to: + ``` + http://: + ``` + +--- + +## **3. Configure ArgoCD for EKS** + +### **Login to ArgoCD Using CLI** +```bash +argocd login : --username admin +``` + +### **Retrieve the Default Admin Password** +```bash +kubectl get secret argocd-initial-admin-secret -n argocd -o jsonpath="{.data.password}" | base64 -d +``` + +### **Check Available Clusters in ArgoCD** +```bash +argocd cluster list +``` + +### **Get the EKS Cluster Context** +```bash +kubectl config get-contexts +``` + +### **Add EKS Cluster to ArgoCD** +```bash +argocd cluster add --name bankapp-eks-cluster +``` +- Replace `` with your EKS cluster context name (e.g., `Madhup@bankapp.us-west-1.eksctl.io`). + +--- + +## **4. Deploy Applications Using ArgoCD** + +### **Prepare Kubernetes Manifests in a Git Repository** +- Organize your manifests (e.g., `namespace.yaml`, `deployment.yaml`, `service.yaml`) in a Git repository. + +### **Create an Application in ArgoCD** +```bash +argocd app create bankapp \ + --repo \ + --path \ + --dest-server https://kubernetes.default.svc \ + --dest-namespace bankapp-namespace +``` + +### **Sync the Application** +```bash +argocd app sync bankapp +``` + +### **Monitor Application Status** +```bash +argocd app list +``` + +--- + +## **5. Deploy NGINX Ingress Controller** + +### **Install NGINX Ingress Controller Using Helm** +```bash +helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx +helm repo update +helm install ingress-nginx ingress-nginx/ingress-nginx \ + --namespace ingress-nginx --create-namespace +``` + +### **Verify Installation** +Check if the NGINX Ingress Controller pods are running: +```bash +kubectl get pods -n ingress-nginx +``` + +### **Retrieve the Load Balancer IP** +Get the external IP assigned to the NGINX Ingress Controller: +```bash +kubectl get svc -n ingress-nginx +``` + +### **Update DNS** +Point your domain (`junoon.trainwithshubham.com`) to the external IP of the NGINX Load Balancer. + +--- + +## **6. Enable HTTPS for the Application** + +### **Install Cert-Manager** +```bash +kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.1/cert-manager.yaml +``` + +### **Create Let's Encrypt ClusterIssuer** +Save the following as `letsencrypt-clusterissuer.yaml`: +```yaml +apiVersion: cert-manager.io/v1 +kind: ClusterIssuer +metadata: + name: letsencrypt-prod +spec: + acme: + server: https://acme-v02.api.letsencrypt.org/directory + email: your-email@example.com + privateKeySecretRef: + name: letsencrypt-prod-key + solvers: + - http01: + ingress: + class: nginx +``` +Apply the ClusterIssuer: +```bash +kubectl apply -f letsencrypt-clusterissuer.yaml +``` + +### **Update Ingress with TLS Configuration** +- Modify your Ingress to include TLS and reference the `letsencrypt-prod` ClusterIssuer. +- Apply the updated Ingress: +```bash +kubectl apply -f +``` + +### **Verify Certificate Issuance** +```bash +kubectl get certificate -n bankapp-namespace +``` + +--- + +## **7. Verify Deployment** + +### **Check Deployed Resources** +```bash +kubectl get all -n bankapp-namespace +``` + +### **Access the Application** +- Open your browser and navigate to: + ``` + https://junoon.trainwithshubham.com + ``` + +--- + +## **8. Add Autoscaling** + +### **Install the Metrics Server** +```bash +kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml +``` + +### **Get the Top Nodes and Pods** +```bash + kubectl top nodes + kubectl top pods -n bankapp-namespace +``` +### **Apply HPA** +```bash + kubectl apply -f bankapp-hpa.yml +``` +--- + diff --git a/kubernetes/README.md b/kubernetes/README.md new file mode 100644 index 00000000..4db1d8b8 --- /dev/null +++ b/kubernetes/README.md @@ -0,0 +1,245 @@ +# End-to-End Setup for Deploying Applications with ArgoCD and EKS + +This README provides a complete step-by-step guide with all the commands required to set up ArgoCD on an AWS EKS cluster, deploy your applications, and configure GitOps. + +--- + +## **1. Create an EKS Cluster** + +### **Create the Cluster Without a Node Group** +```bash +eksctl create cluster --name=bankapp \ + --region=ap-south-1 \ + --version=1.31 \ + --without-nodegroup +``` + +### **Associate IAM OIDC Provider** +```bash +eksctl utils associate-iam-oidc-provider \ + --region ap-south-1 \ + --cluster bankapp \ + --approve +``` + +### **Create a Node Group** +```bash +eksctl create nodegroup --cluster=bankapp \ + --region=ap-south-1 \ + --name=bankapp \ + --node-type=t2.medium \ + --nodes=2 \ + --nodes-min=2 \ + --nodes-max=2 \ + --node-volume-size=29 \ + --ssh-access \ + --ssh-public-key=k8s-in-one-shot +``` + +--- + +## **2. Deploy ArgoCD** + +### **Create the ArgoCD Namespace** +```bash +kubectl create namespace argocd +``` + +### **Install ArgoCD Using Official Manifests** +```bash +kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml +``` + +### **Verify ArgoCD Pods** +```bash +watch kubectl get pods -n argocd +``` + +### **Install ArgoCD CLI** +```bash +curl --silent --location -o /usr/local/bin/argocd https://github.com/argoproj/argo-cd/releases/download/v2.4.7/argocd-linux-amd64 +chmod +x /usr/local/bin/argocd +argocd version +``` + +### **Change ArgoCD Server Service Type to NodePort** +```bash +kubectl patch svc argocd-server -n argocd -p '{"spec": {"type": "NodePort"}}' +``` + +### **Verify the NodePort Service** +```bash +kubectl get svc -n argocd +``` + +### **Expose the Port on Security Groups** +- In the AWS Console, update the security group for your EKS worker nodes to allow inbound traffic on the NodePort assigned to the `argocd-server` service. + +### **Access the ArgoCD Web UI** +- Open your browser and navigate to: + ``` + http://: + ``` + +--- + +## **3. Configure ArgoCD for EKS** + +### **Login to ArgoCD Using CLI** +```bash +argocd login : --username admin +``` + +### **Retrieve the Default Admin Password** +```bash +kubectl get secret argocd-initial-admin-secret -n argocd -o jsonpath="{.data.password}" | base64 -d +``` + +### **Check Available Clusters in ArgoCD** +```bash +argocd cluster list +``` + +### **Get the EKS Cluster Context** +```bash +kubectl config get-contexts +``` + +### **Add EKS Cluster to ArgoCD** +```bash +argocd cluster add --name bankapp-eks-cluster +``` +- Replace `` with your EKS cluster context name (e.g., `Madhup@bankapp.us-west-1.eksctl.io`). + +--- + +## **4. Deploy Applications Using ArgoCD** + +### **Prepare Kubernetes Manifests in a Git Repository** +- Organize your manifests (e.g., `namespace.yaml`, `deployment.yaml`, `service.yaml`) in a Git repository. + +### **Create an Application in ArgoCD** +```bash +argocd app create bankapp \ + --repo \ + --path \ + --dest-server https://kubernetes.default.svc \ + --dest-namespace bankapp-namespace +``` + +### **Sync the Application** +```bash +argocd app sync bankapp +``` + +### **Monitor Application Status** +```bash +argocd app list +``` + +--- + +## **5. Deploy NGINX Ingress Controller** + +### **Install NGINX Ingress Controller Using Helm** +```bash +helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx +helm repo update +helm install ingress-nginx ingress-nginx/ingress-nginx \ + --namespace ingress-nginx --create-namespace +``` + +### **Verify Installation** +Check if the NGINX Ingress Controller pods are running: +```bash +kubectl get pods -n ingress-nginx +``` + +### **Retrieve the Load Balancer IP** +Get the external IP assigned to the NGINX Ingress Controller: +```bash +kubectl get svc -n ingress-nginx +``` + +### **Update DNS** +Point your domain (`junoon.trainwithshubham.com`) to the external IP of the NGINX Load Balancer. + +--- + +## **6. Enable HTTPS for the Application** + +### **Install Cert-Manager** +```bash +kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.1/cert-manager.yaml +``` + +### **Create Let's Encrypt ClusterIssuer** +Save the following as `letsencrypt-clusterissuer.yaml`: +```yaml +apiVersion: cert-manager.io/v1 +kind: ClusterIssuer +metadata: + name: letsencrypt-prod +spec: + acme: + server: https://acme-v02.api.letsencrypt.org/directory + email: your-email@example.com + privateKeySecretRef: + name: letsencrypt-prod-key + solvers: + - http01: + ingress: + class: nginx +``` +Apply the ClusterIssuer: +```bash +kubectl apply -f letsencrypt-clusterissuer.yaml +``` + +### **Update Ingress with TLS Configuration** +- Modify your Ingress to include TLS and reference the `letsencrypt-prod` ClusterIssuer. +- Apply the updated Ingress: +```bash +kubectl apply -f +``` + +### **Verify Certificate Issuance** +```bash +kubectl get certificate -n bankapp-namespace +``` + +--- + +## **7. Verify Deployment** + +### **Check Deployed Resources** +```bash +kubectl get all -n bankapp-namespace +``` + +### **Access the Application** +- Open your browser and navigate to: + ``` + https://junoon.trainwithshubham.com + ``` + +--- + +## **8. Add Autoscaling** + +### **Install the Metrics Server** +```bash +kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml +``` + +### **Get the Top Nodes and Pods** +```bash + kubectl top nodes + kubectl top pods -n bankapp-namespace +``` +### **Apply HPA** +```bash + kubectl apply -f bankapp-hpa.yml +``` +--- + diff --git a/kubernetes/bankapp-deployment.yml b/kubernetes/bankapp-deployment.yml new file mode 100644 index 00000000..b8129d2a --- /dev/null +++ b/kubernetes/bankapp-deployment.yml @@ -0,0 +1,63 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + labels: + app: bankapp-deploy + name: bankapp-deploy + namespace: bankapp-namespace +spec: + replicas: 2 # Keep replicas >= 2 for high availability + selector: + matchLabels: + app: bankapp-deploy + template: + metadata: + labels: + app: bankapp-deploy + spec: + containers: + - name: bankapp + image: pratik83/bankapp-eks:v1 + ports: + - containerPort: 8080 + env: + - name: SPRING_DATASOURCE_URL + valueFrom: + configMapKeyRef: + name: bankapp-config + key: SPRING_DATASOURCE_URL + - name: SPRING_DATASOURCE_USERNAME + valueFrom: + configMapKeyRef: + name: bankapp-config + key: SPRING_DATASOURCE_USERNAME + - name: MYSQL_DATABASE + valueFrom: + configMapKeyRef: + name: bankapp-config + key: MYSQL_DATABASE + - name: SPRING_DATASOURCE_PASSWORD + valueFrom: + secretKeyRef: + name: mysql-secret + key: SPRING_DATASOURCE_PASSWORD + # readinessProbe: + # httpGet: + # path: /actuator/health # Update this based on your app's health endpoint + # port: 8080 + # initialDelaySeconds: 10 + # periodSeconds: 5 + # livenessProbe: + # httpGet: + # path: /actuator/health # Update this based on your app's health endpoint + # port: 8080 + # initialDelaySeconds: 30 + # periodSeconds: 10 + resources: + requests: + memory: "512Mi" + cpu: "250m" + limits: + memory: "1Gi" + cpu: "500m" + diff --git a/kubernetes/bankapp-hpa.yml b/kubernetes/bankapp-hpa.yml new file mode 100644 index 00000000..6c030161 --- /dev/null +++ b/kubernetes/bankapp-hpa.yml @@ -0,0 +1,19 @@ +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: bankapp-hpa + namespace: bankapp-namespace +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: bankapp-deploy + minReplicas: 1 + maxReplicas: 5 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 40 diff --git a/kubernetes/bankapp-namespace.yaml b/kubernetes/bankapp-namespace.yaml new file mode 100644 index 00000000..3a4a5170 --- /dev/null +++ b/kubernetes/bankapp-namespace.yaml @@ -0,0 +1,6 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: bankapp-namespace + labels: + name: bankapp-namespace diff --git a/kubernetes/bankapp-service.yaml b/kubernetes/bankapp-service.yaml new file mode 100644 index 00000000..c63175da --- /dev/null +++ b/kubernetes/bankapp-service.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Service +metadata: + name: bankapp-service + namespace: bankapp-namespace + labels: + app: bankapp +spec: + selector: + app: bankapp-deploy + ports: + - protocol: TCP + port: 8080 + targetPort: 8080 + diff --git a/kubernetes/bankapp-service.yml b/kubernetes/bankapp-service.yml new file mode 100644 index 00000000..e69de29b diff --git a/kubernetes/configmap.yaml b/kubernetes/configmap.yaml new file mode 100644 index 00000000..f2acc025 --- /dev/null +++ b/kubernetes/configmap.yaml @@ -0,0 +1,9 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: bankapp-config + namespace: bankapp-namespace +data: + MYSQL_DATABASE: BankDB + SPRING_DATASOURCE_URL: jdbc:mysql://mysql-svc.bankapp-namespace.svc.cluster.local:3306/BankDB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC + SPRING_DATASOURCE_USERNAME: root diff --git a/kubernetes/mysql-deployment.yml b/kubernetes/mysql-deployment.yml new file mode 100644 index 00000000..c9baa53a --- /dev/null +++ b/kubernetes/mysql-deployment.yml @@ -0,0 +1,42 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: mysql + namespace: bankapp-namespace + labels: + app: mysql +spec: + replicas: 1 + selector: + matchLabels: + app: mysql + template: + metadata: + labels: + app: mysql + spec: + containers: + - name: mysql + image: mysql:8.0 # Use a specific, stable version for production + ports: + - containerPort: 3306 + env: + - name: MYSQL_ROOT_PASSWORD + valueFrom: + secretKeyRef: + name: mysql-secret + key: MYSQL_ROOT_PASSWORD + - name: MYSQL_DATABASE + valueFrom: + configMapKeyRef: + name: bankapp-config + key: MYSQL_DATABASE + volumeMounts: + - name: mysql-pv-storage + mountPath: /var/lib/mysql + subPath: mysql-data # Optional: Ensure a subdirectory is used for better volume organization + volumes: + - name: mysql-pv-storage + persistentVolumeClaim: + claimName: mysql-pvc + diff --git a/kubernetes/mysql-service.yaml b/kubernetes/mysql-service.yaml new file mode 100644 index 00000000..607a8ef2 --- /dev/null +++ b/kubernetes/mysql-service.yaml @@ -0,0 +1,14 @@ +apiVersion: v1 +kind: Service +metadata: + name: mysql-svc + namespace: bankapp-namespace + labels: + app: mysql +spec: + selector: + app: mysql + ports: + - protocol: TCP + port: 3306 + targetPort: 3306 diff --git a/kubernetes/persistent-volume-claim.yaml b/kubernetes/persistent-volume-claim.yaml new file mode 100644 index 00000000..ff23dbd1 --- /dev/null +++ b/kubernetes/persistent-volume-claim.yaml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: mysql-pvc + namespace: bankapp-namespace +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 10Gi + storageClassName: standard diff --git a/kubernetes/persistent-volume.yaml b/kubernetes/persistent-volume.yaml new file mode 100644 index 00000000..efbda4d3 --- /dev/null +++ b/kubernetes/persistent-volume.yaml @@ -0,0 +1,16 @@ +apiVersion: v1 +kind: PersistentVolume +metadata: + name: mysql-pv + namespace: bankapp-namespace +spec: + capacity: + storage: 10Gi + volumeMode: Filesystem + accessModes: + - ReadWriteOnce + persistentVolumeReclaimPolicy: Retain # Keeps the PV after the PVC is deleted + storageClassName: standard # Make sure this matches your cluster's default storage class + hostPath: + path: /mnt/data/mysql + type: DirectoryOrCreate diff --git a/kubernetes/secrets.yaml b/kubernetes/secrets.yaml new file mode 100644 index 00000000..c6596fdb --- /dev/null +++ b/kubernetes/secrets.yaml @@ -0,0 +1,10 @@ +apiVersion: v1 +kind: Secret +metadata: + name: mysql-secret + namespace: bankapp-namespace +type: Opaque +data: + MYSQL_ROOT_PASSWORD: VGVzdEAxMjM= # Base64 for "Test@123" + SPRING_DATASOURCE_PASSWORD: VGVzdEAxMjM= # Base64 for "Test@123" + diff --git a/secrets.yaml b/secrets.yaml new file mode 100644 index 00000000..c6596fdb --- /dev/null +++ b/secrets.yaml @@ -0,0 +1,10 @@ +apiVersion: v1 +kind: Secret +metadata: + name: mysql-secret + namespace: bankapp-namespace +type: Opaque +data: + MYSQL_ROOT_PASSWORD: VGVzdEAxMjM= # Base64 for "Test@123" + SPRING_DATASOURCE_PASSWORD: VGVzdEAxMjM= # Base64 for "Test@123" + diff --git a/src/main/java/com/example/bankapp/config/SecurityConfig.java b/src/main/java/com/example/bankapp/config/SecurityConfig.java deleted file mode 100644 index 38db9af4..00000000 --- a/src/main/java/com/example/bankapp/config/SecurityConfig.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.example.bankapp.config; - -import com.example.bankapp.service.AccountService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; - -@Configuration -@EnableWebSecurity -public class SecurityConfig { - - @Autowired - AccountService accountService; - - @Bean - public static PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - - @Bean - public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { - http - .csrf(csrf -> csrf.disable()) - .authorizeHttpRequests(authz -> authz - .requestMatchers("/register").permitAll() - .requestMatchers("/home").permitAll() - .requestMatchers("/h2-console/**").permitAll() - .requestMatchers("/images/**").permitAll() - .requestMatchers("/css/**").permitAll() - .anyRequest().authenticated() - ) - .formLogin(form -> form - .loginPage("/login") - .loginProcessingUrl("/login") - .defaultSuccessUrl("/dashboard", true) - .permitAll() - ) - .logout(logout -> logout - .invalidateHttpSession(true) - .clearAuthentication(true) - .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) - .logoutSuccessUrl("/login?logout") - .permitAll() - ) - .headers(headers -> headers - .frameOptions(frameOptions -> frameOptions.sameOrigin()) - ); - - return http.build(); - } - - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(accountService).passwordEncoder(passwordEncoder()); - - } -} \ No newline at end of file diff --git a/src/main/java/com/example/bankapp/controller/BankController.java b/src/main/java/com/example/bankapp/controller/BankController.java deleted file mode 100644 index 19fcded7..00000000 --- a/src/main/java/com/example/bankapp/controller/BankController.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.example.bankapp.controller; - -import com.example.bankapp.model.Account; -import com.example.bankapp.service.AccountService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestParam; - -import java.math.BigDecimal; - -@Controller -public class BankController { - - @Autowired - private AccountService accountService; - - @GetMapping("/dashboard") - public String dashboard(Model model) { - String username = SecurityContextHolder.getContext().getAuthentication().getName(); - Account account = accountService.findAccountByUsername(username); - model.addAttribute("account", account); - return "dashboard"; - } - - @GetMapping("/register") - public String showRegistrationForm() { - return "register"; - } - - @PostMapping("/register") - public String registerAccount(@RequestParam String username, @RequestParam String password, Model model) { - try { - accountService.registerAccount(username, password); - return "redirect:/login"; - } catch (RuntimeException e) { - model.addAttribute("error", e.getMessage()); - return "register"; - } - } - - @GetMapping("/login") - public String login() { - return "login"; - } - - @PostMapping("/deposit") - public String deposit(@RequestParam BigDecimal amount) { - String username = SecurityContextHolder.getContext().getAuthentication().getName(); - Account account = accountService.findAccountByUsername(username); - accountService.deposit(account, amount); - return "redirect:/dashboard"; - } - - @PostMapping("/withdraw") - public String withdraw(@RequestParam BigDecimal amount, Model model) { - String username = SecurityContextHolder.getContext().getAuthentication().getName(); - Account account = accountService.findAccountByUsername(username); - - try { - accountService.withdraw(account, amount); - } catch (RuntimeException e) { - model.addAttribute("error", e.getMessage()); - model.addAttribute("account", account); - return "dashboard"; - } - - return "redirect:/dashboard"; - } - - @GetMapping("/transactions") - public String transactionHistory(Model model) { - String username = SecurityContextHolder.getContext().getAuthentication().getName(); - Account account = accountService.findAccountByUsername(username); - model.addAttribute("transactions", accountService.getTransactionHistory(account)); - return "transactions"; - } - - @PostMapping("/transfer") - public String transferAmount(@RequestParam String toUsername, @RequestParam BigDecimal amount, Model model) { - String username = SecurityContextHolder.getContext().getAuthentication().getName(); - Account fromAccount = accountService.findAccountByUsername(username); - - try { - accountService.transferAmount(fromAccount, toUsername, amount); - } catch (RuntimeException e) { - model.addAttribute("error", e.getMessage()); - model.addAttribute("account", fromAccount); - return "dashboard"; - } - - return "redirect:/dashboard"; - } - -} diff --git a/src/main/java/com/example/bankapp/model/Account.java b/src/main/java/com/example/bankapp/model/Account.java deleted file mode 100644 index b5e3f17d..00000000 --- a/src/main/java/com/example/bankapp/model/Account.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.example.bankapp.model; - -import jakarta.persistence.*; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; - -import java.math.BigDecimal; -import java.util.Collection; -import java.util.List; - -@Entity -public class Account implements UserDetails { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - private String username; - private String password; - private BigDecimal balance; - - @OneToMany(mappedBy = "account") - private List transactions; - - @Transient - private Collection authorities; - - public Account() { - - } - - public Account(String username, String password, BigDecimal balance, List transactions, Collection authorities) { - this.username = username; - this.password = password; - this.balance = balance; - this.transactions = transactions; - this.authorities = authorities; - } - - @Override - public Collection getAuthorities() { - return authorities; - } - - public void setAuthorities(Collection authorities) { - this.authorities = authorities; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public BigDecimal getBalance() { - return balance; - } - - public void setBalance(BigDecimal balance) { - this.balance = balance; - } - - public List getTransactions() { - return transactions; - } - - public void setTransactions(List transactions) { - this.transactions = transactions; - } -} diff --git a/src/main/java/com/example/bankapp/model/Transaction.java b/src/main/java/com/example/bankapp/model/Transaction.java deleted file mode 100644 index b3f371f9..00000000 --- a/src/main/java/com/example/bankapp/model/Transaction.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.example.bankapp.model; - -import jakarta.persistence.*; -import java.math.BigDecimal; -import java.time.LocalDateTime; - -@Entity -public class Transaction { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - private BigDecimal amount; - private String type; - private LocalDateTime timestamp; - - @ManyToOne - @JoinColumn(name = "account_id") - private Account account; - - public Transaction() { - - } - - public Transaction(BigDecimal amount, String type, LocalDateTime timestamp, Account account) { - this.amount = amount; - this.type = type; - this.timestamp = timestamp; - this.account = account; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public BigDecimal getAmount() { - return amount; - } - - public void setAmount(BigDecimal amount) { - this.amount = amount; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public LocalDateTime getTimestamp() { - return timestamp; - } - - public void setTimestamp(LocalDateTime timestamp) { - this.timestamp = timestamp; - } - - public Account getAccount() { - return account; - } - - public void setAccount(Account account) { - this.account = account; - } -} diff --git a/src/main/java/com/example/bankapp/repository/AccountRepository.java b/src/main/java/com/example/bankapp/repository/AccountRepository.java deleted file mode 100644 index 72553370..00000000 --- a/src/main/java/com/example/bankapp/repository/AccountRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.example.bankapp.repository; - -import com.example.bankapp.model.Account; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.Optional; - -public interface AccountRepository extends JpaRepository { - Optional findByUsername(String username); -} diff --git a/src/main/java/com/example/bankapp/repository/TransactionRepository.java b/src/main/java/com/example/bankapp/repository/TransactionRepository.java deleted file mode 100644 index 7d4f2578..00000000 --- a/src/main/java/com/example/bankapp/repository/TransactionRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.example.bankapp.repository; - -import com.example.bankapp.model.Transaction; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.List; - -public interface TransactionRepository extends JpaRepository { - List findByAccountId(Long accountId); -} diff --git a/src/main/java/com/example/bankapp/service/AccountService.java b/src/main/java/com/example/bankapp/service/AccountService.java deleted file mode 100644 index 5d7d90ec..00000000 --- a/src/main/java/com/example/bankapp/service/AccountService.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.example.bankapp.service; - -import com.example.bankapp.model.Account; -import com.example.bankapp.model.Transaction; -import com.example.bankapp.repository.AccountRepository; -import com.example.bankapp.repository.TransactionRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; - -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -@Service -public class AccountService implements UserDetailsService { - - @Autowired - PasswordEncoder passwordEncoder; - - @Autowired - private AccountRepository accountRepository; - - @Autowired - private TransactionRepository transactionRepository; - - public Account findAccountByUsername(String username) { - return accountRepository.findByUsername(username).orElseThrow(() -> new RuntimeException("Account not found")); - } - - public Account registerAccount(String username, String password) { - if (accountRepository.findByUsername(username).isPresent()) { - throw new RuntimeException("Username already exists"); - } - - Account account = new Account(); - account.setUsername(username); - account.setPassword(passwordEncoder.encode(password)); // Encrypt password - account.setBalance(BigDecimal.ZERO); // Initial balance set to 0 - return accountRepository.save(account); - } - - - public void deposit(Account account, BigDecimal amount) { - account.setBalance(account.getBalance().add(amount)); - accountRepository.save(account); - - Transaction transaction = new Transaction( - amount, - "Deposit", - LocalDateTime.now(), - account - ); - transactionRepository.save(transaction); - } - - public void withdraw(Account account, BigDecimal amount) { - if (account.getBalance().compareTo(amount) < 0) { - throw new RuntimeException("Insufficient funds"); - } - account.setBalance(account.getBalance().subtract(amount)); - accountRepository.save(account); - - Transaction transaction = new Transaction( - amount, - "Withdrawal", - LocalDateTime.now(), - account - ); - transactionRepository.save(transaction); - } - - public List getTransactionHistory(Account account) { - return transactionRepository.findByAccountId(account.getId()); - } - - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - - Account account = findAccountByUsername(username); - if (account == null) { - throw new UsernameNotFoundException("Username or Password not found"); - } - return new Account( - account.getUsername(), - account.getPassword(), - account.getBalance(), - account.getTransactions(), - authorities()); - } - - public Collection authorities() { - return Arrays.asList(new SimpleGrantedAuthority("USER")); - } - - public void transferAmount(Account fromAccount, String toUsername, BigDecimal amount) { - if (fromAccount.getBalance().compareTo(amount) < 0) { - throw new RuntimeException("Insufficient funds"); - } - - Account toAccount = accountRepository.findByUsername(toUsername) - .orElseThrow(() -> new RuntimeException("Recipient account not found")); - - // Deduct from sender's account - fromAccount.setBalance(fromAccount.getBalance().subtract(amount)); - accountRepository.save(fromAccount); - - // Add to recipient's account - toAccount.setBalance(toAccount.getBalance().add(amount)); - accountRepository.save(toAccount); - - // Create transaction records for both accounts - Transaction debitTransaction = new Transaction( - amount, - "Transfer Out to " + toAccount.getUsername(), - LocalDateTime.now(), - fromAccount - ); - transactionRepository.save(debitTransaction); - - Transaction creditTransaction = new Transaction( - amount, - "Transfer In from " + fromAccount.getUsername(), - LocalDateTime.now(), - toAccount - ); - transactionRepository.save(creditTransaction); - } - -} diff --git a/src/main/java/com/example/bankapp/service/TransactionService.java b/src/main/java/com/example/bankapp/service/TransactionService.java deleted file mode 100644 index 8df56067..00000000 --- a/src/main/java/com/example/bankapp/service/TransactionService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.example.bankapp.service; - -import com.example.bankapp.model.Transaction; -import com.example.bankapp.repository.TransactionRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.List; - -@Service -public class TransactionService { - - @Autowired - private TransactionRepository transactionRepository; - - public List findByAccountId(Long accountId) { - return transactionRepository.findByAccountId(accountId); - } - - public void saveTransaction(Transaction transaction) { - transactionRepository.save(transaction); - } -} diff --git a/src/main/resources/templates/transactions.html b/src/main/resources/templates/transactions.html index 70b504cf..892042c8 100644 --- a/src/main/resources/templates/transactions.html +++ b/src/main/resources/templates/transactions.html @@ -113,8 +113,8 @@

Transaction History

- + th:classappend="${transaction.type.contains('Transfer In') || transaction.type == 'Deposit'} ? 'text-success' : 'text-danger'"> + diff --git a/terraform/.terraform/providers/registry.terraform.io/hashicorp/aws/5.65.0/windows_amd64/LICENSE.txt b/terraform/.terraform/providers/registry.terraform.io/hashicorp/aws/5.65.0/windows_amd64/LICENSE.txt new file mode 100644 index 00000000..b9ac071e --- /dev/null +++ b/terraform/.terraform/providers/registry.terraform.io/hashicorp/aws/5.65.0/windows_amd64/LICENSE.txt @@ -0,0 +1,375 @@ +Copyright (c) 2017 HashiCorp, Inc. + +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/terraform/bankapp-automate-key.pub b/terraform/bankapp-automate-key.pub new file mode 100644 index 00000000..d134556c --- /dev/null +++ b/terraform/bankapp-automate-key.pub @@ -0,0 +1 @@ +ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIM3BhVKeWKB+UD1fk1OK+AxxkzMH6nfxuT4rwGyAsOhG prati@LAPTOP-67ETTK7D diff --git a/terraform/ec2.tf b/terraform/ec2.tf new file mode 100644 index 00000000..d29419d5 --- /dev/null +++ b/terraform/ec2.tf @@ -0,0 +1,93 @@ + +data "aws_ami" "os_image" { + owners = ["099720109477"] + most_recent = true + filter { + name = "state" + values = ["available"] + } + filter { + name = "name" + values = ["ubuntu/images/hvm-ssd/*amd64*"] + } +} + +resource "aws_key_pair" "deployer" { + key_name = "bankapp-automate-key" + public_key = file("bankapp-automate-key.pub") +} + +resource "aws_default_vpc" "default" { + +} + +resource "aws_security_group" "allow_user_to_connect" { + name = "allow TLS" + description = "Allow user to connect" + vpc_id = aws_default_vpc.default.id + ingress { + description = "port 22 allow" + from_port = 22 + to_port = 22 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } + + egress { + description = " allow all outgoing traffic " + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + ingress { + description = "port 80 allow" + from_port = 80 + to_port = 80 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } + + ingress { + description = "port 443 allow" + from_port = 443 + to_port = 443 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } + + tags = { + Name = "bankapp-security" + } +} + +resource "aws_instance" "testinstance" { + ami = data.aws_ami.os_image.id + instance_type = "t2.medium" + key_name = aws_key_pair.deployer.key_name + security_groups = [aws_security_group.allow_user_to_connect.name] + tags = { + Name = "bankapp-automate-instance" + } + root_block_device { + volume_size = 27 + volume_type = "gp3" + } + # connection { + # type = "ssh" + # user = "ubuntu" + # private_key = file("terra-key") + # host = self.public_ip + # } + + # provisioner "remote-exec" { + # inline = [ + # "sudo apt update -y", + # "sudo apt install -y apache2", + # "sudo systemctl start apache2", + # "sudo systemctl enable apache2", + # "echo 'Hello from Terraform Provisioners!' | sudo tee /var/www/html/index.html" + # ] + # } +} diff --git a/terraform/output.tf b/terraform/output.tf new file mode 100644 index 00000000..e1b4e4fe --- /dev/null +++ b/terraform/output.tf @@ -0,0 +1,7 @@ +output "arn" { + value = aws_instance.testinstance.arn +} + +output "public_ip" { + value = aws_instance.testinstance.public_ip +} \ No newline at end of file diff --git a/terraform/terraform.tf b/terraform/terraform.tf new file mode 100644 index 00000000..658bc7fb --- /dev/null +++ b/terraform/terraform.tf @@ -0,0 +1,12 @@ +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = "5.65.0" + } + } +} + +provider "aws" { + region = var.aws_region +} \ No newline at end of file