0%

AWS Lambda LAB2

本次Lambda LAB2 練習 搭配 AWS API Gateway, 主要是Clients 送出一個 request 由AWS API Gateway 代理觸發對應的 Lambda function,Lambda 取得Client IP ,及藉由GeoIP 查找IP 的 Country_code,最後運算完成結果丟回給 API Gateway,最終API Gateway 回應結果給 Clients。如下示意圖:

圖片來源: API Gateway 入門

封裝Pyhton code

使用zip 檔封裝Python code

有個目錄名為 myip , 有以下檔案:

1
2
3
myip
├── GeoLite2-Country.mmdb
└── lambda_function.py
  • lambda_function.py:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    import json
    from geoip import open_database

    GeoipDataBase="GeoLite2-Country.mmdb"
    dbip=open_database(GeoipDataBase)
    def getcountry(ip):
    chkip=getattr(dbip.lookup(ip),'country',None)
    if chkip:
    return chkip
    else:
    return 'NO_Country'
    dbip.close()

    def lambda_handler(event, context):
    # TODO implement
    print("FirstProcess: get Header")
    message={}
    message['xForwardfor']=event['headers']['x-forwarded-for']
    message['myIP']=event['requestContext']['http']['sourceIp']
    message['myCountry']=getcountry(message['myIP'])

    return {
    'statusCode': 200,
    'body': json.dumps(message,sort_keys=True, indent=4, separators=(',', ': '))
    }
  • GeoLite2-Country.mmdb : 可以到 Maxmind 下載 mmdb

lambda_function.py 有引用 Python 第三方模組 geoip , 此模組套件名稱為 python-geoip-python3,並安裝到新 package 目錄

,將package 封裝為zip 壓縮檔 , 檔名為: deploy_lambda_myip.zip

1
2
3
4
cd myip
pip3 install --target ./package python-geoip-python3
cd package
zip -r ../deploy_lambda_myip.zip .

將 原先myip目錄底下兩個檔案 GeoLite2-Country.mmdb , lambda_function.py 封裝到 deploy_lambda_myip.zip

1
2
cd myip
zip -g deploy_lambda_myip.zip GeoLite2-Country.mmdb lambda_function.py

上傳 deploy_lambda_myip.zip

  • 建立Lambda 名為 lambdaLAB2

  • Runtime 選擇 Python3.9

  • CPU 架構選擇 : arm64 (封裝Python code 於 MacBook Air M1下執行的 )

  • 於右邊點選 上傳於 zip

  • 上傳成功後,於左邊可以看到幾個檔案(geoip.py, GeoLite2-Country.mmdb, lambda_function.py)

建立 API Gateway

AWS Lambda 是屬於事件式 Function運算資源, 需要有一個觸發事件去啟動 Lambda。這個 LambdaLAB2 主要呈現像 Web App一樣; Client 端 送出一個 request 事件請求給 API Gateway, API Gateway再依據此事件去調用 Lambda, Lambda 運算完的結果傳給 API Gateway,最後response 給 Client。

  • 於aws console management 搜尋欄 打上 key word: api , 選擇 API Gateway

  • 開始建立API: 選擇 HTTP API 類型

  • 新增整合: 選擇 Lambda

    • AWS 區域: us-east-1 (lambdaLab2 是建立在此區域)

    • Lambda 函數 : 自動會帶出剛建立Lambda ID 尾碼是lambdaLAB2

  • 設定路由 : 方法 get (request) , 資源路徑: / , 整合目標: lambdaLAB (API Gateway 調用目標)

  • 生成一個 叫用 url

  • 於Client 端 Browser 測試 叫用 url

參考資料:

AWS_Lambda LAB1 By Python

Lambda 是AWS 推出 Serverless (無伺服器)服務。與EC2 一樣同屬於運算部分,若要建立一個Application Server ,在EC2上需要部署服務器相關設定及code 等,資源不夠時也要自個設定擴展EC2運算資源或是設定 ELB 將流量負載均衡等;AWS Lambda 與 EC2不同,只需要將運算的 Application code 上傳到AWS Lambda,其他服務設定及資源擴展等等都是由 AWS 做好。

建立 AWS Lambda

  • 建立名為: lambdaLAB1

  • 選擇application code 運算平台(runtime ,中文翻譯不好稱為執行時間) : Python 3.9

  • 其他項目預設即可: 預設上會給予將 Lambda 運算Log 上傳到 CloudWatch 的權利

  • 上傳 code: 隨即系統開啟簡易編輯器,附上Python 範例程式, 檔名為 : lambda_function , 這邊小幅修改如下,再按Deploy

  • Function code Handler: lambda_function.lambda_handler

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import json
    def lambda_handler(event, context):
    print('First... Post Event: {}'.format(event))
    print('Get Key2: {}'.format(event["key2"]))
    print('Get Key3: {}'.format(event["key3"]))
    print(context)
    # TODO implement
    return {
    'statusCode': 200,
    'body': json.dumps('Hello from Lambda! {}'.format(event["key1"]))
    }

    建立 Test

    在AWS Lambda 主控台介面有一個 Test Tool ,簡單對 Function Code 使用 post 方法輸入一個 json 格式的資料, 來驗證上述的Function Code 是否合乎預期。上述 Function Code 第一個參數 event object, 資料是JSON 格式, 外部輸入的資料都由event object 所接收。

  • Test event 名為: TestPost1

  • Event JSON

    1
    2
    3
    4
    5
    {
    "key1": "AWS",
    "key2": "GCP",
    "key3": "Azure"
    }
  • 其他預設即可



查看AWS Lambda 運算結果

  • 於Lambda 主控台看到 response結果

  • AWS CloudWatch 看到 response結果

參考資料

AWS_VPC-LAB3 By Terraform

本篇與 AWS_VPC-LAB2_By-Terraform內容大致相同,主要差異在這邊的Private Subnet 1可以透過 NAT 連上Internet 如下示意圖

以下步驟延續此篇的內容AWS_VPC-LAB2_By-Terraform,只是增加 NAT 元件及修正 Private Subnet路由繞送的部分。

  • 建立NAT (nat.tf)
  • 修正Private Subnet路由 (route.tf)
  • 修正顯示訊息 (myDatasource.tf)
  • 執行 Terraform
  • 測試
  • 清理Lab所建立的所有元件

開始部署之前

本篇不是Terraform 基礎教學,若不清楚Terraform可以看參考資料。

  • 安裝Terraform 很簡單可以看官網-Install Terraform

  • 使用AWS API之前都需要先到IAM 設定申請一組keySECRET_ACCESS_KEY

    因為只是LAB,為了方便執行通常都會將申請好的key放置在shell script

    myauth_key.sh

    1
    2
    3
    #!/bin/bash
    export AWS_ACCESS_KEY_ID='your key id'
    export AWS_SECRET_ACCESS_KEY='your secret key'

    在執行任何AWS API或Terraform之前先執行 myauth_key.sh

    1
    source ./myhome-auth_key.sh
  • 完整Terraform Hcl code 於 88gocode/AWS-LAB-Terraform

    1
    2
    3
    git clone https://github.com/88gocode/AWS-LAB-Terraform.git
    cd AWS-LAB-Terraform
    git checkout lab3

建立NAT (nat.tf)

NAT 元件須建立在 Public Subnet , 另外創建 EIP, 給予 NAT 出去有一個Public IP (nat_gateway_IP)

  • Subnet : aws_subnet.az1-public1-subnet.id
  • NAT 名稱: nat_gw_lab0
  • EIP: aws_eip.nat_eip_lab0.id

nat.tf

1
2
3
4
5
6
7
8
9
10
11
12
resource "aws_eip" "nat_eip_lab0" {
vpc = true
}

resource "aws_nat_gateway" "gw" {
allocation_id = aws_eip.nat_eip_lab0.id
subnet_id = aws_subnet.az1-public1-subnet.id
depends_on = [aws_internet_gateway.main-igw]
tags = {
Name = "nat_gw_lab0"
}
}

修正Private Subnet路由 (route.tf)

增加一筆預設路由往 NAT 走

route.tf , 修正 Private Subnet 部分

1
2
3
4
5
6
7
8
9
10
11
12
# Create Private  Route Table
resource "aws_route_table" "main-private-rt" {
vpc_id = aws_vpc.main.id

route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_nat_gateway.gw.id
}
tags = {
Name = "AZ1-Private-Rtable"
}
}

修正顯示訊息 (myDatasource.tf)

Terraform 部署完後, 增加顯示 nat_gateway_IP

myDatasource.tf

1
2
3
4
output "nat_gateway_IP" {
value = aws_nat_gateway.gw.public_ip
description = "Public IP for Nat Gateway"
}

執行 Terraform

第一次執行Terraform,需要初始化先下載對應的Provider (本篇是 AWS),完成後,於所在目錄底下有一個隱藏檔 .terraform

1
terraform init

可以查看剛寫的 terraform 語法是否正確

1
terraform validate

執行測試計畫,可以看所列的參數

1
terraform plan

開始部署

1
terraform apply  -auto-approve

建立好 EC2, 查看分配Private IP,及EC2 Public IP , 及 nat_gateway_IP

測試

  • 透過public ip 使用 ssh 加上 key 的方式連進來, 再連去 Private Subnet 的EC2

    1
    2
    ssh-add  my-test.pem
    ssh -A [email protected]

  • 於AZ1-Private-EC2_1, 測試是否能聯外

清理

AWS 的價值貴於方便與彈性,使用多少算多少錢,因此這個只是個LAB ,不用時記得將他清理刪除。
使用Terraform 只要下以下指令即可清理完成。

1
terraform destroy

參考資料

AWS_VPC-LAB2 By Terraform

本篇使用Terraform 工具重新部署 AWS_VPC-LAB2內容。如下示意圖

以下步驟與 AWS_VPC-LAB2一樣, 只是換成Terraform 工具操作,延續此篇的內容AWS_VPC-LAB1_By-Terraform,本篇只是增加以下步驟,若要完整使用本篇Terraform HCL code 來建構Lab2 ,建議先使用 AWS_VPC-LAB1_By-Terraform建構好Lab1。

  • 建立Private Subnet
  • 建立Routing Table
  • 將Routing Table與Private Subnet建立關聯
  • 建立Security Group
  • 建立EC2
  • 測試
  • 清理Lab所建立的所有元件

開始部署之前

本篇不是Terraform 基礎教學,若不清楚Terraform可以看參考資料。

  • 安裝Terraform 很簡單可以看官網-Install Terraform

  • 使用AWS API之前都需要先到IAM 設定申請一組keySECRET_ACCESS_KEY

    因為只是LAB,為了方便執行通常都會將申請好的key放置在shell script

    myauth_key.sh

    1
    2
    3
    #!/bin/bash
    export AWS_ACCESS_KEY_ID='your key id'
    export AWS_SECRET_ACCESS_KEY='your secret key'

    在執行任何AWS API或Terraform之前先執行 myauth_key.sh

    1
    source ./myhome-auth_key.sh
  • 完整Terraform Hcl code 在此88gocode/AWS-LAB-Terraform

    1
    2
    3
    git clone https://github.com/88gocode/AWS-LAB-Terraform.git
    cd AWS-LAB-Terraform
    git checkout lab2

    先宣告變數

    以下開始是Terraform hcl 語法。此節將VPC , subnet 等需要網段及登入 EC2 需要Key的名稱等參數, 用變數方式載入便於其他資源物件利用。

vars.tf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
variable "AWS_REGION" {
default = "ap-northeast-3"
}

variable "AWS_AZ" {
default = "ap-northeast-3a"
}

variable "vpc_cidr_lab0" {
default = "10.1.0.0/16"
description = "the vpc cidr"
}

variable "public_subnet_cidr_lab0" {
default = "10.1.1.0/24"
description = "The cidr of the public subnet"
}

variable "private_subnet_cidr_lab0" {
default = "10.1.2.0/24"
description = "The cidr of the private subnet"
}

variable "key_name" {
default = "my-test"
}

佈建雲端 IaaS 使用Terraform 好處是它提供多樣Provider : 像是 AWS,GCP,Azure,aliyun,DigitalOcean等等
以下是宣告是使用AWS Provider
provider.tf

1
2
3
4
provider "aws" {
profile = "default"
region = var.AWS_REGION
}

建立Private Subnet

  • 選擇VPC : VPC-LAB1
  • Subnet 名稱: AZ1-Private-Subnet
    • 選定AZ區域: 選擇日本大阪一個AZ(ap-northeast-3a)
    • 分配網段: 10.1.2.0/24

subnet.tf

1
2
3
4
5
6
7
8
9
10
11
# Create Private Subnet
resource "aws_subnet" "az1-private-subnet" {
vpc_id = aws_vpc.main.id
cidr_block = var.private_subnet_cidr_lab0
availability_zone = var.AWS_AZ
map_public_ip_on_launch = "false"
tags = {
Name = "AZ1-Private-Subnet"

}
}

建立Routing Table

route.tf

1
2
3
4
5
6
7
8
9
10
11
12
13
# Create Private  Route Table
resource "aws_route_table" "main-private-rt" {
vpc_id = aws_vpc.main.id
tags = {
Name = "AZ1-Private-Rtable"
}
}

# route associations private (將路由表與Subnet建立關聯)
resource "aws_route_table_association" "main-private-rt-az1" {
subnet_id = aws_subnet.az1-private-subnet.id
route_table_id = aws_route_table.main-private-rt.id
}

建立Security Group(SG)

建立SG 名為 AZ1_Private_sg1,新增兩筆傳入規則

  • 任何來源 10.1.1.0/24 ,tcp port 22 都允許

  • 任何來源 0.0.0.0/0 ,ICMP-IPv4

sg.tf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
resource "aws_security_group" "sg2" {
name = "main_sg2"
vpc_id = aws_vpc.main.id

ingress {
from_port = "22"
to_port = "22"
protocol = "TCP"
cidr_blocks = ["10.1.1.0/24"]

}

ingress {
from_port = "-1"
to_port = "-1"
protocol = "ICMP"
cidr_blocks = ["0.0.0.0/0"]
}

egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}

tags = {
Name = "AZ1_Private_sg1"
}

}

AWS的 SG 是屬於StateFul,都是綁定在ENI(Elastic Network Interface: 網卡)上(相當於Linux Iptable角色);NACL 屬於 Stateless,都是綁定上 Subnet

建立EC2

這邊EC2簡單建立, Tag Name為 AZ1-Private-EC2_1 , Subnet: AZ1-Private-Subnet ,security group: AZ1_Private_sg1,ssh-key: my-test,AMI: 透過data source 獲取AMI ID (可以看上篇 AWS_VPC-LAB1_By-Terraform 獲取AMI的部分),其他預設即可

**ec2.tf **

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# For Private Subnet
resource "aws_instance" "example2" {
ami = data.aws_ami.example.id
instance_type = "t2.micro"
# the VPC subnet
subnet_id = aws_subnet.az1-private-subnet.id
# the security group
vpc_security_group_ids = [aws_security_group.sg2.id]
# the public SSH key
key_name = var.key_name
tags = {
Name = "AZ1-Private-EC2_1"
}
}

執行 Terraform

完整目錄架構如下:

1
2
3
4
5
6
7
8
9
.
├── ec2.tf
├── myDatasource.tf
├── provider.tf
├── route.tf
├── sg.tf
├── subnet.tf
├── vars.tf
└── vpc.tf

第一次執行Terraform,需要初始化先下載對應的Provider (本篇是 AWS),完成後,於所在目錄底下有一個隱藏檔 .terraform

1
terraform init

可以查看剛寫的 terraform 語法是否正確

1
terraform validate

執行測試計畫,可以看所列的參數

1
terraform plan

開始部署

1
terraform apply  -auto-approve

建立好 EC2, 查看分配Private IP,及EC2 Public IP

測試

  • 透過public ip 使用 ssh 加上 key 的方式連進來

    1
    2
    ssh-add  my-test.pem
    ssh -A [email protected]
  • AZ1-Pub-EC2_1 上 ping AZ1-Private-EC2_1 (Public Subnet 是否可以與 Private Subnet 相連接)

  • 測試 於 AZ1-Pub-EC2_1 上 ssh Login AZ1-Private-EC2_1

  • 於AZ1-Private-EC2_1, 測試是否能聯外

清理

AWS 的價值貴於方便與彈性,使用多少算多少錢,因此這個只是個LAB ,不用時記得將他清理刪除。
使用Terraform 只要下以下指令即可清理完成。

1
terraform destroy

參考資料

AWS_VPC-LAB2

本篇延續AWS_VPC-LAB1內容,增加一個Private Subnet(10.1.2.0/24)並在此建立一個EC2,此Subnet無法連接外網,只能與Public Subnet相互連接。如下示意圖

因爲延續AWS_VPC-LAB1內容,以下步驟只列出增加部分。

  • 建立Private Subnet
  • 建立Routing Table
  • 將Routing Table與Private Subnet建立關聯
  • 建立Security Group
  • 建立EC2
  • 測試
  • 清理Lab所建立的所有元件

建立Private Subnet

  • 選擇VPC : VPC-LAB1
  • Subnet 名稱: AZ1-Private-Subnet
    • 選定AZ區域: 選擇日本大阪一個AZ(ap-northeast-3a)
    • 分配網段: 10.1.2.0/24

建立Routing Table

  • Routing Table: AZ1-Private-Rtable

  • 不用在新增路由,已有一筆來源10.1.0.0/16 對local路由即可

  • 將路由表與Subnet建立關聯

    將剛建立的AZ1-Private-Rtable 與 AZ1-Private-Subnet 建立關聯

建立Security Group(SG)

建立SG 名為 AZ1_Private_sg1,新增兩筆傳入規則

  • 任何來源 10.1.1.0/24 ,tcp port 22 都允許

  • 任何來源 0.0.0.0/0 ,ICMP-IPv4

AWS的 SG 是屬於StateFul,都是綁定在ENI(Elastic Network Interface: 網卡)上(相當於Linux Iptable角色);NACL 屬於 Stateless,都是綁定上 Subnet

建立EC2

這邊EC2簡單建立, Tag Name為 AZ1-Private-EC2_1 ,只要選擇 Network: VPC-LAB1 , Subnet: AZ1-Private-Subnet ,Auto-assign-Public-IP: disable ,其他預設即可

如下圖示

增加Tag 名稱,方便日後辨識

選擇剛建立的security group: AZ1_Private_sg1

選擇之前已建立ssh-key,my-test , 主要是安全地連入EC2

建立好 EC2, 分配Private IP

查看Public Sunet 的EC2 Public IP

測試

  • 透過public ip 使用 ssh 加上 key 的方式連進來

    1
    2
    ssh-add  my-test.pem
    ssh -A [email protected]
  • AZ1-Pub-EC2_1 上 ping AZ1-Private-EC2_1 (Public Subnet 是否可以與 Private Subnet 相連接)

  • 測試 於 AZ1-Pub-EC2_1 上 ssh Login AZ1-Private-EC2_1

  • 於AZ1-Private-EC2_1, 測試是否能聯外

清理

AWS 的價值貴於方便與彈性,使用多少算多少錢,因此這個只是個LAB ,不用時記得將他清理刪除。

AWS_VPC-LAB1 By Terraform

本篇主要是利用時下流行基礎架構程式 (IaC)工具: Terraform 重新部署上一篇AWS_VPC-LAB1 內容。以下步驟與上一篇一樣

  • 建立VPC (Virtual Private Cloud)
  • 建立IGW (Internet Gateway)
  • 建立Subnet
  • 建立Routing Table
  • 將路由表與Subnet建立關聯
  • 建立Security Group
  • 獲取AMI
  • 建立EC2
  • 執行 Terraform
  • 測試
  • 清理Lab所建立的所有元件

完整部署後,如下圖所示:

AWS_VPC-Public

開始部署之前

本篇不是Terraform 基礎教學,若不清楚Terraform可以看參考資料。

  • 安裝Terraform 很簡單可以看官網-Install Terraform

  • 使用AWS API之前都需要先到IAM 設定申請一組keySECRET_ACCESS_KEY

    因為只是LAB,為了方便執行通常都會將申請好的key放置在shell script

    myauth_key.sh

    1
    2
    3
    #!/bin/bash
    export AWS_ACCESS_KEY_ID='your key id'
    export AWS_SECRET_ACCESS_KEY='your secret key'

    在執行任何AWS API或Terraform之前先執行 myauth_key.sh

    1
    source ./myhome-auth_key.sh
  • 完整Terraform Hcl code 在此88gocode/AWS-LAB-Terraform

    1
    2
    3
    git clone https://github.com/88gocode/AWS-LAB-Terraform.git
    cd AWS-LAB-Terraform
    git checkout lab1

    先宣告變數

    以下開始是Terraform hcl 語法。此節將VPC , subnet 等需要網段及登入 EC2 需要Key的名稱等參數, 用變數方式載入便於其他資源物件利用。

vars.tf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
variable "AWS_REGION" {
default = "ap-northeast-3"
}
variable "AWS_AZ" {
default = "ap-northeast-3a"
}
variable "vpc_cidr_lab0" {
default = "10.1.0.0/16"
description = "the vpc cidr"
}
variable "public_subnet_cidr_lab0" {
default = "10.1.1.0/24"
description = "The cidr of the public subnet"
}
variable "key_name" {
default = "my-test"
}

佈建雲端 IaaS 使用Terraform 好處是它提供多樣Provider : 像是 AWS,GCP,Azure,aliyun,DigitalOcean等等
以下是宣告是使用AWS Provider
provider.tf

1
2
3
4
provider "aws" {
profile = "default"
region = var.AWS_REGION
}

建立VPC(Virtual Private Cloud)

vpc.tf

1
2
3
4
5
6
7
8
9
10
resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr_lab0
instance_tenancy = "default"
enable_dns_support = true
enable_dns_hostnames = true
enable_classiclink = "false"
tags = {
Name = "main-simple_VPC"
}
}

建立 igw

接續上一節 vpc.tf 內容 , 這邊只是列出建立 igw 的內容

vpc.tf

1
2
3
4
5
6
7
8
# igw
resource "aws_internet_gateway" "main-igw" {
vpc_id = aws_vpc.main.id
tags = {
Name = "main-igw"

}
}

建立Subnet

subnet.tf

1
2
3
4
5
6
7
8
9
10
# Create Publi Subnet
resource "aws_subnet" "az1-public1-subnet" {
vpc_id = aws_vpc.main.id
cidr_block = var.public_subnet_cidr_lab0
availability_zone = var.AWS_AZ
map_public_ip_on_launch = "true"
tags = {
Name = "main-az1-public1-sunet"
}
}

建立Routing Table

route.tf

1
2
3
4
5
6
7
8
9
10
11
# Create Route Table
resource "aws_route_table" "main-public-rt" {
vpc_id = aws_vpc.main.id
tags = {
Name = "main-public-rt"
}
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.main-igw.id
}
}

將路由表與Subnet建立關聯

同樣地,接續上一節 route.tf內容,將已建立的Subnet,Routing Table等物件兩者做個關聯。

route.tf

1
2
3
4
5
# route associations public
resource "aws_route_table_association" "main-public-rt-az1" {
subnet_id = aws_subnet.az1-public1-subnet.id
route_table_id = aws_route_table.main-public-rt.id
}

建立Security Group(SG)

建立SG 名為 AZ1_Pub_sg1,新增兩筆傳入規則

  • 任何來源 0.0.0.0/0 ,tcp port 22 都允許
  • 任何來源 0.0.0.0/0 ,ICMP-IPv4

sg.tf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
resource "aws_security_group" "sg" {
name = "main_sg1"
vpc_id = aws_vpc.main.id

ingress {
from_port = "22"
to_port = "22"
protocol = "TCP"
cidr_blocks = ["0.0.0.0/0"]
}

ingress {
from_port = "-1"
to_port = "-1"
protocol = "ICMP"
cidr_blocks = ["0.0.0.0/0"]
}

egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}

tags = {
Name = "main_sg1"
}
}

AWS的 SG 是屬於StateFul,都是綁定在ENI(Elastic Network Interface: 網卡)上(相當於Linux Iptable角色);NACL 屬於 Stateless,都是綁定上 Subnet

獲取AMI

使用Terraform 核心組件 Data source(若對Terraform 基礎觀念不了解的,可以看參考資料的介紹)來找尋適合 EC2 AMI

以下找尋AMI 條件

  • amazon自己發行的

  • AMI 名稱開頭為 “^amzn.*”

  • VM-type : hvm

  • root-device-type: abs

  • 最近發行的AMI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
data "aws_ami"  "example" {
most_recent = true
owners = ["amazon"]
name_regex = "^amzn.*"

filter {
name = "virtualization-type"
values = ["hvm"]

}
filter {
name = "root-device-type"
values = ["ebs"]
}
}

output "ami_id" {
value = data.aws_ami.example.id
description = "demo for AMI Image ID"
}

output "IP" {
value = aws_instance.example.public_ip
description = "Public IP for demo"
}

建立EC2

這邊EC2簡單建立, 將已建好Subnet ,Security Group (sg) ,及透過data source 獲取AMI ID
ec2.tf

1
2
3
4
5
6
7
8
9
10
11
12
resource "aws_instance" "example" {
ami = data.aws_ami.example.id
instance_type = "t2.micro"
# the VPC subnet
subnet_id = aws_subnet.az1-public1-subnet.id

# the security group
vpc_security_group_ids = [aws_security_group.sg.id]

# the public SSH key
key_name = var.key_name
}

執行 Terraform

完整目錄架構如下:

1
2
3
4
5
6
7
8
9
.
├── ec2.tf
├── myDatasource.tf
├── provider.tf
├── route.tf
├── sg.tf
├── subnet.tf
├── vars.tf
└── vpc.tf

第一次執行Terraform,需要初始化先下載對應的Provider (本篇是 AWS),完成後,於所在目錄底下有一個隱藏檔 .terraform

1
terraform init

可以查看剛寫的 terraform 語法是否正確

1
terraform validate

執行測試計畫,可以看所列的參數

1
terraform plan

開始部署

1
terraform apply  -auto-approve

測試

  • 透過public ip 使用 ssh 加上 key 的方式連進來
  • 在EC2 上聯外

執行完terraform後,會出現以下內容; 如圖

測試 連進 EC2

1
ssh -i my-test.pem [email protected]

清理

AWS 的價值貴於方便與彈性,使用多少算多少錢,因此這個只是個LAB ,不用時記得將他清理刪除。
使用Terraform 只要下以下指令即可清理完成。

1
terraform destroy

參考資料

AWS_VPC-LAB1

本篇主要簡單建立VPC過程:如下圖

  • 建立VPC (Virtual Private Cloud)
  • 建立IGW (Internet Gateway)
  • 建立Routing Table
  • 建立Subnet
  • 將路由表與Subnet建立關聯
  • 建立Security Group
  • 建立EC2並測試
  • 清理Lab所建立的所有元件

AWS_VPC-Public

建立VPC(Virtual Private Cloud)

建立VPC並命名為 VPC-LAB1,並劃分一個大網段 10.1.0.0/16
VPC-LAB1

建立 igw

建立igw 並命名為 igw-Lab,並連線到 VPC-LAB1
igw-Lab0
igw-LAb1
igw-Lab2

建立Routing Table

  • Routing Table: AZ1-Pub-Rtable

  • 編輯路由表, 新增一筆Default Route 到 igw-Lab

    建立Subnet

  • 選擇剛建立VPC : VPC-LAB1

  • Subnet 名稱: AZ1-PubSubnet

    • 選定AZ區域: 選擇日本大阪一個AZ(ap-northeast-3a)
    • 分配網段: 10.1.1.0/24

將路由表與Subnet建立關聯

建立Security Group(SG)

建立SG 名為 AZ1_Pub_sg1,新增兩筆傳入規則

  • 任何來源 0.0.0.0/0 ,tcp port 22 都允許
  • 任何來源 0.0.0.0/0 ,ICMP-IPv4

AWS的 SG 是屬於StateFul,都是綁定在ENI(Elastic Network Interface: 網卡)上(相當於Linux Iptable角色);NACL 屬於 Stateless,都是綁定上 Subnet

建立EC2 及測試

這邊EC2簡單建立, 只是測試VPC所建立的元件是否正確。

  • 透過public ip 使用 ssh 加上 key 的方式連進來
  • 在EC2 上聯外

以下圖示只要選擇 Network: VPC-LAB1 , Subnet: AZ1-PubSubnet ,Auto-assign-Public-IP: Enable (igw 會DHCP分配一個IP),其他預設即可

選擇剛建立的security group: AZ1_Pub_sg1

建立ssh-key , 主要是安全地連入EC2

建立好 EC2, 查看IGW 分配的IP

測試

  • 測試 連進 EC2
    1
    ssh -i vpc-Lab1.pem [email protected]
    連進去後, 測試是否能聯外

清理

AWS 的價值貴於方便與彈性,使用多少算多少錢,因此這個只是個LAB ,不用時記得將他清理刪除。

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment

使用kops建立K8s_Cluster_on_AWS

事前準備

  • 需要有一個AWS帳號

  • 使用IAM 建立一個使用者供 aws_cli 使用

  • 需要一個Domain Name
    目前有一個 tw88go.top 由CloudFlare 代管
    之後使用kops.tw88go.top 將此領域轉給 AWS Route53代管

    1
    kops.tw88go.top
  • 使用AWS route53指定Domain Name

    1
    aws route53 create-hosted-zone --name kops.tw88go.top --caller-reference 1

    會有輸出NameServers,如以下資訊

    1
    2
    3
    4
    5
    6
    7
    8
    "DelegationSet": {
    "NameServers": [
    "ns-753.awsdns-30.net",
    "ns-1665.awsdns-16.co.uk",
    "ns-500.awsdns-62.com",
    "ns-1475.awsdns-56.org"
    ]
    },

    將以上4個DNS Domain bind在 CloudFlare,如下圖:

  • 建立一個S3 bucket
    建立S3 bucket主要作用是儲存 K8s Cluster state。
    當建立K8s Cluster 的設定檔,metadata等都會儲存在bucket

    1
    aws s3 mb s3://clusters.kops.tw88go.top

    開始使用 kops 建立 K8s

  • 下載 kops

    1
    2
    3
    curl -LO https://github.com/kubernetes/kops/releases/download/$(curl -s https://api.github.com/repos/kubernetes/kops/releases/latest | grep tag_name | cut -d '"' -f 4)/kops-linux-amd64
    sudo mv kops-linux-amd64 /usr/local/bin/kops
    chmod a+x /usr/local/bin/kops
  • 建立 K8s
    以下指令只是建立K8s設定檔 ,並上傳指定S3 bucket
    指定KOPS_STATE_STORE環境變數,就不必使用 –state=s3://clusters.kops.tw88go.top

    1
    2
    KOPS_STATE_STORE=s3://clusters.kops.tw88go.top
    kops create cluster --name=kops.tw88go.top --zones=ap-northeast-3a --master-size=t2.micro --node-size=t2.micro --node-count=2 --dns-zone=kops.tw88go.top
  • 套用以上建立的設定檔

    1
    kops update cluster --name kops.tw88go.top --yes --admin

小試身手-kubectl

  • 簡單建立1個pod
    pod_nginx.yml
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    apiVersion: v1
    kind: Pod
    metadata:
    name: pod-nginx
    labels:
    app: nginx
    spec:
    containers:
    - name: nginx
    image: nginx
    ports:
    - containerPort: 80
    1
    kubectl create -f pod_nginx.yml
  • 將pod 以 LoadBalancer 方式提供服務
    1
    2
    kubectl expose pod pod-nginx --type=LoadBalancer
    kubectl get svc pod-nginx
    輸出以下資訊
    1
    2
    NAME        TYPE           CLUSTER-IP      EXTERNAL-IP                                                                   PORT(S)        AGE
    pod-nginx LoadBalancer 100.67.121.49 a3954a6f5f72848eba9df65e0b6f8842-871043940.ap-northeast-3.elb.amazonaws.com 80:30493/TCP 9m44s
  • test Access EXTERNAL-IP
    1
    curl a3954a6f5f72848eba9df65e0b6f8842-871043940.ap-northeast-3.elb.amazonaws.com

清除 K8s Cluster

1
kops delete cluster --name kops.tw88go.top  --yes

參考資料:

Install nvm

1
2
3
4
5
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
command -v nvm
which nvm
nvm ls
nvm current

Install node by nvm

安裝長期支援的版本

1
nvm install --lts

Install Hexo by npm

1
npm install -g hexo-cli

First Hexo

簡單建立一個MyBlog

  • 建立一個MyBlog

    1
    2
    hexo -v
    hexo init MyBlog
  • 簡單建立一篇文章叫做 First Hexo

    1
    hexo new "First-Hexo"

    會這此目錄下 source/_posts/ 生成 First-Hexo.md

    1
    source/_posts/First-Hexo.md
  • 輸出靜態頁面
    會在此目錄下 MyBlog/public/ 生成html靜態頁面

    1
    hexo generate

    或是使用簡碼

    1
    hexo g
  • 瀏覽生成頁面
    hexo 預設自帶web server ; Listen Port: 4000 ; http://localhost:4000

    1
    2
    3
    hexo server
    ###或是使用簡碼也可
    hexo s

    更換theme

    hexo 網路上推薦 NexT

  • install NexT

    1
    2
    cd MyBlog
    git clone https://github.com/theme-next/hexo-theme-next themes/next
  • 修正網站設定 - theme
    搜尋關鍵字 theme ,將預設 landscape -> next
    MyBlog/_config.yml

    1
    2
    ##theme: landscape
    theme: next

    有RSS功能

    1
    npm install hexo-generator-feed --save

    發佈到GitPage

  • 發佈之前, 需要安裝hexo Plugin - hexo-deployer-git

    1
    npm install hexo-deployer-git –save
  • 編輯 _config.yml ,到deploy 區段增加 repo

    1
    2
    3
    4
    5
    deploy:
    type: git
    repo: https://[email protected]/<UserName>/<UserName>.github.io.git
    ##repo: https://github.com/<Username>/<UserName>.github.io.git -- old
    branch: main

    2021/08/13 GitHub開始使用新的認證方式(Token,SSH),使用舊有認證會有錯誤訊息
    remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.
    remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more informat

  • 開始發佈到GitHub

    1
    2
    3
    4
    hexo clean
    hexo deploy
    ###或是使用簡碼也可
    hexo d

參考資料: