# AWS
## week1
AWS 提供的服務
1. EC2(Elastic Compute Cloud) 計算資源(創建機器)
EC2提供的功能
>auto scaling 自動擴展: 監控CPU超過??% 就再創建一台機器,低於??%就縮減一台機器

2. s3
storage
>備份、大數據的保存、網頁(靜態)
3. VPC
network
>資料庫本身不應該對外開放,應放在私有網路
igw (internet gateway)
4. 自動化
5. serverless
創建instance



允許ssh連線 與 ping測試

>[Launch instance]
---
## week2
(Simple Notification Service,SNS)
publisher, subscriber
Ceate Topic

Create Subscriber

確認

測試


---
連上EC2

---

---
## week3
Available Zone (AZ)
Vitual Private Computing (VPC)
Network Access Controll List(NACL)
> 控管 進出 subnet的流量
> 無狀態 (進出都要檢查)
NAT getway 在Public Subnet中
Pribate Subnet 需要透過 NAT gw向外界溝通 (相反也是)


Elastic Network Interface(ENI)

Instance storage
> 臨時的
Elastic Block Service(EBS)
> 永久存在
> 有備源(差異式備分,儲存空間小)

Elastic Load Balancer(ELB)
> 分散流量

Auto Scaling Group(ASG)
> 讓EC2 自動擴展/內縮
---

預設的subnet都是private,要建立IGW才會變成public
建立vpc
subnet
igw
Attach to VPC
route tables
Edit routes
Edit subnet associations
user data
```
#!/bin/bash
yum update -y
yum install -y httpd.x86_64
systemctl start httpd.service
systemctl enable httpd.service
echo “Hello World from $(hostname -f)” > /var/www/html/index.html
```

## week4
Elastic IP Address
讓VM重新啟動後IP都固定

讓Public裡的VM可以有Public IP

NAT gateway

- [x] Public
[Allocate Elastic IP]
建立Routing table

把subnet與Routing table關聯

## week5放假
## week6
[參考](https://github.com/stereomp3/note/blob/main/linux/111semester01/13-.md#MYSQL)
#### Database
[ec2-user@ip-192-168-1-200 ~]$ mysql -u root -p
MariaDB [(none)]> show databases;
```
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
+--------------------+
3 rows in set (0.002 sec)
```
MariaDB [(none)]> create database testdb;
```
Query OK, 1 row affected (0.000 sec)
```
MariaDB [(none)]> show databases;
```
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| testdb |
+--------------------+
4 rows in set (0.000 sec)
```
MariaDB [(none)]> use testdb;
```
Database changed
```
MariaDB [testdb]> create table addressbook(name varchar(50) not null, phone char(10));
```
Query OK, 0 rows affected (0.007 sec)
```
MariaDB [testdb]> insert into addressbook(name, phone) values ("tom", "0912123456");
```
Query OK, 1 row affected (0.006 sec)
```
MariaDB [testdb]> insert into addressbook(name, phone) values ("mary", "0933123456");
```
Query OK, 1 row affected (0.001 sec)
```
MariaDB [testdb]> insert into addressbook(name, phone) values ("peter", "0955123456");
```
Query OK, 1 row affected (0.001 sec)
```
MariaDB [testdb]> select name,phone from addressbook;
```
+-------+------------+
| name | phone |
+-------+------------+
| tom | 0912123456 |
| mary | 0933123456 |
| peter | 0955123456 |
+-------+------------+
3 rows in set (0.000 sec)
```
MariaDB [testdb]> update addressbook set phone="0911123456" where name="tom";
```
Query OK, 1 row affected (0.001 sec)
Rows matched: 1 Changed: 1 Warnings: 0
```

## Week7 (10/24)
### Auto Scaling Group (ASG)
scale up擴張、scale down縮小
當Clint數量過多時 有兩種應對方法:
>veritcal (增強機器能力)
horizontal (增加機器數量)


基本功能測試
強制Terminate後會自動生成一台機器


---
CPU 壓力測試
使用`stress --cpu 4`
> yum install stress


## week8
### Elastic load balance (ELB)
ELB可以client的請求依照規則(例如Round Robin)分配給多台server處理
在建立ELB前需要先在VPC中建立2個target group
ELB以target group為單位選擇要處理的對象
一個target group內可以包含不同subnet的ec2
ELB與target group的連接


針對各個target group,需要設定被選為處理請求的對象時的預設動作, 稱為Listener rules
add listener rules



ELB測試

## week9
考試
## week10
serverless service
### RDS (Relational Data Service)
> mySQL mariadb aurora...

連線到DB

連線到DB後寫入資料
```
show databases; # 顯示目前有的資料庫
create database testdb; # 創建資料庫
use testdb; # 使用資料庫
create table addrbook(name varchar(50) not null, phone char(10)); # 創建資料表
insert into addrbook(name, phone) values ("tom", "0912123456"); # 加入資料
insert into addrbook(name, phone) values ("mary", "0912123567"); # 加入資料
select name,phone from addrbook; # 選擇資料
update addrbook set phone="0987465123"; # 更新資料
```
修改 /var/www/html/testrds.db
```php
<?php
$servername="testdb.ckshqncabm1d.us-east-1.rds.amazonaws.com";
$username="user";
$password="12345678";
$dbname="testdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("connection failed: " . $conn->connect_error);
}
else{
echo "connect OK!" . "<br>";
}
$sql="select name,phone from addrbook";
$result=$conn->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
echo "name: " . $row["name"] . "\tphone: " . $row["phone"] . "<br>";
}
} else {
echo "0 record";
}
?>
```

delete RDS

### EBS (Elastic Block Service)
讓ec2 terminate後 儲存資料仍存在
新的ec2可以再重新掛載EBS
[參考](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html)


Attach volume


mkfs -t xfs /dev/xvdf
格式化
安裝sudo yum install xfsprogs
sudo lsblk
掛載 sudo mount /dev/xvdf /data

卸載 umount /data

重新Attach volume到另一台ec2後
掛載 sudo mount /dev/xvdf /data
檔案仍然存在

### IFS (Elastic File System)
多個ec2 共享資料
### EIP (Elastic IP)
固定Public IP,每次重新啟動都是相同IP
架設伺服器


當 機器1使用了EIP 但 機器1停止服務後 可以手動將EIP轉到機器2
## week11
### DynamoDB (noSQL)
### BOTO3
### route53
### terraform
### EFS (Elastic File System)
[參考](https://docs.aws.amazon.com/zh_tw/efs/latest/ug/wt1-test.html)
VPC設定-DNS

建立EFS

create AP


選擇有NFS的sg
創建ec2 一台在1a一台在1c 都要選有NFS的sg
mkdir test-efs
sudo yum install -y amazon-efs-utils
sudo mount -t nfs -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport fs-008e8df656b430a4a.efs.us-east-1.amazonaws.com:/ ~/test-efs
(記得改DNS fs-008e8df656b430a4a.efs.us-east-1.amazonaws.com)

### IAM
IAM (Identity and Access Management)
針對user和group管理
是全球的服務(跟region無關)



## Week12
### S3 (Simple Storge Service)
是一個global Service
1. bucket ploicy
2. IAM
3. ACL(Access Control List)








## Week13
### AWS CLI
Install
>curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install



Access key:
AKIARKR5CPIR6DLRCOVZ
Secret access key:
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
vim .aws/credentials

創建bucket
aws s3 mb s3://1205-guangjhe
>make_bucket: 1205-guangjhe

上傳檔案



下載檔案

Rename

Delete

Delete Bucket

### SDK
pip3 install boto3
至少要python3.7
[升級python](https://zhuanlan.zhihu.com/p/590965831)



cors
cross-origin resource sharing



## Week14
Route53
將ec2的public IP與DNS綁定


Create Record

Tecord type: Recprd name - Value
A: domain name - IPv4
AAAA: domain name - IPv6
CNAME: domain name - domain name
TTL 是 DNS與IP的查詢結果存放在cache的時間

![Uploading file..._8obni5k1t]()



Record name不填 使用Alias就可以使用root domain


使用DNS實現負載均衡


CDN (Content Delivery Network)



## week15


client無法直接存取s3(private)
所以需要透過cloudfront間接存取

### WAF (Web Appplication Firewall)




### DynamoDB



> import boto3
import os
os.environ['AWS_DEFAULT_REGION'] = 'us-east-1'
_TableName_ = "addrbook"
client = boto3.client('dynamodb')
DB = boto3.resource('dynamodb')
table = DB.Table(_TableName_)
response = table.get_item(
Key={
'name': "mary"
}
)
response["Item"]
print(response['Item'])
### Lamda
serverless computing



vpc
lambda sqs
## week16

> Lamda role
### serverless computing - Lambda

從Dynomodb 讀取

從Dynomodb 寫入


API gateway




---
Tarraform
初始化
```!
[user@centos7-3 1224]$ terraform init
Initializing the backend...
Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v5.31.0...
- Installed hashicorp/aws v5.31.0 (signed by HashiCorp)
Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
```
plan(預覽執行)
```!
[user@centos7-3 1224]$ terraform plan
Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_instance.mytest_vm will be created
+ resource "aws_instance" "mytest_vm" {
+ ami = "ami-079db87dc4c10ac91"
+ arn = (known after apply)
+ associate_public_ip_address = (known after apply)
+ availability_zone = (known after apply)
+ cpu_core_count = (known after apply)
+ cpu_threads_per_core = (known after apply)
+ disable_api_stop = (known after apply)
+ disable_api_termination = (known after apply)
+ ebs_optimized = (known after apply)
+ get_password_data = false
+ host_id = (known after apply)
+ host_resource_group_arn = (known after apply)
+ iam_instance_profile = (known after apply)
+ id = (known after apply)
+ instance_initiated_shutdown_behavior = (known after apply)
+ instance_lifecycle = (known after apply)
+ instance_state = (known after apply)
+ instance_type = "t2.micro"
+ ipv6_address_count = (known after apply)
+ ipv6_addresses = (known after apply)
+ key_name = (known after apply)
+ monitoring = (known after apply)
+ outpost_arn = (known after apply)
+ password_data = (known after apply)
+ placement_group = (known after apply)
+ placement_partition_number = (known after apply)
+ primary_network_interface_id = (known after apply)
+ private_dns = (known after apply)
+ private_ip = (known after apply)
+ public_dns = (known after apply)
+ public_ip = (known after apply)
+ secondary_private_ips = (known after apply)
+ security_groups = (known after apply)
+ source_dest_check = true
+ spot_instance_request_id = (known after apply)
+ subnet_id = (known after apply)
+ tags_all = (known after apply)
+ tenancy = (known after apply)
+ user_data = (known after apply)
+ user_data_base64 = (known after apply)
+ user_data_replace_on_change = false
+ vpc_security_group_ids = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
───────────────────────────────────────────────────────────────────────────────
Note: You didn't use the -out option to save this plan, so Terraform can't
guarantee to take exactly these actions if you run "terraform apply" now.
```
執行
```!
[user@centos7-3 1224]$ terraform apply
Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_instance.mytest_vm will be created
+ resource "aws_instance" "mytest_vm" {
+ ami = "ami-079db87dc4c10ac91"
+ arn = (known after apply)
+ associate_public_ip_address = (known after apply)
+ availability_zone = (known after apply)
+ cpu_core_count = (known after apply)
+ cpu_threads_per_core = (known after apply)
+ disable_api_stop = (known after apply)
+ disable_api_termination = (known after apply)
+ ebs_optimized = (known after apply)
+ get_password_data = false
+ host_id = (known after apply)
+ host_resource_group_arn = (known after apply)
+ iam_instance_profile = (known after apply)
+ id = (known after apply)
+ instance_initiated_shutdown_behavior = (known after apply)
+ instance_lifecycle = (known after apply)
+ instance_state = (known after apply)
+ instance_type = "t2.micro"
+ ipv6_address_count = (known after apply)
+ ipv6_addresses = (known after apply)
+ key_name = (known after apply)
+ monitoring = (known after apply)
+ outpost_arn = (known after apply)
+ password_data = (known after apply)
+ placement_group = (known after apply)
+ placement_partition_number = (known after apply)
+ primary_network_interface_id = (known after apply)
+ private_dns = (known after apply)
+ private_ip = (known after apply)
+ public_dns = (known after apply)
+ public_ip = (known after apply)
+ secondary_private_ips = (known after apply)
+ security_groups = (known after apply)
+ source_dest_check = true
+ spot_instance_request_id = (known after apply)
+ subnet_id = (known after apply)
+ tags_all = (known after apply)
+ tenancy = (known after apply)
+ user_data = (known after apply)
+ user_data_base64 = (known after apply)
+ user_data_replace_on_change = false
+ vpc_security_group_ids = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
aws_instance.mytest_vm: Creating...
aws_instance.mytest_vm: Still creating... [10s elapsed]
aws_instance.mytest_vm: Still creating... [20s elapsed]
aws_instance.mytest_vm: Still creating... [30s elapsed]
aws_instance.mytest_vm: Creation complete after 37s [id=i-0f7b6226a2049910d]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
```
刪除(ec2)
```!
[user@centos7-3 1224]$ terraform destroy
aws_instance.mytest_vm2: Refreshing state... [id=i-044e6bcb13170af96]
aws_instance.mytest_vm: Refreshing state... [id=i-0f7b6226a2049910d]
Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
- destroy
Terraform will perform the following actions:
# aws_instance.mytest_vm will be destroyed
- resource "aws_instance" "mytest_vm" {
- ami = "ami-079db87dc4c10ac91" -> null
- arn = "arn:aws:ec2:us-east-1:091396143651:instance/i-0f7b6226a2049910d" -> null
- associate_public_ip_address = true -> null
- availability_zone = "us-east-1b" -> null
- cpu_core_count = 1 -> null
- cpu_threads_per_core = 1 -> null
- disable_api_stop = false -> null
- disable_api_termination = false -> null
- ebs_optimized = false -> null
- get_password_data = false -> null
- hibernation = false -> null
- id = "i-0f7b6226a2049910d" -> null
- instance_initiated_shutdown_behavior = "stop" -> null
- instance_state = "running" -> null
- instance_type = "t2.micro" -> null
- ipv6_address_count = 0 -> null
- ipv6_addresses = [] -> null
- monitoring = false -> null
- placement_partition_number = 0 -> null
- primary_network_interface_id = "eni-00a1ac032e61dcf12" -> null
- private_dns = "ip-172-31-90-17.ec2.internal" -> null
- private_ip = "172.31.90.17" -> null
- public_dns = "ec2-52-90-8-51.compute-1.amazonaws.com" -> null
- public_ip = "52.90.8.51" -> null
- secondary_private_ips = [] -> null
- security_groups = [
- "default",
] -> null
- source_dest_check = true -> null
- subnet_id = "subnet-00ee1c3e106402822" -> null
- tags = {} -> null
- tags_all = {} -> null
- tenancy = "default" -> null
- user_data_replace_on_change = false -> null
- vpc_security_group_ids = [
- "sg-0651876b1518d487b",
] -> null
- capacity_reservation_specification {
- capacity_reservation_preference = "open" -> null
}
- cpu_options {
- core_count = 1 -> null
- threads_per_core = 1 -> null
}
- credit_specification {
- cpu_credits = "standard" -> null
}
- enclave_options {
- enabled = false -> null
}
- maintenance_options {
- auto_recovery = "default" -> null
}
- metadata_options {
- http_endpoint = "enabled" -> null
- http_protocol_ipv6 = "disabled" -> null
- http_put_response_hop_limit = 2 -> null
- http_tokens = "required" -> null
- instance_metadata_tags = "disabled" -> null
}
- private_dns_name_options {
- enable_resource_name_dns_a_record = false -> null
- enable_resource_name_dns_aaaa_record = false -> null
- hostname_type = "ip-name" -> null
}
- root_block_device {
- delete_on_termination = true -> null
- device_name = "/dev/xvda" -> null
- encrypted = false -> null
- iops = 3000 -> null
- tags = {} -> null
- throughput = 125 -> null
- volume_id = "vol-0eb5bdfb5cbc2af3c" -> null
- volume_size = 8 -> null
- volume_type = "gp3" -> null
}
}
# aws_instance.mytest_vm2 will be destroyed
- resource "aws_instance" "mytest_vm2" {
- ami = "ami-079db87dc4c10ac91" -> null
- arn = "arn:aws:ec2:us-east-1:091396143651:instance/i-044e6bcb13170af96" -> null
- associate_public_ip_address = true -> null
- availability_zone = "us-east-1b" -> null
- cpu_core_count = 1 -> null
- cpu_threads_per_core = 1 -> null
- disable_api_stop = false -> null
- disable_api_termination = false -> null
- ebs_optimized = false -> null
- get_password_data = false -> null
- hibernation = false -> null
- id = "i-044e6bcb13170af96" -> null
- instance_initiated_shutdown_behavior = "stop" -> null
- instance_state = "running" -> null
- instance_type = "t2.micro" -> null
- ipv6_address_count = 0 -> null
- ipv6_addresses = [] -> null
- monitoring = false -> null
- placement_partition_number = 0 -> null
- primary_network_interface_id = "eni-04a6ba17ad35063bb" -> null
- private_dns = "ip-172-31-91-223.ec2.internal" -> null
- private_ip = "172.31.91.223" -> null
- public_dns = "ec2-34-207-159-216.compute-1.amazonaws.com" -> null
- public_ip = "34.207.159.216" -> null
- secondary_private_ips = [] -> null
- security_groups = [
- "default",
] -> null
- source_dest_check = true -> null
- subnet_id = "subnet-00ee1c3e106402822" -> null
- tags = {
- "Name" = "mytest"
} -> null
- tags_all = {
- "Name" = "mytest"
} -> null
- tenancy = "default" -> null
- user_data_replace_on_change = false -> null
- vpc_security_group_ids = [
- "sg-0651876b1518d487b",
] -> null
- capacity_reservation_specification {
- capacity_reservation_preference = "open" -> null
}
- cpu_options {
- core_count = 1 -> null
- threads_per_core = 1 -> null
}
- credit_specification {
- cpu_credits = "standard" -> null
}
- enclave_options {
- enabled = false -> null
}
- maintenance_options {
- auto_recovery = "default" -> null
}
- metadata_options {
- http_endpoint = "enabled" -> null
- http_protocol_ipv6 = "disabled" -> null
- http_put_response_hop_limit = 2 -> null
- http_tokens = "required" -> null
- instance_metadata_tags = "disabled" -> null
}
- private_dns_name_options {
- enable_resource_name_dns_a_record = false -> null
- enable_resource_name_dns_aaaa_record = false -> null
- hostname_type = "ip-name" -> null
}
- root_block_device {
- delete_on_termination = true -> null
- device_name = "/dev/xvda" -> null
- encrypted = false -> null
- iops = 3000 -> null
- tags = {} -> null
- throughput = 125 -> null
- volume_id = "vol-01a7f07aa835bb729" -> null
- volume_size = 8 -> null
- volume_type = "gp3" -> null
}
}
Plan: 0 to add, 0 to change, 2 to destroy.
Do you really want to destroy all resources?
Terraform will destroy all your managed infrastructure, as shown above.
There is no undo. Only 'yes' will be accepted to confirm.
Enter a value: yes
aws_instance.mytest_vm: Destroying... [id=i-0f7b6226a2049910d]
aws_instance.mytest_vm2: Destroying... [id=i-044e6bcb13170af96]
aws_instance.mytest_vm: Still destroying... [id=i-0f7b6226a2049910d, 10s elapsed]
aws_instance.mytest_vm2: Still destroying... [id=i-044e6bcb13170af96, 10s elapsed]
aws_instance.mytest_vm: Still destroying... [id=i-0f7b6226a2049910d, 20s elapsed]
aws_instance.mytest_vm2: Still destroying... [id=i-044e6bcb13170af96, 20s elapsed]
aws_instance.mytest_vm: Still destroying... [id=i-0f7b6226a2049910d, 30s elapsed]
aws_instance.mytest_vm2: Still destroying... [id=i-044e6bcb13170af96, 30s elapsed]
aws_instance.mytest_vm: Still destroying... [id=i-0f7b6226a2049910d, 40s elapsed]
aws_instance.mytest_vm2: Still destroying... [id=i-044e6bcb13170af96, 40s elapsed]
aws_instance.mytest_vm: Destruction complete after 42s
aws_instance.mytest_vm2: Destruction complete after 42s
Destroy complete! Resources: 2 destroyed.
```
創建vpc
```
resource "aws_vpc" "testvpc1"{
cidr_block="192.168.0.0/16"
tags = {
Name = "testvpc1"
}
}
```
創建子網域
```
resource "aws_subnet" "testvpc1-web" {
vpc_id = "${aws_vpc.testvpc1.id}"
cidr_block = "192.168.1.0/24"
availability_zone = "us-east-1a"
tags = {
Name = "testvpc1-web"
}
}
```

## week17
Spot instance
花費較低的成本使用閒置資源
加分作業
透過terraform 建立ALB輪循訪問兩台ec2
``` python
provider "aws" {
region = "us-east-1"
}
# 創建VPC
resource "aws_vpc" "myvpc"{
cidr_block="192.168.0.0/16"
tags = {
Name = "myvpc"
}
}
# 建立subnet
resource "aws_subnet" "myvpc-web" {
vpc_id = "${aws_vpc.myvpc.id}"
cidr_block = "192.168.1.0/24"
availability_zone = "us-east-1a"
tags = {
Name = "myvpc-web"
}
}
resource "aws_subnet" "myvpc-web2" {
vpc_id = "${aws_vpc.myvpc.id}"
cidr_block = "192.168.2.0/24"
availability_zone = "us-east-1b"
tags = {
Name = "myvpc-web"
}
}
# 建立Internet Gateway
resource "aws_internet_gateway" "igw" {
vpc_id="${aws_vpc.myvpc.id}" # 綁定VPC
tags = {
Name = "myvpcvpc-igw"
}
}
# 設定Routing Table
resource "aws_route_table" "myrt" {
vpc_id="${aws_vpc.myvpc.id}" # 綁定VPC
route {
cidr_block="0.0.0.0/0" # 增加內定路由(default route)
gateway_id = "${aws_internet_gateway.igw.id}"
}
tags = {
Name = "myvpc-rt"
}
}
# 綁定 subnet 與 Routing Table
resource "aws_route_table_association" "myrt_assoc" {
subnet_id = aws_subnet.myvpc-web.id
route_table_id = aws_route_table.myrt.id
}
resource "aws_route_table_association" "myrt_assoc2" {
subnet_id = aws_subnet.myvpc-web2.id
route_table_id = aws_route_table.myrt.id
}
# 建立 security group
resource "aws_security_group" "sg_myvpc" {
name = "sg_myvpc"
description="security group for myvpc"
vpc_id="${aws_vpc.myvpc.id}" # 綁定VPC
# 允許80, 443, 22
ingress {
description = "HTTPS traffic"
from_port = 443
to_port = 443
protocol ="tcp"
cidr_blocks = ["0.0.0.0/0"] # 允許任何來源的連線
}
ingress {
description = "HTTP traffic"
from_port = 80
to_port = 80
protocol ="tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "SSH traffic"
from_port = 22
to_port = 22
protocol ="tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0 # 0 表示 don't care
to_port = 0 # 0 表示 don't care
protocol ="-1"
cidr_blocks= ["0.0.0.0/0"]
}
tags = {
Name = "sg_myvpc"
}
}
# 申請 網路卡
resource "aws_network_interface" "webserver-nic" {
subnet_id = aws_subnet.myvpc-web.id
private_ips=["192.168.1.100"]
security_groups = ["${aws_security_group.sg_myvpc.id}"]
}
resource "aws_network_interface" "webserver-nic2" {
subnet_id = aws_subnet.myvpc-web2.id
private_ips=["192.168.2.100"]
security_groups = ["${aws_security_group.sg_myvpc.id}"]
}
# 申請 Elastic IP 並 與網路卡綁定
resource "aws_eip" "web-eip" {
vpc = true
network_interface = aws_network_interface.webserver-nic.id
associate_with_private_ip = "192.168.1.100"
depends_on = [aws_internet_gateway.igw]
}
resource "aws_eip" "web-eip2" {
vpc = true
network_interface = aws_network_interface.webserver-nic2.id
associate_with_private_ip = "192.168.2.100"
depends_on = [aws_internet_gateway.igw]
}
# 創建ec2
resource "aws_instance" "webserver" {
ami="ami-0c7217cdde317cfec" # 這是一台ubuntu
instance_type = "t2.micro"
availability_zone = "us-east-1a"
key_name = "mykey999"
network_interface {
device_index = 0
network_interface_id = aws_network_interface.webserver-nic.id
}
user_data = <<-EOF
#!/bin/bash
sudo apt update -y
sudo apt install apache2 -y
sudo systemctl start apache2
sudo bash -c 'echo I am A > /var/www/html/index.html'
EOF
tags ={
Name = "web-server"
}
}
resource "aws_instance" "webserver2" {
ami="ami-0c7217cdde317cfec" # 這是一台ubuntu
instance_type = "t2.micro"
availability_zone = "us-east-1b"
key_name = "mykey999"
network_interface {
device_index = 0
network_interface_id = aws_network_interface.webserver-nic2.id
}
user_data = <<-EOF
#!/bin/bash
sudo apt update -y
sudo apt install apache2 -y
sudo systemctl start apache2
sudo bash -c 'echo I am B > /var/www/html/index.html'
EOF
tags ={
Name = "web-server"
}
}
# 創建 Target Group
resource "aws_lb_target_group" "tg1" {
name = "tg-testvpc"
target_type = "instance"
port = 80
protocol = "HTTP"
protocol_version = "HTTP1"
vpc_id = "${aws_vpc.myvpc.id}"
}
# 綁定 Target Group 與 ec2
resource "aws_lb_target_group_attachment" "attest" {
target_group_arn = aws_lb_target_group.tg1.arn
target_id = aws_instance.webserver.id
port = 80
}
resource "aws_lb_target_group_attachment" "attest2" {
target_group_arn = aws_lb_target_group.tg1.arn
target_id = aws_instance.webserver2.id
port = 80
}
# 創建 ALB
resource "aws_alb" "albtestvpc" {
name = "albtestvpc"
internal = false
load_balancer_type = "application"
security_groups = ["${aws_security_group.sg_myvpc.id}"]
subnets = ["${aws_subnet.myvpc-web.id}", "${aws_subnet.myvpc-web2.id}"]
}
# 綁定 ALB 與 Target Group
resource "aws_lb_listener" "elb_listener" {
load_balancer_arn = aws_alb.albtestvpc.arn
port = 80
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.tg1.arn
}
}
```
