---
# System prepended metadata

title: Những notes ngắn khi làm việc với AWS

---

# Những notes ngắn khi làm việc với AWS

## ssh vao ec2

```
ssh -i /path/my-key-pair.pem ec2-user@ec2-.....compute-1.amazonaws.com
```

[Ref](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html)

## API Gateway

#### private API - VPC endpoint configure

```yaml:template.yaml
Globals:
  Api:
    EndpointConfiguration: PRIVATE
...
  FooBarFunction:
    Type: 'AWS::Serverless::Function'
    Properties:
      CodeUri: foo-bar/
      Handler: app.handler
      Runtime: nodejs10.x
      Timeout: 10
      Events:
        Foobar:
          Type: Api
          Properties:
            Path: /foo/bar
            Method: put
            Auth:
              ResourcePolicy:
                CustomStatements:
                  Effect: Allow
                  Action: 'execute-api:Invoke'
                  Resource:
                    - 'execute-api:/*/*/*'
                  Principal: '*'
                  Condition:
                    ForAnyValue:StringEquals:
                      aws:sourceVpce: !FindInMap [ Configs, !Ref Stage, SourceVpce ]
```

## Lambda Function

#### CORS problem

Cách đơn giản là trong response khi trả về, gán thêm thông số sau trong headers.

```javascript:app.js
const response = {
                    'statusCode': 200,
                    headers: {
                        "Access-Control-Allow-Origin": "REQUEST_DOMAIN",
                    },
                    'body': JSON.stringify({
                        ...
                    })
                }
``` 

#### Khi làm việc với S3 / SecretsManager
Cần phải thêm S3Readpolicy vào phần Policies

```yaml:template.yaml
...
      Policies:
        - SecretsManagerReadWrite
        - S3ReadPolicy:
            BucketName: !FindInMap [ Configs, !Ref Stage, ShopInfoBucket ]
```

## S3

### aws cli s3

```bash
aws s3 sync . s3://bucket_name/
```

## Dynamo

Dùng dynamodb local để phát triển giúp tiết kiệm chi phí
Cài đặt thông qua docker

```bash
$ docker pull amazon/dynamodb-local
$ docker images
```

Khởi động

```bash
$ docker run -d -p 8000:8000 amazon/dynamodb-local -jar DynamoDBLocal.jar -inMemory -sharedDb
$ docker ps --no-trunc
```

Dùng GUI để sử dụng cho dễ

```bash
$ npm install dynamodb-admin -g
$ export DYNAMO_ENDPOINT=http://localhost:8000
$ dynamodb-admin
```
Truy cập GUI thông qua: http://localhost:8001

### lam viec voi local dynamo thong qua aws cli

create table
```bash
aws --endpoint-url=http://localhost:4569 dynamodb create-table \
    --table-name item-extras \
    --attribute-definitions AttributeName=shop_code,AttributeType=S AttributeName=item_code,AttributeType=S \
    --key-schema AttributeName=shop_code,KeyType=HASH AttributeName=item_code,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=10
```

## Cloudfront


## Nodejs local dev

### local web server (không cần nginx hay apache)

```bash
npm install -g local-web-server
cd project/dist/
ws --rewrite '/api/(.*) -> http://127.0.0.1:8080/api/$1'
↓
Listening on http://ip-10-3-4-80.ap-northeast-1.compute.internal:8000, http://127.0.0.1:8000, http://10.3.4.80:8000
```

[local-web-server: reference](https://www.npmjs.com/package/local-web-server)

### sam local start-api environmet variables

#### 1. Dùng --env-vars xyz.json

```bash
sam local start-api --env-vars ./env-var-xyz.json
```

```json:env-var-xyz.json
{
  "Parameters": {
    "KEY": "VALUE"
  }
}
```

chú ý, KEY ở đây là biến được định nghĩa trong file template.yaml.
Có thể định nghĩa trong gloabl section hoặc trong các function section
Khi sử dụng, thường được gọi dưới dạng `process.env.KEY`

#### 2. Dùng .env file

Trong trường hợp các biến không định nghĩa trong file template.yaml mà muốn dùng giá trị dành cho môi trường local, ta có thể tạo file .env và để file này trong thư mục được build của mỗi lambda function

```bash:.env
KEY=VALUE
```
Khi sử dụng, thường được gọi dưới dạng `process.env.KEY`


## localstack

[Link](https://github.com/localstack/localstack)


### Install

```bash
git clone https://github.com/atlassian/localstack.git

cd localstack

TMPDIR=/private$TMPDIR \
DATA_DIR=/tmp/localstack/data \
SERVICES=apigateway,kinesis,dynamodb,dynamodbstreams,elasticsearch,s3,\
lambda,sns,sqs,redshift,es,ses,route53,cloudformation,cloudwatch,\
ssm,secretsmanager,stepfunctions,logs,sts,iam,ec2 \
docker-compose up -d
```
[Other install way](https://qiita.com/Yuki_BB3/items/106a88c6f27690f922cc)

```
docker pull localstack/localstack
docker run -it -p 4567-4584:4567-4584 -p 8080:8080 localstack/localstack
```

### service/port

```bash
API Gateway at http://localhost:4567
Kinesis at http://localhost:4568
DynamoDB at http://localhost:4569
DynamoDB Streams at http://localhost:4570
Elasticsearch at http://localhost:4571
S3 at http://localhost:4572
Firehose at http://localhost:4573
Lambda at http://localhost:4574
SNS at http://localhost:4575
SQS at http://localhost:4576
Redshift at http://localhost:4577
ES (Elasticsearch Service) at http://localhost:4578
SES at http://localhost:4579
Route53 at http://localhost:4580
CloudFormation at http://localhost:4581
CloudWatch at http://localhost:4582
SSM at http://localhost:4583
SecretsManager at http://localhost:4584
StepFunctions at http://localhost:4585
CloudWatch Logs at http://localhost:4586
EventBridge (CloudWatch Events) at http://localhost:4587
STS at http://localhost:4592
IAM at http://localhost:4593
EC2 at http://localhost:4597
```

### aws s3 cli

```bash
aws --endpoint-url=http://localhost:4572 s3 ls
aws --endpoint-url=http://localhost:4572 s3 ls s3://bucket_name --recursive
aws --endpoint-url=http://localhost:4572 s3 mb s3://bucket_name
aws --endpoint-url=http://localhost:4572 s3 cp s3://bucket_name/file {TO_DIR}
```

### aws secretmanager cli

```bash
aws --endpoint-url=http://localhost:4584 secretsmanager create-secret --name {SECRET_ID}/{STAGE} --secret-string file://data/secret_data.json
aws --endpoint-url=http://localhost:4584 secretsmanager list-secrets
aws --endpoint-url=http://localhost:4584 secretsmanager get-secret-value --secret-id {SECRET_ID}/{STAGE}
aws --endpoint-url=http://localhost:4584 secretsmanager put-secret-value --secret-id {SECRET_ID}/{STAGE}  --secret-string file://secret_data.json
```

### aws sqs cli
- Get message from sqs
aws --endpoint-url=http://localhost:4576 sqs receive-message --queue-url http://localhost:4576/000000000000/SQS_QUEUE_NAME.fifo --max-number-of-messages 10

## Docker

```
# List image/container:
docker image/container ls

# Delete image/container:
docker image/container rm <tên image/container >

# Delete all image hiện có:
docker image rm $(docker images –a –q)

# List all container hiện có:
docker ps –a

# Stop a container cụ thể:
docker stop <tên container>

# Run container từ image và thay đổi tên container:
docker run –name <tên container> <tên image>

# Stop all container:
docker stop $(docker ps –a –q)

# Delete all container hiện có:
docker rm $(docker ps –a –q)

# Show log a container:
docker logs <tên container>

# Build một image từ container:
docker build -t <tên container> .

# Tạo một container chạy ngầm:
docker run -d <tên image>

# Tải một image trên docker hub:
docker pull <tên image>

# Start một container:
docker start <tên container>

# xoa het nhung container dang stop
docker container prune 

```







