Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task 8 #17

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
AWS_POSTGRES_DB_USER=
AWS_POSTGRES_DB_HOST=
AWS_POSTGRES_DB_NAME=
AWS_POSTGRES_DB_PASSWORD=
AWS_POSTGRES_DB_PORT=
18 changes: 18 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
.env

# compiled output
/dist
/node_modules
package-lock.json

# Logs
logs
Expand Down Expand Up @@ -36,3 +39,18 @@ lerna-debug.log*
.elasticbeanstalk/*
!.elasticbeanstalk/*.cfg.yml
!.elasticbeanstalk/*.global.yml


# Python

*.swp
package-lock.json
__pycache__
.pytest_cache
.venv
venv
*.egg-info

# CDK asset staging directory
.cdk.staging
cdk.out
7 changes: 7 additions & 0 deletions api_test.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
###

GET https://9xxyy8znb3.execute-api.eu-north-1.amazonaws.com/prod/ HTTP/1.1
Content-Type: application/json
# x-api-key: TestApiKey

###
31 changes: 31 additions & 0 deletions create_cart_tables_and_insert_items.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
-- 1. Create the carts table

CREATE TABLE carts (
id UUID PRIMARY KEY,
user_id UUID NOT NULL,
created_at DATE NOT NULL,
updated_at DATE NOT NULL,
status VARCHAR(10) NOT NULL CHECK (status IN ('OPEN', 'ORDERED'))
);

-- 2. Create the cart_items table

CREATE TABLE cart_items (
cart_id UUID REFERENCES carts(id),
product_id UUID,
count INTEGER,
PRIMARY KEY (cart_id, product_id)
);

-- 3. Insert test data into carts

INSERT INTO carts (id, user_id, created_at, updated_at, status) VALUES
('b3e1c25d-d2e8-4c5c-a8a3-f2e6ad9d0d61', 'c4e6ac7e-bd13-4b74-8f8f-63a1b3b1e689', '2024-07-01', '2024-07-01', 'OPEN'),
('5a1d7e11-5d62-4d2f-9f6b-c4e4c5c6a84f', 'd7a2f14b-ef87-4c3e-9f5d-f5a7b7e5d4e3', '2024-07-02', '2024-07-02', 'ORDERED');

-- 4. Insert test data into cart_items

INSERT INTO cart_items (cart_id, product_id, count) VALUES
('b3e1c25d-d2e8-4c5c-a8a3-f2e6ad9d0d61', 'bf700af8-b570-4a77-b1d2-38ba3ea34553', 30),
('b3e1c25d-d2e8-4c5c-a8a3-f2e6ad9d0d61', 'dcee7d21-7d6d-450c-87b1-39789cc63ceb', 30),
('5a1d7e11-5d62-4d2f-9f6b-c4e4c5c6a84f', '273937a9-ab4f-4d05-bccc-34062e5861a6', 10);
58 changes: 58 additions & 0 deletions infra/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@

# Welcome to your CDK Python project!

This is a blank project for CDK development with Python.

The `cdk.json` file tells the CDK Toolkit how to execute your app.

This project is set up like a standard Python project. The initialization
process also creates a virtualenv within this project, stored under the `.venv`
directory. To create the virtualenv it assumes that there is a `python3`
(or `python` for Windows) executable in your path with access to the `venv`
package. If for any reason the automatic creation of the virtualenv fails,
you can create the virtualenv manually.

To manually create a virtualenv on MacOS and Linux:

```
$ python3 -m venv .venv
```

After the init process completes and the virtualenv is created, you can use the following
step to activate your virtualenv.

```
$ source .venv/bin/activate
```

If you are a Windows platform, you would activate the virtualenv like this:

```
% .venv\Scripts\activate.bat
```

Once the virtualenv is activated, you can install the required dependencies.

```
$ pip install -r requirements.txt
```

At this point you can now synthesize the CloudFormation template for this code.

```
$ cdk synth
```

To add additional dependencies, for example other CDK libraries, just add
them to your `setup.py` file and rerun the `pip install -r requirements.txt`
command.

## Useful commands

* `cdk ls` list all stacks in the app
* `cdk synth` emits the synthesized CloudFormation template
* `cdk deploy` deploy this stack to your default AWS account/region
* `cdk diff` compare deployed stack with current state
* `cdk docs` open CDK documentation

Enjoy!
53 changes: 53 additions & 0 deletions infra/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
import os

import aws_cdk as cdk

from infra.api_nest_stack import ApiNestStack
from infra.rds_stack import RdsStack
from infra.vpc_stack import VpcStack

# 0. Set environment variables

env_cdk = {
"account": "730335652080",
"region": "eu-north-1",
}

env_app = {
"AWS_POSTGRES_DB_USER": os.getenv("AWS_POSTGRES_DB_USER"),
"AWS_POSTGRES_DB_HOST": os.getenv("AWS_POSTGRES_DB_HOST"),
"AWS_POSTGRES_DB_NAME": os.getenv("AWS_POSTGRES_DB_NAME"),
"AWS_POSTGRES_DB_PASSWORD": os.getenv("AWS_POSTGRES_DB_PASSWORD"),
"AWS_POSTGRES_DB_PORT": os.getenv("AWS_POSTGRES_DB_PORT"),
}

# 1. Init cdk app

app = cdk.App()

# # 2. Create VPC stack

# vpc_stack = VpcStack(app, "VpcStack", env=env)

# # 3. Create RDS stack and pass the VPC

# RdsStack(
# app,
# "RdsStack",
# vpc=vpc_stack.vpc,
# env=env,
# )

# 4. Create API NestJS wrapper lambda stack

ApiNestStack(
app,
"ApiNestStack",
env_app=env_app,
env=env_cdk,
)

# 5. Generate AWS CloudFormation template

app.synth()
7 changes: 7 additions & 0 deletions infra/cdk.context.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"availability-zones:account=730335652080:region=eu-north-1": [
"eu-north-1a",
"eu-north-1b",
"eu-north-1c"
]
}
70 changes: 70 additions & 0 deletions infra/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
{
"app": "python3 app.py",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"requirements*.txt",
"source.bat",
"**/__init__.py",
"**/__pycache__",
"tests"
]
},
"context": {
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/core:checkSecretUsage": true,
"@aws-cdk/core:target-partitions": [
"aws",
"aws-cn"
],
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
"@aws-cdk/aws-iam:minimizePolicies": true,
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
"@aws-cdk/core:enablePartitionLiterals": true,
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
"@aws-cdk/aws-iam:standardizedServicePrincipals": true,
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
"@aws-cdk/aws-route53-patters:useCertificate": true,
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
"@aws-cdk/aws-redshift:columnId": true,
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
"@aws-cdk/aws-kms:aliasNameRef": true,
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true,
"@aws-cdk/aws-eks:nodegroupNameAttribute": true,
"@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true,
"@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true,
"@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false
}
}
Empty file added infra/infra/__init__.py
Empty file.
60 changes: 60 additions & 0 deletions infra/infra/api_nest_stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import logging
from aws_cdk import (
aws_lambda as _lambda,
aws_apigateway as apigateway,
Stack,
)
from constructs import Construct

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ApiNestStack(Stack):

def __init__(self, scope: Construct, construct_id: str, env_app: dict, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

try:

nestHandler = _lambda.Function(
self,
"ApiNestHandlerFunction",
runtime=_lambda.Runtime.NODEJS_18_X,
code=_lambda.Code.from_asset("../dist"),
handler="main.handler",
environment=env_app,
)

api = apigateway.RestApi(
self,
id="CartAPINestJS",
rest_api_name="Cart API NestJS",
deploy=True,
# default_method_options={"api_key_required": True},
)

api.root.add_proxy(
default_integration=apigateway.LambdaIntegration(
nestHandler, proxy=True
)
)

# plan = api.add_usage_plan("UsagePlan",
# name="UsagePlanEasy",
# api_stages=[
# apigateway.StageOptions(stage_name=api.deployment_stage.stage_name)
# ],
# throttle=apigateway.ThrottleSettings(
# rate_limit=10,
# burst_limit=2
# )
# )

# api_key = api.add_api_key("TestApiKey")

# plan.add_api_key(api_key)

logger.info("ApiNestStack created successfully")

except Exception as err:
logger.error(f"Error in ApiNestStack: {err}")
36 changes: 36 additions & 0 deletions infra/infra/rds_stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import logging
from aws_cdk import (
aws_rds as rds,
Stack,
aws_ec2 as ec2,
)
from constructs import Construct

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class RdsStack(Stack):
def __init__(self, scope: Construct, id: str, vpc, **kwargs) -> None:
super().__init__(scope, id, **kwargs)

try:
rds.DatabaseInstance(
self,
"ShopPostgresDB",
engine=rds.DatabaseInstanceEngine.postgres(
version=rds.PostgresEngineVersion.VER_16_3
),
instance_type=ec2.InstanceType.of(
ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO # db.t2.micro is eligible for the AWS Free Tier
),
vpc=vpc, # Ensure `my_vpc` is defined or passed correctly
database_name="shop_cart_db",
allocated_storage=20, # Set to 20GB to fit within Free Tier
max_allocated_storage=20, # Optional: Prevents autoscaling of storage and incurring costs
)

logger.info("RdsStack created successfully")

except Exception as err:
logger.error(f"Error in RdsStack: {err}")

Loading