0%

AWS_VPC-LAB3 By Terraform

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

參考資料

歡迎關注我的其它發布渠道