GithubHelp home page GithubHelp logo

shehzadashiq / aws-bootcamp-cruddur-2023 Goto Github PK

View Code? Open in Web Editor NEW
1.0 1.0 0.0 2.79 MB

Shell 15.04% Python 33.84% HTML 1.39% CSS 10.92% JavaScript 32.00% Dockerfile 1.56% PowerShell 0.11% Ruby 2.76% TypeScript 2.38%

aws-bootcamp-cruddur-2023's People

Contributors

shehzadashiq avatar

Stargazers

 avatar

Watchers

 avatar  avatar

aws-bootcamp-cruddur-2023's Issues

Frontend Sync Tool

Listing of S3 bucket

image

Sync Executed
image

Invalidation Created
image

Invalidation Details
image

Failure on GitHub Actions
image

Backend Container refusing to build

After migrating to a new workspace I encountered the following issue when building.

image

aws-bootcamp-cruddur-2023-backend-flask-1      |     __import__(module_name)
aws-bootcamp-cruddur-2023-backend-flask-1      |   File "/backend-flask/app.py", line 112, in <module>
aws-bootcamp-cruddur-2023-backend-flask-1      |     @app.before_first_request
aws-bootcamp-cruddur-2023-backend-flask-1      | AttributeError: 'Flask' object has no attribute 'before_first_request'. Did you mean: '_got_first_request'

According to this article: https://stackoverflow.com/questions/73570041/flask-deprecated-before-first-request-how-to-update/74629704#74629704

before_first_request is deprecated and will be removed from Flask 2.3

To resolve this I had to do the following

# @app.before_first_request
with app.app_context():
  def init_rollbar():
      """init rollbar module"""
      rollbar.init(
          # access token
          rollbar_access_token,
          # environment name
          'production',
          # server root directory, makes tracebacks prettier
          root=os.path.dirname(os.path.realpath(__file__)),
          # flask already sets up logging
          allow_logging_basic_config=False)

      # send exceptions from `app` to rollbar, using flask's signal system.
      got_request_exception.connect(rollbar.contrib.flask.report_exception, app)\

The container now builds successfully.

CFN Creation

CLI Output of running ./bin/cfn/networking-deploy
image

Stack Ready to be reviewed
image

Change Set Created
image

Change Set ready to be executed
image

Execute Change Set
image

Creation in Progress
image

Stack Creation Events
image

Stack Overview Once completed
image

Stack Parameters used during Creation
image

Stack Resources
image

Stack Outputs
image

Stack Change Set
image

Stack Created Successfully
image

All stacks created
image

PostGres SQL Setup

Step 1: Initial Screen
image

Step 2: Installation Directory
image

Step 3: Select Components
image

Step 4: Data Directory
image

Step 5: use password here as the password
image

Step 6: Port
image

Step 7 - Advanced Options:
image

Step 8: Pre-Installation Summary
image

Step 9: Ready To Install
image

Step 10: Finish Setup
image

Windows Settings:
image

Windows Settings About:
image

Windows: Advanced System Settings
image

Environment Variables:
image

System Variables Path:
image

New Variable
image

Add C:\Program Files\PostgreSQL\15\bin to Path
image

Click OK,OK twice

Serverless Application Deployment

Verify Original Image was uploaded
image

Check how it looks, it should be 1920x1080
image

Confirm that the lambda has placed the file in the s3 bucket
image

Check that the processed image was resized to 512x512
image

Request Certificate for Cloudfront
image

Copying CloudFront Bucket Policy
image

Bucket Policy Applied
image

Create Route 53 entry for CF distribution
image

Create CloudFront Invalidation
image

Downloading lambda-authorizer application

image

Edit Runtime Settings
image

CruddurApiGatewayLambdaAuthorizer uploaded and packaged correctly
image

Create API
image

Triggers for CruddurAvatarUpload
image

Routes for API Gateway - Post
image

Routes for API Gateway - Options
image

Authorisation for API Gateway
image

Integration for KeyUpload
image

Integration for Options
image

Cors for API Gateway
image

AWS CLI Issues

In GitPod, docker compose started to fail

image

I noticed that tasks within Gitpod.yml were not working either.

image

Could not connect to the endpoint URL: "http://dynamodb-local:8000/"

This value was configured as an environment variable AWS_ENDPOINT_URL when we were using DynamoDB in week 5 locally. This had not caused any issues previously so I was surprised that this had happened.

To resolve this issue I unset the variable locally and removed it from Gitpod

gp env -u AWS_ENDPOINT_URL
unset AWS_ENDPOINT_URL

Once this had been unset I was able to run all aws_cli commands and run docker-compose

Content Moderation User

Running Cloudformation for user

image

Successfully Created Moderation User

image

Moderation Policy Applied Successfully

image

Creation of trigger

image

AppSync

App Sync Configuration

Navigate to AppSync

Click Create API

image

Choose Import from DynamoDB

image

Option Value
API Name crudAppSyncApi
DynamoDB table region Your-Region
DynamoDB table name ShouldPickUpYourDb
Service role Create and use a new service role

Specify API details

image

Specify GraphQL resources

image

image

Review and create

image

image

Click Create API

Initialising AppSync in Application

Overview

image

image

Choose Access Keys and enter your credentials

Choose your region

image

Generating credentials

Amplify Application Created
image

amplify add codegen --apiId <api_id>

Choose Js as language

Output of adding AppSync --apiID

image

Amplify CodeGen

image

AppSync Settings Overview

image

AppSync Schema

image

AppSync Data Source

image

AppSync Query Tool

This tool was invaluable in testing GraphQL queries to understand how a query should be constructed. In this screenshot the authorisation shows that the authentication method is API Key. It needs to be configured this way as the tool does not support IAM authentication. Make note to change this as required when testing.

image

Structure of results returned by query

image

image

Proof that AppSync works from the command line

image

Tables shown in DynamoDB

image

Error shown when trying to list message groups via AppSync

192.168.138.9 - - [31/Jul/2023 04:20:19] "GET /api/message_groups HTTP/1.1" 500 -
192.168.138.9 - - [31/Jul/2023 04:20:40] "OPTIONS /api/message_groups HTTP/1.1" 200 -
[2023-07-31 04:20:40,171] ERROR in app: Exception on /api/message_groups [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 2190, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 1486, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.10/site-packages/flask_cors/extension.py", line 176, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 1484, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 1469, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/backend-flask/lib/cognito_jwt_token.py", line 142, in decorated_function
    return f(*args, **kwargs)
  File "/backend-flask/routes/messages.py", line 21, in data_message_groups
    model = MessageGroups.run(cognito_user_id=g.cognito_user_id)
  File "/backend-flask/services/message_groups.py", line 36, in run
    data = AppSync.list_message_groups(appsync,my_user_uuid)
  File "/backend-flask/lib/appsync.py", line 119, in list_message_groups
  File "/usr/local/lib/python3.10/site-packages/gql/client.py", line 403, in execute
    return self.execute_sync(
  File "/usr/local/lib/python3.10/site-packages/gql/client.py", line 220, in execute_sync
    with self as session:
  File "/usr/local/lib/python3.10/site-packages/gql/client.py", line 702, in __enter__
    return self.connect_sync()
  File "/usr/local/lib/python3.10/site-packages/gql/client.py", line 686, in connect_sync
    self.session.fetch_schema()
  File "/usr/local/lib/python3.10/site-packages/gql/client.py", line 881, in fetch_schema
    execution_result = self.transport.execute(parse(get_introspection_query()))
  File "/usr/local/lib/python3.10/site-packages/gql/transport/requests.py", line 220, in execute
    response = self.session.request(
  File "/usr/local/lib/python3.10/site-packages/requests/sessions.py", line 575, in request
    prep = self.prepare_request(req)
  File "/usr/local/lib/python3.10/site-packages/requests/sessions.py", line 486, in prepare_request
    p.prepare(
  File "/usr/local/lib/python3.10/site-packages/requests/models.py", line 368, in prepare
    self.prepare_url(url, params)
  File "/usr/local/lib/python3.10/site-packages/requests/models.py", line 439, in prepare_url
    raise MissingSchema(
requests.exceptions.MissingSchema: Invalid URL 'None': No scheme supplied. Perhaps you meant https://None?
192.168.138.9 - - [31/Jul/2023 04:20:40] "GET /api/message_groups HTTP/1.1" 500 -

Prod Proof

Messaging to AltUser working in Prod

image

Cruds work in Prod

image

Replies working in Prod

image

CORS Amendments required to allow avatars to be uploaded to the S3 bucket

image

PUT Method not allowed in application

image

Profile Image successfully uploaded

image

Bio Changed

image

Issues running validator Tool

Error running validate command

image

Fixed by changing line 52 in lib/cpbvt/payloads/aws/policy.rb from

"#{general-params.run_uuid}-cross-account-role-template.yaml"

to

'cross-account-role-template.yaml'

This causes an issue because when trying to merge the files it cannot find the original source file and fails.

Error showing source file could not be found

image

Changes to Code

image

CodeBuild Creation Error

Builds failing when unable to download source

image

No logs were visible when source was failing

image

Troubleshooting showed what the issue was

image

Build failing with permissions errors

image

20 | [Container] 2023/05/03 23:07:48 Phase complete: DOWNLOAD_SOURCE State: SUCCEEDED
-- | --
21 | [Container] 2023/05/03 23:07:48 Phase context status code:  Message:
22 | [Container] 2023/05/03 23:07:48 Entering phase INSTALL
23 | [Container] 2023/05/03 23:07:48 Running command echo "cd into $CODEBUILD_SRC_DIR/backend"
24 | cd into /codebuild/output/src377814590/src/github.com/shehzadashiq/aws-bootcamp-cruddur-2023/backend
25 | ย 
26 | [Container] 2023/05/03 23:07:48 Running command cd $CODEBUILD_SRC_DIR/backend-flask
27 | ย 
28 | [Container] 2023/05/03 23:07:48 Running command aws ecr get-login-password --region $AWS_DEFAULT_REGION \| docker login --username AWS --password-stdin $IMAGE_URL
29 | ย 
30 | An error occurred (AccessDeniedException) when calling the GetAuthorizationToken operation: User: arn:aws:sts::797130574998:assumed-role/codebuild-cruddur--service-role/AWSCodeBuild-b0931d7a-83c6-4df9-a555-f341715bf817 is not authorized to perform: ecr:GetAuthorizationToken on resource: * because no identity-based policy allows the ecr:GetAuthorizationToken action
31 | Error: Cannot perform an interactive login from a non TTY device
32 | ย 
33 | [Container] 2023/05/03 23:08:01 Command did not exit successfully aws ecr get-login-password --region $AWS_DEFAULT_REGION \| docker login --username AWS --password-stdin $IMAGE_URL exit status 1
34 | [Container] 2023/05/03 23:08:01 Phase complete: INSTALL State: FAILED
35 | [Container] 2023/05/03 23:08:01 Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: aws ecr get-login-password --region $AWS_DEFAULT_REGION \| docker login --username AWS --password-stdin $IMAGE_URL. Reason: exit status 1

Misconfigured Environment
image

IAM Role required changing
image

Locate Role in IAM
image

Create Inline Policy
image

JSON Policy to Add

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "VisualEditor0",
      "Effect": "Allow",
      "Action": [
        "ecr:BatchCheckLayerAvailability",
        "ecr:CompleteLayerUpload",
        "ecr:GetAuthorizationToken",
        "ecr:InitiateLayerUpload",
        "ecr:PutImage",
        "ecr:UploadLayerPart",
        "ecr:BatchGetImage",
        "ecr:GetDownloadUrlForLayer"
      ],
      "Resource": "*"
    }
  ]
}

Call Policy -> ECRPermissions

image

Successful Run once permissions have been granted.

image

Cluster Stack Creation

Cluster fails to create with ALBSG failing

image

Deletion protection disabled:
LoadBalancerAttributes:
- Key: deletion_protection.enabled
Value: false

PrivateSubnetIds:
Value: !Join
- ","
- - !Ref SubnetPriv1
- !Ref SubnetPriv1
- !Ref SubnetPriv2
- !Ref SubnetPriv3

Has duplicate so changed to:

PrivateSubnetIds:
Value: !Join
- ","
- - !Ref SubnetPriv1
- !Ref SubnetPriv2
- !Ref SubnetPriv3

Frontend Static Build

Warnings being shown when running static build

image

These were addressed by commenting out the following import line

import ReactDOM from 'react-dom';

Banner Not Loading

Avatar image is displaying fine

image

Banner image placed in the banner folder does not display only a 1x1 pixel is displayed.

image

Verified that the banner.jpg exists in S3 bucket

image

Verified that all images exist in avatars folder

image

The same image uploaded to the avatars folder displays without any issue.

image

Ping was not working with new cloudfront distribution so I had to abandon testing it that way.

image

The cause for this was Kaspersky's Anti Banner component

image

Architecture Diagrams

CFN Networking Layer Diagram

image

CI/CD Layer Diagram Detail

image

Route53/Cloudfront Layer Diagram Detail

image

Architectural Diagram Overview

image

Architectural Diagram

CFN Network Layer

Service Stack Creation

Application failing to start

image

6/3/2023, 7:01:54 AM GMT+1 | cognito_jwt_token = CognitoJwtToken( | backend-flask
6/3/2023, 7:01:54 AM GMT+1 | File "/backend-flask/lib/cognito_jwt_token.py", line 32, in __init__ | backend-flask
6/3/2023, 7:01:54 AM GMT+1 | self._load_jwk_keys() | backend-flask
6/3/2023, 7:01:54 AM GMT+1 | File "/backend-flask/lib/cognito_jwt_token.py", line 39, in _load_jwk_keys | backend-flask
6/3/2023, 7:01:54 AM GMT+1 | self.jwk_keys = response.json()["keys"] | backend-flask
6/3/2023, 7:01:54 AM GMT+1 | KeyError: 'keys' | backend-flask

This was caused by a mistake in the cognito variables. I had the incorrect value for EnvAWSCognitoUserPoolId.

Changing this resolved the issue.

ELB Health Check Failures
image

Logs showed the following error

ConnectionRefusedError: [Errno 111] Connection refused
urllib3.exceptions.NewConnectionError: <botocore.awsrequest.AWSHTTPConnection object at 0x7f5a310e4970>: Failed to establish a new connection: [Errno 111] Connection refused
botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "http://127.0.0.1:2000/SamplingTargets"

To resolve this I overrode it first manually in the Console here by changing it to 4567 as mentioned by other bootcampers

image

This allowed the service stack to be created successfully.

image

To automate this I changed the backend health check port from 80 to 4567 in /workspace/aws-bootcamp-cruddur-2023/aws/cfn/cluster/template.yaml from

  BackendHealthCheckPort:
    Type: String
    Default: 80

to

  BackendHealthCheckPort:
    Type: String
    Default: 4567

This took the deployment time from hours down to 7 minutes

image

Application is inaccessible

The service stack once deployed successfully shows 200 in its logs

image

However, trying to access https://api.tajarba.com/api/health-check would result in the following error ERR_NAME_NOT_RESOLVED

image

This is because in Route53, the A record for api.tajarba.com needed to be changed. Here we can see it is pointing to the old ALB which no longer exists

image

To verify which ALB was created by the cluster this can be seen in the resources created by the Cluster stack CrdCluster

image

503 Error being shown once stack has been deployed

Accessing https://api.tajarba.com/api/health-check would show that the stack was successfully deployed however trying to access https://api.tajarba.com/api/activities/home would display a 503 error

image

This was because in the cluster stack HTTP Host Header had been set incorrectly

          HostHeaderConfig: 
            Values: 
              - api.cruddur.com

to

          HostHeaderConfig: 
            Values: 
              - api.tajarba.com

CI/CD Stack Creation

Error on First Run as Pipeline Execution Fails

image

Connection shows as pending
image

image

Choose Connection Application and click connect
![image]https://github.com/shehzadashiq/aws-bootcamp-cruddur-2023/assets/5746804/dd3d062e-0390-4a76-a97d-85b8a3719906

Connection created successfully
![image]https://github.com/shehzadashiq/aws-bootcamp-cruddur-2023/assets/5746804/99575532-7849-4c6c-aba5-2516b240f6b9

Pipeline still fails saying [GitHub] No Branch [prod] found for FullRepositoryName [aws-bootcamp-cruddur-2023]

image

When trying to edit the pipeline the following message is displayed A repository Id must be in the format <account>/<repository-name>

image

To resolve this change the following setting GithubRepo in aws/cfn/cicd/config.toml to include the account name e.g

GithubRepo = 'shehzadashiq/aws-bootcamp-cruddur-2023'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.