Skip to content

Commit

Permalink
feat: add cdk script for ec2 instance and updated setup script
Browse files Browse the repository at this point in the history
  • Loading branch information
jjmchew committed Aug 8, 2024
1 parent af43d71 commit 1d97a93
Show file tree
Hide file tree
Showing 14 changed files with 5,040 additions and 11 deletions.
8 changes: 8 additions & 0 deletions cdk/ec22/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
*.js
!jest.config.js
*.d.ts
node_modules

# CDK asset staging directory
.cdk.staging
cdk.out
6 changes: 6 additions & 0 deletions cdk/ec22/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*.ts
!*.d.ts

# CDK asset staging directory
.cdk.staging
cdk.out
14 changes: 14 additions & 0 deletions cdk/ec22/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Welcome to your CDK TypeScript project

This is a blank project for CDK development with TypeScript.

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

## Useful commands

* `npm run build` compile typescript to js
* `npm run watch` watch for changes and compile
* `npm run test` perform the jest unit tests
* `npx cdk deploy` deploy this stack to your default AWS account/region
* `npx cdk diff` compare deployed stack with current state
* `npx cdk synth` emits the synthesized CloudFormation template
21 changes: 21 additions & 0 deletions cdk/ec22/bin/ec22.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { Ec22Stack } from '../lib/ec22-stack';

const app = new cdk.App();
new Ec22Stack(app, 'Ec22Stack', {
/* If you don't specify 'env', this stack will be environment-agnostic.
* Account/Region-dependent features and context lookups will not work,
* but a single synthesized template can be deployed anywhere. */

/* Uncomment the next line to specialize this stack for the AWS Account
* and Region that are implied by the current CLI configuration. */
// env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },

/* Uncomment the next line if you know exactly what Account and Region you
* want to deploy the stack to. */
// env: { account: '123456789012', region: 'us-east-1' },

/* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */
});
1 change: 1 addition & 0 deletions cdk/ec22/cdk.context.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
71 changes: 71 additions & 0 deletions cdk/ec22/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
{
"app": "npx ts-node --prefer-ts-exts bin/ec22.ts",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"**/*.d.ts",
"**/*.js",
"tsconfig.json",
"package*.json",
"yarn.lock",
"node_modules",
"test"
]
},
"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-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
}
}
8 changes: 8 additions & 0 deletions cdk/ec22/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
testEnvironment: 'node',
roots: ['<rootDir>/test'],
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.tsx?$': 'ts-jest'
}
};
11 changes: 11 additions & 0 deletions cdk/ec22/lib/cdk.context.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"availability-zones:account=891377036664:region=us-east-1": [
"us-east-1a",
"us-east-1b",
"us-east-1c",
"us-east-1d",
"us-east-1e",
"us-east-1f"
],
"ami:account=891377036664:filters.image-type.0=machine:filters.name.0=ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*:filters.state.0=available:owners.0=099720109477:region=us-east-1": "ami-03e31863b8e1f70a5"
}
90 changes: 90 additions & 0 deletions cdk/ec22/lib/ec22-stack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
// import * as sqs from 'aws-cdk-lib/aws-sqs';

import * as ec2 from 'aws-cdk-lib/aws-ec2';

// from gpt
export class Ec22Stack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);

// Create a VPC (Virtual Private Cloud)
const vpc = new ec2.Vpc(this, 'CDKVpc', {
maxAzs: 2, // Default is all AZs in the region
});

const securityGroup = new ec2.SecurityGroup(this, 'CDKSecurityGroup', {
vpc,
allowAllOutbound: true,
});

securityGroup.addIngressRule(
ec2.Peer.anyIpv4(),
ec2.Port.tcp(22), // Allow SSH access
'Allow SSH access from anywhere',
);

securityGroup.addIngressRule(
ec2.Peer.anyIpv4(),
ec2.Port.tcp(80), // Allow HTTP access
'Allow HTTP access from anywhere',
);

const ubuntuAmi = ec2.MachineImage.lookup({
name: 'ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*',
owners: ['099720109477'], // Canonical's AWS account ID
});

const userData = ec2.UserData.forLinux();
userData.addCommands(
'sudo apt update -y',
'sudo apt upgrade -y',
'git clone https://github.com/2405-team3/db.git',
'curl https://pyenv.run | bash',
'export PYENV_ROOT="$HOME/.pyenv',
'[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"',
'eval "$(pyenv init -)"',
// 'sudo apt install build-essential libssl-dev zlib1g-dev \
// libbz2-dev libreadline-dev libsqlite3-dev curl \
// libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev -y',
)

// Define an Amazon Machine Image (AMI)
// const ami = new ec2.AmazonLinuxImage();

const keyPair = ec2.KeyPair.fromKeyPairAttributes(this, 'KeyPair', {
keyPairName: 'aws1',
type: ec2.KeyPairType.RSA,
})

// Create an EC2 instance
const instance = new ec2.Instance(this, 'CDKEC2-1', {
vpc,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO),
machineImage: ubuntuAmi, securityGroup,
keyPair: keyPair,
userData,
vpcSubnets: {
subnetType: ec2.SubnetType.PUBLIC, // Ensure the instance is deployed in a public subnet
},
associatePublicIpAddress: true, // Ensure the instance gets a public IP address
});

// output the instance public DNS
new cdk.CfnOutput(this, 'InstancePublicDNS', {
value: instance.instancePublicDnsName,
});
}
}

const app = new cdk.App();
new Ec22Stack(app, 'CDKInstance2', {
env: {
account: '891377036664',
region: 'us-east-1'
}
});
app.synth();


Loading

0 comments on commit 1d97a93

Please sign in to comment.