-
-
Save Rafat97/ce9ff2bc52819a3213baebb750ce0d0d to your computer and use it in GitHub Desktop.
π£ AWS EC2 Amazon Linux 2 init commend π£
aws configure --profile <profile_name>
aws configure list
aws route53 list-hosted-zones --starting-token Z2BCXXAD85TQPE
aws route53 list-resource-record-sets --hosted-zone-id Z2BCXXAD85TQPE
sam init
1. sam deploy -g
2. sam deploy
sam local invoke -e [event.json] [function name]
my sam template-
https://github.com/Rafat97/my-works/blob/master/learn/AWSLearn/sam.zip
const aws = require("aws-sdk");
const db = require("mysql2");
const { Sequelize, Model, DataTypes } = require("sequelize");
const Joi = require("joi");
let schema = Joi.object({
name: Joi.string().required(),
email: Joi.string().email().required(),
// age: Joi.number().required().positive().integer(),
});
const sequelize = new Sequelize(
"mysql://username:password@<host>:3306/new_schema"
);
function CustomException(message, code, ...others) {
const error = new Error(message);
error.code = code;
error.others = [...others];
return error;
}
const User = sequelize.define(
"User",
{
// Model attributes are defined here
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
// allowNull defaults to true
},
},
{
tableName: "test_db",
}
);
exports.handler = async (event, context, callback) => {
// context.callbackWaitsForEmptyEventLoop = false;
let response = {};
await sequelize.authenticate();
console.log("Connection has been established successfully.");
try {
console.log("received:", JSON.stringify(event));
const {
headers,
httpMethod,
path,
pathParameters,
queryStringParameters,
body,
} = event;
const content_type = headers["content-type"] || headers["Content-Type"];
if (content_type !== "application/json") {
throw new CustomException(
`content-type header must be application/json`,
403,
event
);
}
if (httpMethod === "GET") {
const users = await User.findAll();
console.log(users[0].id);
response = {
statusCode: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
},
body: JSON.stringify(users),
};
} else if (httpMethod === "POST") {
const data = JSON.parse(body);
console.log(data);
const result = schema.validate(data);
const { value, error } = result;
const valid = error == null;
if (!valid) {
const { details } = error;
console.log(error);
const message = details.map((i) => i.message).join(",");
console.log(details);
throw new CustomException(message, 422, details);
} else if (httpMethod === "PUT") {
const data = JSON.parse(body);
}
const { name, email } = { ...data };
const jane = await User.create({ name: name, email: email });
console.log(jane);
console.log(name, email);
response = {
statusCode: 201,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
},
body: JSON.stringify(event),
};
} else if (httpMethod === "PUT") {
const { id } = { ...pathParameters };
const data = JSON.parse(body);
const { name, email } = { ...data };
console.log(data);
const userUpdate = await User.update(
{ name: name },
{
where: {
id: id,
},
}
);
let message = {};
if (userUpdate[0]) {
message = {
message: "Data updated successfully",
};
} else {
message = {
message: "No data found",
};
}
console.log(userUpdate);
response = {
statusCode: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
},
body: JSON.stringify(message),
};
} else if (httpMethod === "DELETE") {
const { id } = { ...pathParameters };
const userDelete = await User.destroy({
where: {
id: id,
},
});
let message = {};
if (userDelete) {
message = {
message: "Data delete successfully",
};
} else {
message = {
message: "No data found",
};
}
response = {
statusCode: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
},
body: JSON.stringify(message),
};
} else {
throw new Error(`${httpMethod} method not found`);
}
} catch (e) {
console.log(e);
console.log(typeof e);
if (e.name === "SequelizeUniqueConstraintError") {
e.code = 403;
e.message = "Unique Constraint Error";
e.others = e.errors;
}
let err = {
errorMessage: e.message,
others: e.others,
};
response = {
statusCode: e.code,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
},
body: JSON.stringify(err),
};
}
return response;
};
https://github.com/aws/aws-sam-cli-app-templates/tree/master/nodejs14.x
AWSTemplateFormatVersion: 2010-09-09
Description: >-
test-sam-app
Transform:
- AWS::Serverless-2016-10-31
Resources:
helloFromLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Handler: src/handlers/hello-from-lambda.helloFromLambdaHandler
Runtime: nodejs14.x
MemorySize: 128
Timeout: 100
Description: A Lambda function that returns a static string.
Policies:
# Give Lambda basic execution Permission to the helloFromLambda
- AWSLambdaBasicExecutionRole
testSamAppApiWork:
Type: AWS::Serverless::Function
Properties:
Handler: src/handlers/test-lambda-put.apiPutRequest
Runtime: nodejs14.x
MemorySize: 128
Timeout: 100
Description: A Lambda function that returns a static string.
Policies:
# Give Lambda basic execution Permission to the helloFromLambda
- AWSLambdaBasicExecutionRole
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
hello-world-sample
Sample SAM Template for hello-world-sample
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs14.x
Environment:
Variables:
DATABASE_STRING: "mysql://username:password@<host>:3306/new_schema"
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
HelloWorldFunctionPOST:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs14.x
Environment:
Variables:
DATABASE_STRING: "mysql://username:password@<host>:3306/new_schema"
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: POST
HelloWorldFunctionPUT:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs14.x
Environment:
Variables:
DATABASE_STRING: "mysql://username:password@<host>:3306/new_schema"
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: PUT
HelloWorldFunctionDELETE:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs14.x
Environment:
Variables:
DATABASE_STRING: "mysql://username:password@<host>:3306/new_schema"
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: DELETE
TestWorldFunctionGET:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs14.x
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /test
Method: GET
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
HelloWorldFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt HelloWorldFunctionRole.Arn
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
UploadBucket: | |
Type: AWS::S3::Bucket | |
# DeletionPolicy: Retain | Delete | |
Properties: | |
BucketName: bucket-name | |
CorsConfiguration: | |
CorsRules: | |
- AllowedHeaders: | |
- "*" | |
AllowedMethods: | |
- GET | |
- PUT | |
- POST | |
AllowedOrigins: | |
- "*" | |
ExposedHeaders: | |
- Date | |
Id: S3OutputVideoCORSRuleId1 | |
MaxAge: 3600 | |
VersioningConfiguration: | |
Status: Enabled | |
BucketEncryption: | |
ServerSideEncryptionConfiguration: | |
- ServerSideEncryptionByDefault: | |
SSEAlgorithm: AES256 | |
--- | |
#!/bin/bash
yum update -y
amazon-linux-extras install -y epel
yum -y install stress htop telnet
amazon-linux-extras install -y nginx1
systemctl start nginx
systemctl enable nginx
yum install -y certbot
yum install -y python-certbot-nginx
sudo yum install -y git
amazon-linux-extras install docker
service docker start
usermod -a -G docker ec2-user
chkconfig docker on
sudo curl -L https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
reboot
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html
[ec2-user ~]$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
xvda 202:0 0 8G 0 disk
-xvda1 202:1 0 8G 0 part /
xvdf 202:80 0 10G 0 disk
[ec2-user ~]$ sudo file -s /dev/xvdf /dev/xvdf: data
[ec2-user ~]$ sudo file -s /dev/xvda1 /dev/xvda1: SGI XFS filesystem data (blksz 4096, inosz 512, v2 dirs)
[ec2-user ~]$ sudo mkfs -t xfs /dev/xvdf
[ec2-user ~]$ sudo yum install xfsprogs
[ec2-user ~]$ sudo mkdir /data
[ec2-user ~]$ sudo mount /dev/xvdf /data
#!/bin/bash
sudo yum update -y
sudo yum install -y docker
sudo service docker start
sudo usermod -a -G docker ec2-user
docker run -d -v redisinsight:/db -p 80:8001 redislabs/redisinsight:latest
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment