# AWS ## week1 AWS 提供的服務 1. EC2(Elastic Compute Cloud) 計算資源(創建機器) EC2提供的功能 >auto scaling 自動擴展: 監控CPU超過??% 就再創建一台機器,低於??%就縮減一台機器 ![](https://hackmd.io/_uploads/H1_Ou-vyT.png) 2. s3 storage >備份、大數據的保存、網頁(靜態) 3. VPC network >資料庫本身不應該對外開放,應放在私有網路 igw (internet gateway) 4. 自動化 5. serverless 創建instance ![截圖 2024-01-06 下午4.15.20](https://hackmd.io/_uploads/rkFU3YIuT.png) ![image](https://hackmd.io/_uploads/SkNshYLdT.png) ![image](https://hackmd.io/_uploads/S1IhhYIdT.png) 允許ssh連線 與 ping測試 ![image](https://hackmd.io/_uploads/Hy_a3KL_T.png) >[Launch instance] --- ## week2 (Simple Notification Service,SNS) publisher, subscriber Ceate Topic ![](https://hackmd.io/_uploads/ByglTgvyp.png) Create Subscriber ![](https://hackmd.io/_uploads/rkSupgPyp.png) 確認 ![](https://hackmd.io/_uploads/BkFs0gDJa.png) 測試 ![](https://hackmd.io/_uploads/Bk6kAeDka.png) ![](https://hackmd.io/_uploads/Sy8fk-wk6.png) --- 連上EC2 ![](https://hackmd.io/_uploads/rkhFrGD1a.png) --- ![](https://hackmd.io/_uploads/SJAfuzw1a.png) --- ## week3 Available Zone (AZ) Vitual Private Computing (VPC) Network Access Controll List(NACL) > 控管 進出 subnet的流量 > 無狀態 (進出都要檢查) NAT getway 在Public Subnet中 Pribate Subnet 需要透過 NAT gw向外界溝通 (相反也是) ![](https://hackmd.io/_uploads/ByAkcNgeT.png) ![](https://hackmd.io/_uploads/HJdDqElgp.png) Elastic Network Interface(ENI) ![](https://hackmd.io/_uploads/H17so4gxa.png) Instance storage > 臨時的 Elastic Block Service(EBS) > 永久存在 > 有備源(差異式備分,儲存空間小) ![](https://hackmd.io/_uploads/rk4M2ExeT.png) Elastic Load Balancer(ELB) > 分散流量 ![](https://hackmd.io/_uploads/B11uhNxxp.png) Auto Scaling Group(ASG) > 讓EC2 自動擴展/內縮 --- ![](https://hackmd.io/_uploads/B1epNBgx6.png) 預設的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 ``` ![](https://hackmd.io/_uploads/SkfUGUgxT.png) ## week4 Elastic IP Address 讓VM重新啟動後IP都固定 ![](https://hackmd.io/_uploads/B1epNBgx6.png) 讓Public裡的VM可以有Public IP ![](https://hackmd.io/_uploads/SJP84dKxT.png) NAT gateway ![截圖 2024-01-06 下午6.20.05](https://hackmd.io/_uploads/ryI_KsLOa.png) - [x] Public [Allocate Elastic IP] 建立Routing table ![截圖 2024-01-06 下午6.28.34](https://hackmd.io/_uploads/rk4dsjUua.png) 把subnet與Routing table關聯 ![image](https://hackmd.io/_uploads/BJHnssIdT.png) ## 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 ``` ![](https://hackmd.io/_uploads/BkLOwxhb6.png) ## Week7 (10/24) ### Auto Scaling Group (ASG) scale up擴張、scale down縮小 當Clint數量過多時 有兩種應對方法: >veritcal (增強機器能力) horizontal (增加機器數量) ![](https://hackmd.io/_uploads/BylX-7rfp.png) ![](https://hackmd.io/_uploads/H1qp8mrG6.png) 基本功能測試 強制Terminate後會自動生成一台機器 ![](https://hackmd.io/_uploads/Byo6RmHMa.jpg) ![](https://hackmd.io/_uploads/SyjpAQHzT.jpg) --- CPU 壓力測試 使用`stress --cpu 4` > yum install stress ![](https://hackmd.io/_uploads/B1y5CmSfT.png) ![](https://hackmd.io/_uploads/ryjxHNSM6.png) ## 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的連接 ![image](https://hackmd.io/_uploads/r13vaiL_T.png) ![image](https://hackmd.io/_uploads/SJyupiLOa.png) 針對各個target group,需要設定被選為處理請求的對象時的預設動作, 稱為Listener rules add listener rules ![image](https://hackmd.io/_uploads/HJ8api8da.png) ![image](https://hackmd.io/_uploads/SkcppoUO6.png) ![image](https://hackmd.io/_uploads/rJgCajIu6.png) ELB測試 ![](https://hackmd.io/_uploads/r1pcvEBMa.gif) ## week9 考試 ## week10 serverless service ### RDS (Relational Data Service) > mySQL mariadb aurora... ![RDS us-east-1png](https://hackmd.io/_uploads/B19_YRxET.png) 連線到DB ![image](https://hackmd.io/_uploads/BkFeqRg4T.png) 連線到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"; } ?> ``` ![image](https://hackmd.io/_uploads/ry9UhAgVp.png) delete RDS ![image](https://hackmd.io/_uploads/Hk4yfJW46.png) ### EBS (Elastic Block Service) 讓ec2 terminate後 儲存資料仍存在 新的ec2可以再重新掛載EBS [參考](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html) ![image](https://hackmd.io/_uploads/HJDlE1bNp.png) ![image](https://hackmd.io/_uploads/rkc1S1b4a.png) Attach volume ![image](https://hackmd.io/_uploads/Sk_TNy-Ep.png) ![image](https://hackmd.io/_uploads/Hy2NHyWVp.png) mkfs -t xfs /dev/xvdf 格式化 安裝sudo yum install xfsprogs sudo lsblk 掛載 sudo mount /dev/xvdf /data ![image](https://hackmd.io/_uploads/ByuM8kbVp.png) 卸載 umount /data ![image](https://hackmd.io/_uploads/BymhIkbNa.png) 重新Attach volume到另一台ec2後 掛載 sudo mount /dev/xvdf /data 檔案仍然存在 ![image](https://hackmd.io/_uploads/H13luyb4T.png) ### IFS (Elastic File System) 多個ec2 共享資料 ### EIP (Elastic IP) 固定Public IP,每次重新啟動都是相同IP 架設伺服器 ![image](https://hackmd.io/_uploads/BkX4jy-Na.png) ![image](https://hackmd.io/_uploads/B1y5oJWNp.png) 當 機器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 ![image](https://hackmd.io/_uploads/Sy8mJm5V6.png) 建立EFS ![image](https://hackmd.io/_uploads/ByS75WcN6.png) create AP ![image](https://hackmd.io/_uploads/B13TpZ9N6.png) ![image](https://hackmd.io/_uploads/SyhR0M5Np.png) 選擇有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) ![image](https://hackmd.io/_uploads/SkzsyX5E6.png) ### IAM IAM (Identity and Access Management) 針對user和group管理 是全球的服務(跟region無關) ![image](https://hackmd.io/_uploads/SJSiBM5Na.png) ![image](https://hackmd.io/_uploads/r1KQUGq4T.png) ![image](https://hackmd.io/_uploads/rJc-vf9NT.png) ## Week12 ### S3 (Simple Storge Service) 是一個global Service 1. bucket ploicy 2. IAM 3. ACL(Access Control List) ![image](https://hackmd.io/_uploads/BJTKUHXST.png) ![image](https://hackmd.io/_uploads/r1-rFS7Sa.png) ![image](https://hackmd.io/_uploads/Hy7YjHQBT.png) ![image](https://hackmd.io/_uploads/HkODx8XBT.png) ![image](https://hackmd.io/_uploads/ryxlZLXB6.png) ![image](https://hackmd.io/_uploads/BkMFfUXBp.png) ![image](https://hackmd.io/_uploads/Syv3RLQrp.png) ![image](https://hackmd.io/_uploads/S1IYJwXHp.png) ## Week13 ### AWS CLI Install >curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" unzip awscliv2.zip sudo ./aws/install ![image](https://hackmd.io/_uploads/rkVJ1t2Ha.png) ![image](https://hackmd.io/_uploads/ryZjgK2ST.png) ![image](https://hackmd.io/_uploads/H1LpxthBa.png) Access key: AKIARKR5CPIR6DLRCOVZ Secret access key: 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 vim .aws/credentials ![image](https://hackmd.io/_uploads/Sy2dWFnr6.png) 創建bucket aws s3 mb s3://1205-guangjhe >make_bucket: 1205-guangjhe ![image](https://hackmd.io/_uploads/BJ2jQKhrp.png) 上傳檔案 ![image](https://hackmd.io/_uploads/Sy8SNK3Bp.png) ![image](https://hackmd.io/_uploads/SyQMHFhBa.png) ![image](https://hackmd.io/_uploads/B11jrFhHp.png) 下載檔案 ![image](https://hackmd.io/_uploads/rklF4t2H6.png) Rename ![image](https://hackmd.io/_uploads/rkoZUF2H6.png) Delete ![image](https://hackmd.io/_uploads/ry5ELthSp.png) Delete Bucket ![image](https://hackmd.io/_uploads/Hk63IKnHp.png) ### SDK pip3 install boto3 至少要python3.7 [升級python](https://zhuanlan.zhihu.com/p/590965831) ![image](https://hackmd.io/_uploads/B1IWat3Hp.png) ![image](https://hackmd.io/_uploads/rk0mxcnH6.png) ![image](https://hackmd.io/_uploads/rkkuf93H6.png) cors cross-origin resource sharing ![image](https://hackmd.io/_uploads/SJQgh5hHa.png) ![image](https://hackmd.io/_uploads/BkTM6c2ST.png) ![image](https://hackmd.io/_uploads/rJqMyonS6.png) ## Week14 Route53 將ec2的public IP與DNS綁定 ![image](https://hackmd.io/_uploads/SJQMFnHL6.png) ![image](https://hackmd.io/_uploads/S1VAunBU6.png) Create Record ![image](https://hackmd.io/_uploads/HJLxohSLT.png) Tecord type: Recprd name - Value A: domain name - IPv4 AAAA: domain name - IPv6 CNAME: domain name - domain name TTL 是 DNS與IP的查詢結果存放在cache的時間 ![image](https://hackmd.io/_uploads/Hk79T2BUT.png) ![Uploading file..._8obni5k1t]() ![image](https://hackmd.io/_uploads/ry7JMpHIT.png) ![image](https://hackmd.io/_uploads/S1V5qpBIT.png) ![image](https://hackmd.io/_uploads/rJhCz6rUp.png) Record name不填 使用Alias就可以使用root domain ![image](https://hackmd.io/_uploads/BygM86SIT.png) ![image](https://hackmd.io/_uploads/H1vL8pHIa.png) 使用DNS實現負載均衡 ![image](https://hackmd.io/_uploads/B1KR9prU6.png) ![image](https://hackmd.io/_uploads/SypD9pH86.png) CDN (Content Delivery Network) ![image](https://hackmd.io/_uploads/rkikN0rUp.png) ![image](https://hackmd.io/_uploads/SJZONRSI6.png) ![image](https://hackmd.io/_uploads/B1eSnRrIp.png) ## week15 ![image](https://hackmd.io/_uploads/SyYXQgJwT.png) ![image](https://hackmd.io/_uploads/Syf9QgyP6.png) client無法直接存取s3(private) 所以需要透過cloudfront間接存取 ![image](https://hackmd.io/_uploads/S1ZxrlJD6.png) ### WAF (Web Appplication Firewall) ![image](https://hackmd.io/_uploads/SkDQAgJvT.png) ![image](https://hackmd.io/_uploads/H1ZE7ZyDT.png) ![image](https://hackmd.io/_uploads/SJJiI-JPp.png) ![image](https://hackmd.io/_uploads/r1zMPbkwT.png) ### DynamoDB ![image](https://hackmd.io/_uploads/BJ3Gc-Jwp.png) ![image](https://hackmd.io/_uploads/ryImc-kPp.png) ![image](https://hackmd.io/_uploads/ByTLJzJDp.png) > 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 ![image](https://hackmd.io/_uploads/SyKAlGywa.png) ![image](https://hackmd.io/_uploads/SkjSbGyv6.png) ![image](https://hackmd.io/_uploads/BJb5WzJvT.png) vpc lambda sqs ## week16 ![image](https://hackmd.io/_uploads/HyCnT7uwT.png) > Lamda role ### serverless computing - Lambda ![image](https://hackmd.io/_uploads/rkJD1EuDp.png) 從Dynomodb 讀取 ![image](https://hackmd.io/_uploads/SktBG4uwT.png) 從Dynomodb 寫入 ![image](https://hackmd.io/_uploads/Hy8NNEOPT.png) ![image](https://hackmd.io/_uploads/BkE2V4dwp.png) API gateway ![image](https://hackmd.io/_uploads/Skm7vNdw6.png) ![image](https://hackmd.io/_uploads/S1YiDEOw6.png) ![image](https://hackmd.io/_uploads/ByWcPVdvT.png) ![image](https://hackmd.io/_uploads/r1KKeSuwp.png) --- 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" } } ``` ![image](https://hackmd.io/_uploads/r1uy2rODT.png) ## 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 } } ``` ![1704267721369](https://hackmd.io/_uploads/ryVaLhIOT.gif)