「AWS Hands-on for Beginners スケーラブルウェブサイト構築編 」をAWS CLIでやってみる

https://pages.awscloud.com/JAPAN-event-OE-Hands-on-for-Beginners-Scalable-2022-reg-event.html

上記、「AWS Hands-on for Beginners 〜 スケーラブルウェブサイト構築編 〜」 をAWS CLIでやってみる
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3297641/8b13fd30-8480-ec9d-c0ff-32b636267b87.png)
ハンズオンから引用
# 02 Amazon VPCの作成 ～ WordPress用Webサーバ・データベースを配置するための仮想ネットワークを作成する ～
## 変数設定
```bash:コマンド
# VPC名
VPC_NAME="handson-user1" \
&& echo ${VPC_NAME}

# 第1アベイラビリティーゾーンのパブリックサブネット名
AZ1_PUB_NAME="パブリックサブネット-1a" \
&& echo ${AZ1_PUB_NAME}

# 第2アベイラビリティーゾーンのパブリックサブネット名
AZ2_PUB_NAME="パブリックサブネット-1c" \
&& echo ${AZ2_PUB_NAME}

# 第1アベイラビリティーゾーンのプライベートサブネット名
AZ1_PRI_NAME="プライベートサブネット-1a" \
&& echo ${AZ1_PRI_NAME}

# 第2アベイラビリティーゾーンのプライベートサブネット名
AZ2_PRI_NAME="プライベートサブネット-1c" \
&& echo ${AZ2_PRI_NAME}

# IPv4 CIDR ブロック
VPC_CIDR_BLOCK="10.0.0.0/16" \
&& echo ${VPC_CIDR_BLOCK}

# 第1アベイラビリティーゾーンのパブリックサブネットCIDRブロック
AZ1_PUB_CIDR_BLOCK="10.0.0.0/24" \
&& echo ${AZ1_PUB_CIDR_BLOCK}

# 第2アベイラビリティーゾーンのパブリックサブネットCIDRブロック
AZ2_PUB_CIDR_BLOCK="10.0.1.0/24" \
&& echo ${AZ2_PUB_CIDR_BLOCK}

# 第1アベイラビリティーゾーンのプライベートサブネットCIDRブロック
AZ1_PRI_CIDR_BLOCK="10.0.2.0/24" \
&& echo ${AZ1_PRI_CIDR_BLOCK}

# 第2アベイラビリティーゾーンのプライベートサブネットCIDRブロック
AZ2_PRI_CIDR_BLOCK="10.0.3.0/24" \
&& echo ${AZ2_PRI_CIDR_BLOCK}

# アベイラビリティーゾーン
AZ_1="ap-northeast-1a" \
&& echo ${AZ_1}

AZ_2="ap-northeast-1c" \
&& echo ${AZ_1}

# インターネットゲートウェイ名
IGW_NAME=${VPC_NAME}-igw \
&& echo ${IGW_NAME}

# パブリックルートテーブル名
PUB_RT_NAME=${VPC_NAME}-rtb-public \
&& echo ${PUB_RT_NAME}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # VPC名
[cloudshell-user@ip-10-132-84-39 ~]$ VPC_NAME="handson-user1" \
> && echo ${VPC_NAME}
handson-user1
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第1アベイラビリティーゾーンのパブリックサブネット名
[cloudshell-user@ip-10-132-84-39 ~]$ AZ1_PUB_NAME="パブリックサブネット-1a" \
> && echo ${AZ1_PUB_NAME}
パブリックサブネット-1a
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第2アベイラビリティーゾーンのパブリックサブネット名
[cloudshell-user@ip-10-132-84-39 ~]$ AZ2_PUB_NAME="パブリックサブネット-1c" \
> && echo ${AZ2_PUB_NAME}
パブリックサブネット-1c
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第1アベイラビリティーゾーンのプライベートサブネット名
[cloudshell-user@ip-10-132-84-39 ~]$ AZ1_PRI_NAME="プライベートサブネット-1a" \
> && echo ${AZ1_PRI_NAME}
プライベートサブネット-1a
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第2アベイラビリティーゾーンのプライベートサブネット名
[cloudshell-user@ip-10-132-84-39 ~]$ AZ2_PRI_NAME="プライベートサブネット-1c" \
> && echo ${AZ2_PRI_NAME}
プライベートサブネット-1c
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # IPv4 CIDR ブロック
[cloudshell-user@ip-10-132-84-39 ~]$ VPC_CIDR_BLOCK="10.0.0.0/16" \
> && echo ${VPC_CIDR_BLOCK}
10.0.0.0/16
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第1アベイラビリティーゾーンのパブリックサブネットCIDRブロック
[cloudshell-user@ip-10-132-84-39 ~]$ AZ1_PUB_CIDR_BLOCK="10.0.0.0/24" \
> && echo ${AZ1_PUB_CIDR_BLOCK}
10.0.0.0/24
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第2アベイラビリティーゾーンのパブリックサブネットCIDRブロック
[cloudshell-user@ip-10-132-84-39 ~]$ AZ2_PUB_CIDR_BLOCK="10.0.1.0/24" \
> && echo ${AZ2_PUB_CIDR_BLOCK}
10.0.1.0/24
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第1アベイラビリティーゾーンのプライベートサブネットCIDRブロック
[cloudshell-user@ip-10-132-84-39 ~]$ AZ1_PRI_CIDR_BLOCK="10.0.2.0/24" \
> && echo ${AZ1_PRI_CIDR_BLOCK}
10.0.2.0/24
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第2アベイラビリティーゾーンのプライベートサブネットCIDRブロック
[cloudshell-user@ip-10-132-84-39 ~]$ AZ2_PRI_CIDR_BLOCK="10.0.3.0/24" \
> && echo ${AZ2_PRI_CIDR_BLOCK}
10.0.3.0/24
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # アベイラビリティーゾーン
[cloudshell-user@ip-10-132-84-39 ~]$ AZ_1="ap-northeast-1a" \
> && echo ${AZ_1}
ap-northeast-1a
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ AZ_2="ap-northeast-1c" \
> && echo ${AZ_1}
ap-northeast-1a
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # インターネットゲートウェイ名
[cloudshell-user@ip-10-132-84-39 ~]$ IGW_NAME=${VPC_NAME}-igw \
> && echo ${IGW_NAME}
handson-user1-igw
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # パブリックルートテーブル名
[cloudshell-user@ip-10-132-84-39 ~]$ PUB_RT_NAME=${VPC_NAME}-rtb-public \
> && echo ${PUB_RT_NAME}
handson-user1-rtb-public
```
## VPC作成
### 作成
```bash:コマンド
# VPC作成
aws ec2 create-vpc \
    --cidr-block ${VPC_CIDR_BLOCK} \
    --tag-specifications "ResourceType=vpc,Tags=[{Key=Name,Value=${VPC_NAME}}]"

# ID取得
VPC_ID=$(
    aws ec2 describe-vpcs \
        --filters "Name=tag:Name,Values=${VPC_NAME}" \
        --query "Vpcs[0].VpcId" \
        --output text\
)\
&& echo ${VPC_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # VPC作成
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 create-vpc \
>     --cidr-block ${VPC_CIDR_BLOCK} \
>     --tag-specifications "ResourceType=vpc,Tags=[{Key=Name,Value=${VPC_NAME}}]"
{
    "Vpc": {
        "CidrBlock": "10.0.0.0/16",
        "DhcpOptionsId": "dopt-0e7d97fbb33a62ce1",
        "State": "pending",
        "VpcId": "vpc-02b5fbe797028d4e8",
        "OwnerId": "999999999999",
        "InstanceTenancy": "default",
        "Ipv6CidrBlockAssociationSet": [],
        "CidrBlockAssociationSet": [
            {
                "AssociationId": "vpc-cidr-assoc-0a45cdae866f69969",
                "CidrBlock": "10.0.0.0/16",
                "CidrBlockState": {
                    "State": "associated"
                }
            }
        ],
        "IsDefault": false,
        "Tags": [
            {
                "Key": "Name",
                "Value": "handson-user1"
            }
        ]
    }
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ID取得
[cloudshell-user@ip-10-132-84-39 ~]$ VPC_ID=$(
>     aws ec2 describe-vpcs \
>         --filters "Name=tag:Name,Values=${VPC_NAME}" \
>         --query "Vpcs[0].VpcId" \
>         --output text\
> )\
> && echo ${VPC_ID}
vpc-02b5fbe797028d4e8
```
## サブネット作成
```bash:コマンド
# 第1アベイラビリティーゾーンのパブリックサブネット
aws ec2 create-subnet \
    --vpc-id ${VPC_ID} \
    --cidr-block ${AZ1_PUB_CIDR_BLOCK} \
    --availability-zone ${AZ_1} \
    --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${AZ1_PUB_NAME}}]"

# 第2アベイラビリティーゾーンのパブリックサブネット
aws ec2 create-subnet \
    --vpc-id ${VPC_ID} \
    --cidr-block ${AZ2_PUB_CIDR_BLOCK} \
    --availability-zone ${AZ_2} \
    --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${AZ2_PUB_NAME}}]"

# 第1アベイラビリティーゾーンのプライベートサブネット
aws ec2 create-subnet \
    --vpc-id ${VPC_ID} \
    --cidr-block ${AZ1_PRI_CIDR_BLOCK} \
    --availability-zone ${AZ_1} \
    --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${AZ1_PRI_NAME}}]"

# 第2アベイラビリティーゾーンのプライベートサブネット
aws ec2 create-subnet \
    --vpc-id ${VPC_ID} \
    --cidr-block ${AZ2_PRI_CIDR_BLOCK} \
    --availability-zone ${AZ_2} \
    --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${AZ2_PRI_NAME}}]"

# ID取得
# 第1アベイラビリティーゾーンのパブリックサブネット
AZ1_PUB_ID=$( \
    aws ec2 describe-subnets \
      --filters Name=vpc-id,Values=${VPC_ID} \
                Name=tag:Name,Values="${AZ1_PUB_NAME}" \
      --query "Subnets[].SubnetId" \
      --output text \
) \
&& echo ${AZ1_PUB_ID}

# 第2アベイラビリティーゾーンのパブリックサブネット
AZ2_PUB_ID=$( \
    aws ec2 describe-subnets \
      --filters Name=vpc-id,Values=${VPC_ID} \
                Name=tag:Name,Values="${AZ2_PUB_NAME}" \
      --query "Subnets[].SubnetId" \
      --output text \
) \
&& echo ${AZ2_PUB_ID}

# 第1アベイラビリティーゾーンのプライベートサブネット
AZ1_PRI_ID=$( \
    aws ec2 describe-subnets \
      --filters Name=vpc-id,Values=${VPC_ID} \
                Name=tag:Name,Values="${AZ1_PRI_NAME}" \
      --query "Subnets[].SubnetId" \
      --output text \
) \
&& echo ${AZ1_PRI_ID}

# 第2アベイラビリティーゾーンのプライベートサブネット
AZ2_PRI_ID=$( \
    aws ec2 describe-subnets \
      --filters Name=vpc-id,Values=${VPC_ID} \
                Name=tag:Name,Values="${AZ2_PRI_NAME}" \
      --query "Subnets[].SubnetId" \
      --output text \
) \
&& echo ${AZ2_PRI_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # 第1アベイラビリティーゾーンのパブリックサブネット
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 create-subnet \
>     --vpc-id ${VPC_ID} \
>     --cidr-block ${AZ1_PUB_CIDR_BLOCK} \
>     --availability-zone ${AZ_1} \
>     --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${AZ1_PUB_NAME}}]"
{
    "Subnet": {
        "AvailabilityZone": "ap-northeast-1a",
        "AvailabilityZoneId": "apne1-az4",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.0.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-09ce509c9397d5932",
        "VpcId": "vpc-02b5fbe797028d4e8",
        "OwnerId": "999999999999",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [],
        "Tags": [
            {
                "Key": "Name",
                "Value": "パブリックサブネット-1a"
            }
        ],
        "SubnetArn": "arn:aws:ec2:ap-northeast-1:999999999999:subnet/subnet-09ce509c9397d5932",
        "EnableDns64": false,
        "Ipv6Native": false,
        "PrivateDnsNameOptionsOnLaunch": {
            "HostnameType": "ip-name",
            "EnableResourceNameDnsARecord": false,
            "EnableResourceNameDnsAAAARecord": false
        }
    }
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第2アベイラビリティーゾーンのパブリックサブネット
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 create-subnet \
>     --vpc-id ${VPC_ID} \
>     --cidr-block ${AZ2_PUB_CIDR_BLOCK} \
>     --availability-zone ${AZ_2} \
>     --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${AZ2_PUB_NAME}}]"
{
    "Subnet": {
        "AvailabilityZone": "ap-northeast-1c",
        "AvailabilityZoneId": "apne1-az1",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.1.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-0d31beb3e7dd1140d",
        "VpcId": "vpc-02b5fbe797028d4e8",
        "OwnerId": "999999999999",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [],
        "Tags": [
            {
                "Key": "Name",
                "Value": "パブリックサブネット-1c"
            }
        ],
        "SubnetArn": "arn:aws:ec2:ap-northeast-1:999999999999:subnet/subnet-0d31beb3e7dd1140d",
        "EnableDns64": false,
        "Ipv6Native": false,
        "PrivateDnsNameOptionsOnLaunch": {
            "HostnameType": "ip-name",
            "EnableResourceNameDnsARecord": false,
            "EnableResourceNameDnsAAAARecord": false
        }
    }
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第1アベイラビリティーゾーンのプライベートサブネット
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 create-subnet \
>     --vpc-id ${VPC_ID} \
>     --cidr-block ${AZ1_PRI_CIDR_BLOCK} \
>     --availability-zone ${AZ_1} \
>     --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${AZ1_PRI_NAME}}]"
{
    "Subnet": {
        "AvailabilityZone": "ap-northeast-1a",
        "AvailabilityZoneId": "apne1-az4",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.2.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-04ef02ee504c79f77",
        "VpcId": "vpc-02b5fbe797028d4e8",
        "OwnerId": "999999999999",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [],
        "Tags": [
            {
                "Key": "Name",
                "Value": "プライベートサブネット-1a"
            }
        ],
        "SubnetArn": "arn:aws:ec2:ap-northeast-1:999999999999:subnet/subnet-04ef02ee504c79f77",
        "EnableDns64": false,
        "Ipv6Native": false,
        "PrivateDnsNameOptionsOnLaunch": {
            "HostnameType": "ip-name",
            "EnableResourceNameDnsARecord": false,
            "EnableResourceNameDnsAAAARecord": false
        }
    }
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第2アベイラビリティーゾーンのプライベートサブネット
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 create-subnet \
>     --vpc-id ${VPC_ID} \
>     --cidr-block ${AZ2_PRI_CIDR_BLOCK} \
>     --availability-zone ${AZ_2} \
>     --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${AZ2_PRI_NAME}}]"
{
    "Subnet": {
        "AvailabilityZone": "ap-northeast-1c",
        "AvailabilityZoneId": "apne1-az1",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.3.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-06ddf6a468a549ff8",
        "VpcId": "vpc-02b5fbe797028d4e8",
        "OwnerId": "999999999999",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [],
        "Tags": [
            {
                "Key": "Name",
                "Value": "プライベートサブネット-1c"
            }
        ],
        "SubnetArn": "arn:aws:ec2:ap-northeast-1:999999999999:subnet/subnet-06ddf6a468a549ff8",
        "EnableDns64": false,
        "Ipv6Native": false,
        "PrivateDnsNameOptionsOnLaunch": {
            "HostnameType": "ip-name",
            "EnableResourceNameDnsARecord": false,
            "EnableResourceNameDnsAAAARecord": false
        }
    }
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ID取得
[cloudshell-user@ip-10-132-84-39 ~]$ # 第1アベイラビリティーゾーンのパブリックサブネット
[cloudshell-user@ip-10-132-84-39 ~]$ AZ1_PUB_ID=$( \
>     aws ec2 describe-subnets \
>       --filters Name=vpc-id,Values=${VPC_ID} \
>                 Name=tag:Name,Values="${AZ1_PUB_NAME}" \
>       --query "Subnets[].SubnetId" \
>       --output text \
> ) \
> && echo ${AZ1_PUB_ID}
subnet-09ce509c9397d5932
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第2アベイラビリティーゾーンのパブリックサブネット
[cloudshell-user@ip-10-132-84-39 ~]$ AZ2_PUB_ID=$( \
>     aws ec2 describe-subnets \
>       --filters Name=vpc-id,Values=${VPC_ID} \
>                 Name=tag:Name,Values="${AZ2_PUB_NAME}" \
>       --query "Subnets[].SubnetId" \
>       --output text \
> ) \
> && echo ${AZ2_PUB_ID}
subnet-0d31beb3e7dd1140d
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第1アベイラビリティーゾーンのプライベートサブネット
[cloudshell-user@ip-10-132-84-39 ~]$ AZ1_PRI_ID=$( \
>     aws ec2 describe-subnets \
>       --filters Name=vpc-id,Values=${VPC_ID} \
>                 Name=tag:Name,Values="${AZ1_PRI_NAME}" \
>       --query "Subnets[].SubnetId" \
>       --output text \
> ) \
> && echo ${AZ1_PRI_ID}
subnet-04ef02ee504c79f77
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 第2アベイラビリティーゾーンのプライベートサブネット
[cloudshell-user@ip-10-132-84-39 ~]$ AZ2_PRI_ID=$( \
>     aws ec2 describe-subnets \
>       --filters Name=vpc-id,Values=${VPC_ID} \
>                 Name=tag:Name,Values="${AZ2_PRI_NAME}" \
>       --query "Subnets[].SubnetId" \
>       --output text \
> ) \
> && echo ${AZ2_PRI_ID}
subnet-06ddf6a468a549ff8
```
## インターネットゲートウェイ作成
```bash:コマンド
# インターネットゲートウェイ作成
aws ec2 create-internet-gateway \
    --tag-specifications "ResourceType=internet-gateway,Tags=[{Key=Name,Value=${IGW_NAME}}]"

# インターネットゲートウェイID取得
IGW_ID=$(
    aws ec2 describe-internet-gateways \
        --filters Name=tag:Name,Values=${IGW_NAME} \
        --query "InternetGateways[].InternetGatewayId" \
        --output text
) \
&& echo ${IGW_ID}

# インターネットゲートウェイをVPCにアタッチ
aws ec2 attach-internet-gateway \
    --vpc-id ${VPC_ID} \
    --internet-gateway-id ${IGW_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # インターネットゲートウェイ作成
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 create-internet-gateway \
>     --tag-specifications "ResourceType=internet-gateway,Tags=[{Key=Name,Value=${IGW_NAME}}]"
{
    "InternetGateway": {
        "Attachments": [],
        "InternetGatewayId": "igw-0bc2bedb86a7c059b",
        "OwnerId": "999999999999",
        "Tags": [
            {
                "Key": "Name",
                "Value": "handson-user1-igw"
            }
        ]
    }
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # インターネットゲートウェイID取得
[cloudshell-user@ip-10-132-84-39 ~]$ IGW_ID=$(
>     aws ec2 describe-internet-gateways \
>         --filters Name=tag:Name,Values=${IGW_NAME} \
>         --query "InternetGateways[].InternetGatewayId" \
>         --output text
> ) \
> && echo ${IGW_ID}
igw-0bc2bedb86a7c059b
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # インターネットゲートウェイをVPCにアタッチ
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 attach-internet-gateway \
>     --vpc-id ${VPC_ID} \
>     --internet-gateway-id ${IGW_ID}
```
## ルートテーブル作成
```bash:コマンド
# ルートテーブル作成
aws ec2 create-route-table \
    --vpc-id ${VPC_ID} \
    --tag-specifications "ResourceType=route-table,Tags=[{Key=Name,Value=${PUB_RT_NAME}}]"

# ルートテーブルID取得
PUB_RT_ID=$(
    aws ec2 describe-route-tables \
        --filters Name=vpc-id,Values=${VPC_ID} \
                  Name=tag:Name,Values="${PUB_RT_NAME}" \
        --query "RouteTables[].RouteTableId" \
        --output text
) \
&& echo ${PUB_RT_ID}

# デフォルトルート作成
aws ec2 create-route \
    --route-table-id ${PUB_RT_ID} \
    --destination-cidr-block 0.0.0.0/0 \
    --gateway-id ${IGW_ID}

# サブネット関連付け
aws ec2 associate-route-table \
    --subnet-id ${AZ1_PUB_ID} \
    --route-table-id ${PUB_RT_ID}

aws ec2 associate-route-table \
    --subnet-id ${AZ2_PUB_ID} \
    --route-table-id ${PUB_RT_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ルートテーブル作成
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 create-route-table \
>     --vpc-id ${VPC_ID} \
>     --tag-specifications "ResourceType=route-table,Tags=[{Key=Name,Value=${PUB_RT_NAME}}]"
{
    "RouteTable": {
        "Associations": [],
        "PropagatingVgws": [],
        "RouteTableId": "rtb-051e6d5d9d55a2d2a",
        "Routes": [
            {
                "DestinationCidrBlock": "10.0.0.0/16",
                "GatewayId": "local",
                "Origin": "CreateRouteTable",
                "State": "active"
            }
        ],
        "Tags": [
            {
                "Key": "Name",
                "Value": "handson-user1-rtb-public"
            }
        ],
        "VpcId": "vpc-02b5fbe797028d4e8",
        "OwnerId": "999999999999"
    },
    "ClientToken": "1649375e-0e85-4830-b5d4-a4852f2e27eb"
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ルートテーブルID取得
[cloudshell-user@ip-10-132-84-39 ~]$ PUB_RT_ID=$(
>     aws ec2 describe-route-tables \
>         --filters Name=vpc-id,Values=${VPC_ID} \
>                   Name=tag:Name,Values="${PUB_RT_NAME}" \
>         --query "RouteTables[].RouteTableId" \
>         --output text
> ) \
> && echo ${PUB_RT_ID}
rtb-051e6d5d9d55a2d2a
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # デフォルトルート作成
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 create-route \
>     --route-table-id ${PUB_RT_ID} \
>     --destination-cidr-block 0.0.0.0/0 \
>     --gateway-id ${IGW_ID}
{
    "Return": true
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # サブネット関連付け
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 associate-route-table \
>     --subnet-id ${AZ1_PUB_ID} \
>     --route-table-id ${PUB_RT_ID}
{
    "AssociationId": "rtbassoc-06a12f53a757f34d7",
    "AssociationState": {
        "State": "associated"
    }
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 associate-route-table \
>     --subnet-id ${AZ2_PUB_ID} \
>     --route-table-id ${PUB_RT_ID}
{
    "AssociationId": "rtbassoc-0e33b19b48ec49eec",
    "AssociationState": {
        "State": "associated"
    }
}
```
# 2. 03 Amazon EC2の作成 ～ WordPressがインストールされたWebサーバを作成する ～
## 変数
```bash:コマンド
# EC2インスタンス名 1
EC2_NAME_1="webserver#1-user1" \
&& echo ${EC2_NAME_1}

# インスタンスタイプ
EC2_INSTANCE_TYPE="t2.micro" \
&& echo ${EC2_INSTANCE_TYPE}

# Amazon マシンイメージ (AMI)
EC2_IMAGE_ID="resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2" \
&& echo ${EC2_IMAGE_ID}

# EC2セキュリティグループ名
EC2_SECURITY_GROUP_NAME='web-user1' \
&& echo ${EC2_SECURITY_GROUP_NAME}

# EC2セキュリティグループ説明
EC2_SECURITY_GROUP_DESCRIPTION='web-user1' \
&& echo ${EC2_SECURITY_GROUP_DESCRIPTION}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # EC2インスタンス名 1
[cloudshell-user@ip-10-132-84-39 ~]$ EC2_NAME_1="webserver#1-user1" \
> && echo ${EC2_NAME_1}
webserver#1-user1
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # インスタンスタイプ
[cloudshell-user@ip-10-132-84-39 ~]$ EC2_INSTANCE_TYPE="t2.micro" \
> && echo ${EC2_INSTANCE_TYPE}
t2.micro
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # Amazon マシンイメージ (AMI)
[cloudshell-user@ip-10-132-84-39 ~]$ EC2_IMAGE_ID="resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2" \
> && echo ${EC2_IMAGE_ID}
resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # EC2セキュリティグループ名
[cloudshell-user@ip-10-132-84-39 ~]$ EC2_SECURITY_GROUP_NAME='web-user1' \
> && echo ${EC2_SECURITY_GROUP_NAME}
web-user1
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # EC2セキュリティグループ説明
[cloudshell-user@ip-10-132-84-39 ~]$ EC2_SECURITY_GROUP_DESCRIPTION='web-user1' \
> && echo ${EC2_SECURITY_GROUP_DESCRIPTION}
web-user1
```
## セキュリティグループ作成
### セキュリティグループ作成
```bash:コマンド
# セキュリティグループ作成
aws ec2 create-security-group \
    --group-name ${EC2_SECURITY_GROUP_NAME} \
    --description ${EC2_SECURITY_GROUP_DESCRIPTION} \
    --vpc-id ${VPC_ID}

# ID取得
EC2_SECURITY_GROUP_ID=$( \
    aws ec2 describe-security-groups \
        --filters Name=vpc-id,Values=${VPC_ID} \
                  Name=group-name,Values=${EC2_SECURITY_GROUP_NAME} \
        --query "SecurityGroups[].GroupId" \
        --output text \
) \
&& echo ${EC2_SECURITY_GROUP_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # セキュリティグループ作成
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 create-security-group \
>     --group-name ${EC2_SECURITY_GROUP_NAME} \
>     --description ${EC2_SECURITY_GROUP_DESCRIPTION} \
>     --vpc-id ${VPC_ID}
{
    "GroupId": "sg-0f13aa5ebac4e8118"
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ID取得
[cloudshell-user@ip-10-132-84-39 ~]$ EC2_SECURITY_GROUP_ID=$( \
>     aws ec2 describe-security-groups \
>         --filters Name=vpc-id,Values=${VPC_ID} \
>                   Name=group-name,Values=${EC2_SECURITY_GROUP_NAME} \
>         --query "SecurityGroups[].GroupId" \
>         --output text \
> ) \
> && echo ${EC2_SECURITY_GROUP_ID}
sg-0f13aa5ebac4e8118
```
### ルール追加
```bash:コマンド
# ルール追加
aws ec2 authorize-security-group-ingress \
    --group-id ${EC2_SECURITY_GROUP_ID} \
    --protocol tcp \
    --port 22 \
    --cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress \
    --group-id ${EC2_SECURITY_GROUP_ID} \
    --protocol tcp \
    --port 80 \
    --cidr 0.0.0.0/0

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ルール追加
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 authorize-security-group-ingress \
>     --group-id ${EC2_SECURITY_GROUP_ID} \
>     --protocol tcp \
>     --port 22 \
>     --cidr 0.0.0.0/0
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-07ceea7e3395ffb73",
            "GroupId": "sg-0f13aa5ebac4e8118",
            "GroupOwnerId": "999999999999",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 22,
            "ToPort": 22,
            "CidrIpv4": "0.0.0.0/0"
        }
    ]
}
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 authorize-security-group-ingress \
>     --group-id ${EC2_SECURITY_GROUP_ID} \
>     --protocol tcp \
>     --port 80 \
>     --cidr 0.0.0.0/0
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-021c732d1c3d1cb17",
            "GroupId": "sg-0f13aa5ebac4e8118",
            "GroupOwnerId": "999999999999",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 80,
            "ToPort": 80,
            "CidrIpv4": "0.0.0.0/0"
        }
    ]
}
```
## EC2作成
### ユーザーデータ作成(ヒアドキュメント)
※スクリプトはハンズオンから引用
```bash:コマンド
cat << 'EOF' > user_data.txt
#!/bin/bash

yum -y update
yum -y install php httpd mysql

PHP_VERSION=`php -v | head -n 1 | awk '{print $2}' | awk -F "." '{print $1}'`
while [  ${PHP_VERSION} -ne 7 ]
do
amazon-linux-extras install php7.4 -y
PHP_VERSION=`php -v | head -n 1 | awk '{print $2}' | awk -F "." '{print $1}'`
done

yum -y install php-mbstring php-xml

wget http://ja.wordpress.org/latest-ja.tar.gz -P /tmp/
tar zxvf /tmp/latest-ja.tar.gz -C /tmp
cp -r /tmp/wordpress/* /var/www/html/
chown apache:apache -R /var/www/html

systemctl enable httpd.service
systemctl start httpd.service
EOF

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ cat << 'EOF' > user_data.txt
> #!/bin/bash
> 
> yum -y update
> yum -y install php httpd mysql
> 
> PHP_VERSION=`php -v | head -n 1 | awk '{print $2}' | awk -F "." '{print $1}'`
> while [  ${PHP_VERSION} -ne 7 ]
> do
> amazon-linux-extras install php7.4 -y
> PHP_VERSION=`php -v | head -n 1 | awk '{print $2}' | awk -F "." '{print $1}'`
> done
> 
> yum -y install php-mbstring php-xml
> 
> wget http://ja.wordpress.org/latest-ja.tar.gz -P /tmp/
> tar zxvf /tmp/latest-ja.tar.gz -C /tmp
> cp -r /tmp/wordpress/* /var/www/html/
> chown apache:apache -R /var/www/html
> 
> systemctl enable httpd.service
> systemctl start httpd.service
> EOF
```
### EC2作成
```bash:コマンド
# EC2インスタンス作成
aws ec2 run-instances \
    --image-id ${EC2_IMAGE_ID} \
    --instance-type ${EC2_INSTANCE_TYPE} \
    --security-group-ids ${EC2_SECURITY_GROUP_ID} \
    --subnet-id ${AZ1_PUB_ID} \
    --associate-public-ip-address \
    --user-data file://user_data.txt \
    --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${EC2_NAME_1}}]" \
    --no-cli-pager

# インスタンスID
EC2_ID_1=$( \
    aws ec2 describe-instances \
        --filters Name=tag:Name,Values=${EC2_NAME_1}  \
        --query "Reservations[*].Instances[*].[InstanceId]" \
        --output text
) \
&& echo ${EC2_ID_1}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # EC2インスタンス作成
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 run-instances \
>     --image-id ${EC2_IMAGE_ID} \
>     --instance-type ${EC2_INSTANCE_TYPE} \
>     --security-group-ids ${EC2_SECURITY_GROUP_ID} \
>     --subnet-id ${AZ1_PUB_ID} \
>     --associate-public-ip-address \
>     --user-data file://user_data.txt \
>     --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${EC2_NAME_1}}]" \
>     --no-cli-pager
{
    "Groups": [],
    "Instances": [
        {
            "AmiLaunchIndex": 0,
            "ImageId": "ami-07281c2a30e5bc1ab",
            "InstanceId": "i-0ed3b54d25b834102",
            "InstanceType": "t2.micro",
            "LaunchTime": "2024-08-25T09:30:45+00:00",
            "Monitoring": {
                "State": "disabled"
            },
            "Placement": {
                "AvailabilityZone": "ap-northeast-1a",
                "GroupName": "",
                "Tenancy": "default"
            },
            "PrivateDnsName": "ip-10-0-0-6.ap-northeast-1.compute.internal",
            "PrivateIpAddress": "10.0.0.6",
            "ProductCodes": [],
            "PublicDnsName": "",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "StateTransitionReason": "",
            "SubnetId": "subnet-09ce509c9397d5932",
            "VpcId": "vpc-02b5fbe797028d4e8",
            "Architecture": "x86_64",
            "BlockDeviceMappings": [],
            "ClientToken": "d47d36a4-8ec1-4a44-a809-5f8958c4f5d1",
            "EbsOptimized": false,
            "EnaSupport": true,
            "Hypervisor": "xen",
            "NetworkInterfaces": [
                {
                    "Attachment": {
                        "AttachTime": "2024-08-25T09:30:45+00:00",
                        "AttachmentId": "eni-attach-07f3f68205eb1c46b",
                        "DeleteOnTermination": true,
                        "DeviceIndex": 0,
                        "Status": "attaching",
                        "NetworkCardIndex": 0
                    },
                    "Description": "",
                    "Groups": [
                        {
                            "GroupName": "web-user1",
                            "GroupId": "sg-0f13aa5ebac4e8118"
                        }
                    ],
                    "Ipv6Addresses": [],
                    "MacAddress": "06:96:9d:da:85:7b",
                    "NetworkInterfaceId": "eni-0f0b55cacbdf977b8",
                    "OwnerId": "999999999999",
                    "PrivateIpAddress": "10.0.0.6",
                    "PrivateIpAddresses": [
                        {
                            "Primary": true,
                            "PrivateIpAddress": "10.0.0.6"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Status": "in-use",
                    "SubnetId": "subnet-09ce509c9397d5932",
                    "VpcId": "vpc-02b5fbe797028d4e8",
                    "InterfaceType": "interface"
                }
            ],
            "RootDeviceName": "/dev/xvda",
            "RootDeviceType": "ebs",
            "SecurityGroups": [
                {
                    "GroupName": "web-user1",
                    "GroupId": "sg-0f13aa5ebac4e8118"
                }
            ],
            "SourceDestCheck": true,
            "StateReason": {
                "Code": "pending",
                "Message": "pending"
            },
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "webserver#1-user1"
                }
            ],
            "VirtualizationType": "hvm",
            "CpuOptions": {
                "CoreCount": 1,
                "ThreadsPerCore": 1
            },
            "CapacityReservationSpecification": {
                "CapacityReservationPreference": "open"
            },
            "MetadataOptions": {
                "State": "pending",
                "HttpTokens": "optional",
                "HttpPutResponseHopLimit": 1,
                "HttpEndpoint": "enabled",
                "HttpProtocolIpv6": "disabled",
                "InstanceMetadataTags": "disabled"
            },
            "EnclaveOptions": {
                "Enabled": false
            },
            "PrivateDnsNameOptions": {
                "HostnameType": "ip-name",
                "EnableResourceNameDnsARecord": false,
                "EnableResourceNameDnsAAAARecord": false
            },
            "MaintenanceOptions": {
                "AutoRecovery": "default"
            },
            "CurrentInstanceBootMode": "legacy-bios"
        }
    ],
    "OwnerId": "999999999999",
    "ReservationId": "r-0c5a6693ae8fcc07e"
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # インスタンスID
[cloudshell-user@ip-10-132-84-39 ~]$ EC2_ID_1=$( \
>     aws ec2 describe-instances \
>         --filters Name=tag:Name,Values=${EC2_NAME_1}  \
>         --query "Reservations[*].Instances[*].[InstanceId]" \
>         --output text
> ) \
> && echo ${EC2_ID_1}
i-0ed3b54d25b834102
```
# 3. 04 Amazon RDSの作成 ～ WordPress用のMySQLデータベースを作成する～
## 変数設定
```bash:コマンド
# DBセキュリティグループ名
# DBセキュリティグループ名
RDS_SG_NAME='db-user1' \
&& echo ${RDS_SG_NAME}

# DBセキュリティグループ説明
RDS_SG_DESC='RDS for MySQL' \
&& echo ${RDS_SG_DESC}

# サブネットグループ名
DB_SUBNET_GROUP_NAME='db-subnet-user1' \
&& echo ${DB_SUBNET_GROUP_NAME}

# サブネットグループ説明
DB_SUBNET_GROUP_DESC='RDS for MySQL' \
&& echo ${DB_SUBNET_GROUP_DESC}

# DB インスタンス識別子
DB_INSTANCE_IDENTIFIER='db-user1' \
&& echo ${DB_INSTANCE_IDENTIFIER}

# 最初のデータベース名
DB_NAME="wordpress" \
&& echo ${DB_NAME}

# インスタンスクラス
DB_INSTANCE_CLASS="db.t3.micro" \
&& echo ${DB_INSTANCE_CLASS}

# エンジンのタイプ
ENGINE="mysql" \
&& echo ${ENGINE}

# マスターユーザー名
MASTER_USERNAME="admin" \
&& echo ${MASTER_USERNAME}

# マスターパスワード
MASTER_USER_PASSWORD=$(< /dev/urandom tr -dc 'A-Za-z0-9' | head -c12) \
&& echo ${MASTER_USER_PASSWORD}

# ストレージ割り当て
ALLOCATED_STORAGE=20 \
&& echo ${ALLOCATED_STORAGE}

# 最大ストレージしきい値
MAX_ALLOCATED_STORAGE=1000 \
&& echo ${MAX_ALLOCATED_STORAGE}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # DBセキュリティグループ名
[cloudshell-user@ip-10-132-84-39 ~]$ RDS_SG_NAME='db-user1' \
> && echo ${RDS_SG_NAME}
db-user1
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # DBセキュリティグループ説明
[cloudshell-user@ip-10-132-84-39 ~]$ RDS_SG_DESC='RDS for MySQL' \
> && echo ${RDS_SG_DESC}
RDS for MySQL
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # サブネットグループ名
[cloudshell-user@ip-10-132-84-39 ~]$ DB_SUBNET_GROUP_NAME='db-subnet-user1' \
> && echo ${DB_SUBNET_GROUP_NAME}
db-subnet-user1
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # サブネットグループ説明
[cloudshell-user@ip-10-132-84-39 ~]$ DB_SUBNET_GROUP_DESC='RDS for MySQL' \
> && echo ${DB_SUBNET_GROUP_DESC}
RDS for MySQL
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # DB インスタンス識別子
[cloudshell-user@ip-10-132-84-39 ~]$ DB_INSTANCE_IDENTIFIER='db-user1' \
> && echo ${DB_INSTANCE_IDENTIFIER}
db-user1
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 最初のデータベース名
[cloudshell-user@ip-10-132-84-39 ~]$ DB_NAME="wordpress" \
> && echo ${DB_NAME}
wordpress
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # インスタンスクラス
[cloudshell-user@ip-10-132-84-39 ~]$ DB_INSTANCE_CLASS="db.t3.micro" \
> && echo ${DB_INSTANCE_CLASS}
db.t3.micro
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # エンジンのタイプ
[cloudshell-user@ip-10-132-84-39 ~]$ ENGINE="mysql" \
> && echo ${ENGINE}
mysql
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # マスターユーザー名
[cloudshell-user@ip-10-132-84-39 ~]$ MASTER_USERNAME="admin" \
> && echo ${MASTER_USERNAME}
admin
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # マスターパスワード
[cloudshell-user@ip-10-132-84-39 ~]$ MASTER_USER_PASSWORD=$(< /dev/urandom tr -dc 'A-Za-z0-9' | head -c12) \
> && echo ${MASTER_USER_PASSWORD}
AjO5PqEZI6IX
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ストレージ割り当て
[cloudshell-user@ip-10-132-84-39 ~]$ ALLOCATED_STORAGE=20 \
> && echo ${ALLOCATED_STORAGE}
20
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # 最大ストレージしきい値
[cloudshell-user@ip-10-132-84-39 ~]$ MAX_ALLOCATED_STORAGE=1000 \
> && echo ${MAX_ALLOCATED_STORAGE}
1000
```
## セキュリティグループ作成
### セキュリティグループ作成
```bash:コマンド
# セキュリティグループ作成
aws ec2 create-security-group \
    --group-name ${RDS_SG_NAME} \
    --description "${RDS_SG_DESC}" \
    --vpc-id ${VPC_ID}

# ID取得
RDS_SG_ID=$( \
    aws ec2 describe-security-groups \
        --filters Name=vpc-id,Values=${VPC_ID} \
                  Name=group-name,Values=${RDS_SG_NAME} \
        --query "SecurityGroups[].GroupId" \
        --output text
) \
&& echo ${RDS_SG_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # セキュリティグループ作成
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 create-security-group \
>     --group-name ${RDS_SG_NAME} \
>     --description "${RDS_SG_DESC}" \
>     --vpc-id ${VPC_ID}
{
    "GroupId": "sg-08c2854a9b34f089b"
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ID取得
[cloudshell-user@ip-10-132-84-39 ~]$ RDS_SG_ID=$( \
>     aws ec2 describe-security-groups \
>         --filters Name=vpc-id,Values=${VPC_ID} \
>                   Name=group-name,Values=${RDS_SG_NAME} \
>         --query "SecurityGroups[].GroupId" \
>         --output text
> ) \
> && echo ${RDS_SG_ID}
sg-08c2854a9b34f089b
```
### ルール追加
```bash:コマンド
# ルール追加
aws ec2 authorize-security-group-ingress \
    --group-id ${RDS_SG_ID} \
    --protocol tcp \
    --port 3306 \
    --source-group ${EC2_SECURITY_GROUP_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ルール追加
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 authorize-security-group-ingress \
>     --group-id ${RDS_SG_ID} \
>     --protocol tcp \
>     --port 3306 \
>     --source-group ${EC2_SECURITY_GROUP_ID}
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-00e4182d98008e519",
            "GroupId": "sg-08c2854a9b34f089b",
            "GroupOwnerId": "999999999999",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 3306,
            "ToPort": 3306,
            "ReferencedGroupInfo": {
                "GroupId": "sg-0f13aa5ebac4e8118",
                "UserId": "999999999999"
            }
        }
    ]
}
```
## サブネットグループ作成
```bash:コマンド
aws rds create-db-subnet-group \
    --db-subnet-group-name ${DB_SUBNET_GROUP_NAME} \
    --db-subnet-group-description "${DB_SUBNET_GROUP_DESC}" \
    --subnet-ids ${AZ1_PRI_ID} ${AZ2_PRI_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ aws rds create-db-subnet-group \
>     --db-subnet-group-name ${DB_SUBNET_GROUP_NAME} \
>     --db-subnet-group-description "${DB_SUBNET_GROUP_DESC}" \
>     --subnet-ids ${AZ1_PRI_ID} ${AZ2_PRI_ID}
{
    "DBSubnetGroup": {
        "DBSubnetGroupName": "db-subnet-user1",
        "DBSubnetGroupDescription": "RDS for MySQL",
        "VpcId": "vpc-02b5fbe797028d4e8",
        "SubnetGroupStatus": "Complete",
        "Subnets": [
            {
                "SubnetIdentifier": "subnet-04ef02ee504c79f77",
                "SubnetAvailabilityZone": {
                    "Name": "ap-northeast-1a"
                },
                "SubnetOutpost": {},
                "SubnetStatus": "Active"
            },
            {
                "SubnetIdentifier": "subnet-06ddf6a468a549ff8",
                "SubnetAvailabilityZone": {
                    "Name": "ap-northeast-1c"
                },
                "SubnetOutpost": {},
                "SubnetStatus": "Active"
            }
        ],
        "DBSubnetGroupArn": "arn:aws:rds:ap-northeast-1:999999999999:subgrp:db-subnet-user1",
        "SupportedNetworkTypes": [
            "IPV4"
        ]
    }
}
```
## RDS作成
```bash:コマンド
aws rds create-db-instance \
    --db-name ${DB_NAME} \
    --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
    --allocated-storage ${ALLOCATED_STORAGE} \
    --db-instance-class ${DB_INSTANCE_CLASS} \
    --engine ${ENGINE} \
    --master-username ${MASTER_USERNAME} \
    --master-user-password ${MASTER_USER_PASSWORD} \
    --vpc-security-group-ids ${RDS_SG_ID} \
    --availability-zone ${AZ_1} \
    --db-subnet-group-name ${DB_SUBNET_GROUP_NAME} \
    --backup-retention-period 0 \
    --no-publicly-accessible \
    --max-allocated-storage ${MAX_ALLOCATED_STORAGE} \
    --storage-encrypted \
    --no-cli-pager

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ aws rds create-db-instance \
>     --db-name ${DB_NAME} \
>     --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
>     --allocated-storage ${ALLOCATED_STORAGE} \
>     --db-instance-class ${DB_INSTANCE_CLASS} \
>     --engine ${ENGINE} \
>     --master-username ${MASTER_USERNAME} \
>     --master-user-password ${MASTER_USER_PASSWORD} \
>     --vpc-security-group-ids ${RDS_SG_ID} \
>     --availability-zone ${AZ_1} \
>     --db-subnet-group-name ${DB_SUBNET_GROUP_NAME} \
>     --backup-retention-period 0 \
>     --no-publicly-accessible \
>     --max-allocated-storage ${MAX_ALLOCATED_STORAGE} \
>     --storage-encrypted \
>     --no-cli-pager
{
    "DBInstance": {
        "DBInstanceIdentifier": "db-user1",
        "DBInstanceClass": "db.t3.micro",
        "Engine": "mysql",
        "DBInstanceStatus": "creating",
        "MasterUsername": "admin",
        "DBName": "wordpress",
        "AllocatedStorage": 20,
        "PreferredBackupWindow": "13:43-14:13",
        "BackupRetentionPeriod": 0,
        "DBSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-08c2854a9b34f089b",
                "Status": "active"
            }
        ],
        "DBParameterGroups": [
            {
                "DBParameterGroupName": "default.mysql8.0",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "AvailabilityZone": "ap-northeast-1a",
        "DBSubnetGroup": {
            "DBSubnetGroupName": "db-subnet-user1",
            "DBSubnetGroupDescription": "RDS for MySQL",
            "VpcId": "vpc-02b5fbe797028d4e8",
            "SubnetGroupStatus": "Complete",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-04ef02ee504c79f77",
                    "SubnetAvailabilityZone": {
                        "Name": "ap-northeast-1a"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-06ddf6a468a549ff8",
                    "SubnetAvailabilityZone": {
                        "Name": "ap-northeast-1c"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                }
            ]
        },
        "PreferredMaintenanceWindow": "sun:15:03-sun:15:33",
        "PendingModifiedValues": {
            "MasterUserPassword": "****"
        },
        "MultiAZ": false,
        "EngineVersion": "8.0.35",
        "AutoMinorVersionUpgrade": true,
        "ReadReplicaDBInstanceIdentifiers": [],
        "LicenseModel": "general-public-license",
        "OptionGroupMemberships": [
            {
                "OptionGroupName": "default:mysql-8-0",
                "Status": "in-sync"
            }
        ],
        "PubliclyAccessible": false,
        "StorageType": "gp2",
        "DbInstancePort": 0,
        "StorageEncrypted": true,
        "KmsKeyId": "arn:aws:kms:ap-northeast-1:999999999999:key/951b3fa0-aedb-4215-a2e6-9b7c2f5292e5",
        "DbiResourceId": "db-JLWEZ2TQ2U6TEYZGZWHYZ7R3L4",
        "CACertificateIdentifier": "rds-ca-rsa2048-g1",
        "DomainMemberships": [],
        "CopyTagsToSnapshot": false,
        "MonitoringInterval": 0,
        "DBInstanceArn": "arn:aws:rds:ap-northeast-1:999999999999:db:db-user1",
        "IAMDatabaseAuthenticationEnabled": false,
        "PerformanceInsightsEnabled": false,
        "DeletionProtection": false,
        "AssociatedRoles": [],
        "MaxAllocatedStorage": 1000,
        "TagList": [],
        "CustomerOwnedIpEnabled": false,
        "BackupTarget": "region",
        "NetworkType": "IPV4",
        "StorageThroughput": 0,
        "CertificateDetails": {
            "CAIdentifier": "rds-ca-rsa2048-g1"
        },
        "DedicatedLogVolume": false,
        "EngineLifecycleSupport": "open-source-rds-extended-support"
    }
}
```
## 確認
### 詳細
```bash:コマンド
# 詳細
aws rds describe-db-instances \
    --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
    --no-cli-pager

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # 詳細
[cloudshell-user@ip-10-132-84-39 ~]$ aws rds describe-db-instances \
>     --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
>     --no-cli-pager
{
    "DBInstances": [
        {
            "DBInstanceIdentifier": "db-user1",
            "DBInstanceClass": "db.t3.micro",
            "Engine": "mysql",
            "DBInstanceStatus": "available",
            "MasterUsername": "admin",
            "DBName": "wordpress",
            "Endpoint": {
                "Address": "db-user1.clacqicsiqrt.ap-northeast-1.rds.amazonaws.com",
                "Port": 3306,
                "HostedZoneId": "Z24O6O9L7SGTNB"
            },
            "AllocatedStorage": 20,
            "InstanceCreateTime": "2024-08-25T09:35:37.302000+00:00",
            "PreferredBackupWindow": "13:43-14:13",
            "BackupRetentionPeriod": 0,
            "DBSecurityGroups": [],
            "VpcSecurityGroups": [
                {
                    "VpcSecurityGroupId": "sg-08c2854a9b34f089b",
                    "Status": "active"
                }
            ],
            "DBParameterGroups": [
                {
                    "DBParameterGroupName": "default.mysql8.0",
                    "ParameterApplyStatus": "in-sync"
                }
            ],
            "AvailabilityZone": "ap-northeast-1a",
            "DBSubnetGroup": {
                "DBSubnetGroupName": "db-subnet-user1",
                "DBSubnetGroupDescription": "RDS for MySQL",
                "VpcId": "vpc-02b5fbe797028d4e8",
                "SubnetGroupStatus": "Complete",
                "Subnets": [
                    {
                        "SubnetIdentifier": "subnet-04ef02ee504c79f77",
                        "SubnetAvailabilityZone": {
                            "Name": "ap-northeast-1a"
                        },
                        "SubnetOutpost": {},
                        "SubnetStatus": "Active"
                    },
                    {
                        "SubnetIdentifier": "subnet-06ddf6a468a549ff8",
                        "SubnetAvailabilityZone": {
                            "Name": "ap-northeast-1c"
                        },
                        "SubnetOutpost": {},
                        "SubnetStatus": "Active"
                    }
                ]
            },
            "PreferredMaintenanceWindow": "sun:15:03-sun:15:33",
            "PendingModifiedValues": {},
            "MultiAZ": false,
            "EngineVersion": "8.0.35",
            "AutoMinorVersionUpgrade": true,
            "ReadReplicaDBInstanceIdentifiers": [],
            "LicenseModel": "general-public-license",
            "OptionGroupMemberships": [
                {
                    "OptionGroupName": "default:mysql-8-0",
                    "Status": "in-sync"
                }
            ],
            "PubliclyAccessible": false,
            "StorageType": "gp2",
            "DbInstancePort": 0,
            "StorageEncrypted": true,
            "KmsKeyId": "arn:aws:kms:ap-northeast-1:999999999999:key/951b3fa0-aedb-4215-a2e6-9b7c2f5292e5",
            "DbiResourceId": "db-JLWEZ2TQ2U6TEYZGZWHYZ7R3L4",
            "CACertificateIdentifier": "rds-ca-rsa2048-g1",
            "DomainMemberships": [],
            "CopyTagsToSnapshot": false,
            "MonitoringInterval": 0,
            "DBInstanceArn": "arn:aws:rds:ap-northeast-1:999999999999:db:db-user1",
            "IAMDatabaseAuthenticationEnabled": false,
            "PerformanceInsightsEnabled": false,
            "DeletionProtection": false,
            "AssociatedRoles": [],
            "MaxAllocatedStorage": 1000,
            "TagList": [],
            "CustomerOwnedIpEnabled": false,
            "ActivityStreamStatus": "stopped",
            "BackupTarget": "region",
            "NetworkType": "IPV4",
            "StorageThroughput": 0,
            "CertificateDetails": {
                "CAIdentifier": "rds-ca-rsa2048-g1",
                "ValidTill": "2025-08-25T09:34:46+00:00"
            },
            "DedicatedLogVolume": false,
            "IsStorageConfigUpgradeAvailable": false,
            "EngineLifecycleSupport": "open-source-rds-extended-support"
        }
    ]
}
```
### エンドポイントアドレス
```bash:コマンド
# エンドポイントアドレス
aws rds describe-db-instances \
    --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
    --query DBInstances[].Endpoint.Address \
    --output text

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # エンドポイントアドレス
[cloudshell-user@ip-10-132-84-39 ~]$ aws rds describe-db-instances \
>     --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
>     --query DBInstances[].Endpoint.Address \
>     --output text
db-user1.clacqicsiqrt.ap-northeast-1.rds.amazonaws.com
```
# 05 ELB の作成 ～ 負荷分散用のロードバランサーを作成する ～
## 変数
```bash:コマンド
# ELBセキュリティグループ名
ELB_SECURITY_GROUP_NAME='elb-user1' \
&& echo ${ELB_SECURITY_GROUP_NAME}

# DBセキュリティグループ説明
ELB_SECURITY_GROUP_DESCRIPTION='elb-user1' \
&& echo ${ELB_SECURITY_GROUP_DESCRIPTION}

# ターゲットタイプ
Target_GROUP_TYPE="instance" \
&& echo ${Target_GROUP_TYPE}

# ターゲットグループ名
Target_GROUP_NAME="target-user1" \
&& echo ${Target_GROUP_NAME}

# ターゲットグループ プロトコル
Target_GROUP_PROTOCOL="HTTP" \
&& echo ${Target_GROUP_PROTOCOL}

# ターゲットグループ ポート
Target_GROUP_PORT="80" \
&& echo ${Target_GROUP_PORT}

# ターゲットグループ プロトコルバージョン
Target_GROUP_PROTOCOLVERSION="HTTP1" \
&& echo ${Target_GROUP_PROTOCOLVERSION}

# ヘルスチェックプロトコル
HEALTH_CHECK_PROTOCOL="HTTP" \
&& echo ${HEALTH_CHECK_PROTOCOL}

# ヘルスチェックパス
HEALTH_CHECK_PATH="/wp-includes/images/blank.gif" \
&& echo ${HEALTH_CHECK_PATH}

# ロードバランサー名
LB_NAME="elb-user1" \
&& echo ${LB_NAME}

# リスナー プロトコル
LISTENER_PROTOCOL="HTTP" \
&& echo ${LISTENER_PROTOCOL}

# リスナー ポート
LISTENER_PORT="80" \
&& echo ${LISTENER_PORT}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ELBセキュリティグループ名
[cloudshell-user@ip-10-132-84-39 ~]$ ELB_SECURITY_GROUP_NAME='elb-user1' \
> && echo ${ELB_SECURITY_GROUP_NAME}
elb-user1
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # DBセキュリティグループ説明
[cloudshell-user@ip-10-132-84-39 ~]$ ELB_SECURITY_GROUP_DESCRIPTION='elb-user1' \
> && echo ${ELB_SECURITY_GROUP_DESCRIPTION}
elb-user1
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ターゲットタイプ
[cloudshell-user@ip-10-132-84-39 ~]$ Target_GROUP_TYPE="instance" \
> && echo ${Target_GROUP_TYPE}
instance
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ターゲットグループ名
[cloudshell-user@ip-10-132-84-39 ~]$ Target_GROUP_NAME="target-user1" \
> && echo ${Target_GROUP_NAME}
target-user1
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ターゲットグループ プロトコル
[cloudshell-user@ip-10-132-84-39 ~]$ Target_GROUP_PROTOCOL="HTTP" \
> && echo ${Target_GROUP_PROTOCOL}
HTTP
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ターゲットグループ ポート
[cloudshell-user@ip-10-132-84-39 ~]$ Target_GROUP_PORT="80" \
> && echo ${Target_GROUP_PORT}
80
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ターゲットグループ プロトコルバージョン
[cloudshell-user@ip-10-132-84-39 ~]$ Target_GROUP_PROTOCOLVERSION="HTTP1" \
> && echo ${Target_GROUP_PROTOCOLVERSION}
HTTP1
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ヘルスチェックプロトコル
[cloudshell-user@ip-10-132-84-39 ~]$ HEALTH_CHECK_PROTOCOL="HTTP" \
> && echo ${HEALTH_CHECK_PROTOCOL}
HTTP
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ヘルスチェックパス
[cloudshell-user@ip-10-132-84-39 ~]$ HEALTH_CHECK_PATH="/wp-includes/images/blank.gif" \
> && echo ${HEALTH_CHECK_PATH}
/wp-includes/images/blank.gif
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ロードバランサー名
[cloudshell-user@ip-10-132-84-39 ~]$ LB_NAME="elb-user1" \
> && echo ${LB_NAME}
elb-user1
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # リスナー プロトコル
[cloudshell-user@ip-10-132-84-39 ~]$ LISTENER_PROTOCOL="HTTP" \
> && echo ${LISTENER_PROTOCOL}
HTTP
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # リスナー ポート
[cloudshell-user@ip-10-132-84-39 ~]$ LISTENER_PORT="80" \
> && echo ${LISTENER_PORT}
80
```
## セキュリティグループ作成
### セキュリティグループ作成
```bash:コマンド
# セキュリティグループ作成
aws ec2 create-security-group \
    --group-name ${ELB_SECURITY_GROUP_NAME} \
    --description ${ELB_SECURITY_GROUP_DESCRIPTION} \
    --vpc-id ${VPC_ID}

# ID取得
ELB_SECURITY_GROUP_ID=$( \
    aws ec2 describe-security-groups \
        --filters Name=vpc-id,Values=${VPC_ID} \
                  Name=group-name,Values=${ELB_SECURITY_GROUP_NAME} \
        --query "SecurityGroups[].GroupId" \
        --output text \
) \
&& echo ${ELB_SECURITY_GROUP_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # セキュリティグループ作成
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 create-security-group \
>     --group-name ${ELB_SECURITY_GROUP_NAME} \
>     --description ${ELB_SECURITY_GROUP_DESCRIPTION} \
>     --vpc-id ${VPC_ID}
{
    "GroupId": "sg-07b48cc330643f5ad"
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ID取得
[cloudshell-user@ip-10-132-84-39 ~]$ ELB_SECURITY_GROUP_ID=$( \
>     aws ec2 describe-security-groups \
>         --filters Name=vpc-id,Values=${VPC_ID} \
>                   Name=group-name,Values=${ELB_SECURITY_GROUP_NAME} \
>         --query "SecurityGroups[].GroupId" \
>         --output text \
> ) \
> && echo ${ELB_SECURITY_GROUP_ID}
sg-07b48cc330643f5ad
```
### ルール追加
```bash:コマンド
# ルール追加
aws ec2 authorize-security-group-ingress \
    --group-id ${ELB_SECURITY_GROUP_ID} \
    --protocol tcp \
    --port 80 \
    --cidr 0.0.0.0/0

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ルール追加
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 authorize-security-group-ingress \
>     --group-id ${ELB_SECURITY_GROUP_ID} \
>     --protocol tcp \
>     --port 80 \
>     --cidr 0.0.0.0/0
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-0dc1cd74abcc810af",
            "GroupId": "sg-07b48cc330643f5ad",
            "GroupOwnerId": "999999999999",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 80,
            "ToPort": 80,
            "CidrIpv4": "0.0.0.0/0"
        }
    ]
}
```
## ターゲットグループ作成
### ターゲットグループ作成
```bash:コマンド
# ターゲットグループ作成
aws elbv2 create-target-group \
    --name ${Target_GROUP_NAME} \
    --protocol ${Target_GROUP_PROTOCOL} \
    --port ${Target_GROUP_PORT} \
    --vpc-id ${VPC_ID} \
    --target-type ${Target_GROUP_TYPE} \
    --health-check-protocol ${HEALTH_CHECK_PROTOCOL} \
    --health-check-path ${HEALTH_CHECK_PATH}

# ARN取得
TARGET_GROUP_ARN=$(
    aws elbv2 describe-target-groups \
        --names ${Target_GROUP_NAME} \
        --query 'TargetGroups[*].TargetGroupArn' \
        --output text
) \
&& echo ${TARGET_GROUP_ARN}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ターゲットグループ作成
[cloudshell-user@ip-10-132-84-39 ~]$ aws elbv2 create-target-group \
>     --name ${Target_GROUP_NAME} \
>     --protocol ${Target_GROUP_PROTOCOL} \
>     --port ${Target_GROUP_PORT} \
>     --vpc-id ${VPC_ID} \
>     --target-type ${Target_GROUP_TYPE} \
>     --health-check-protocol ${HEALTH_CHECK_PROTOCOL} \
>     --health-check-path ${HEALTH_CHECK_PATH}
{
    "TargetGroups": [
        {
            "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target-user1/a8bc1528bb902b2e",
            "TargetGroupName": "target-user1",
            "Protocol": "HTTP",
            "Port": 80,
            "VpcId": "vpc-02b5fbe797028d4e8",
            "HealthCheckProtocol": "HTTP",
            "HealthCheckPort": "traffic-port",
            "HealthCheckEnabled": true,
            "HealthCheckIntervalSeconds": 30,
            "HealthCheckTimeoutSeconds": 5,
            "HealthyThresholdCount": 5,
            "UnhealthyThresholdCount": 2,
            "HealthCheckPath": "/wp-includes/images/blank.gif",
            "Matcher": {
                "HttpCode": "200"
            },
            "TargetType": "instance",
            "ProtocolVersion": "HTTP1",
            "IpAddressType": "ipv4"
        }
    ]
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ARN取得
[cloudshell-user@ip-10-132-84-39 ~]$ TARGET_GROUP_ARN=$(
>     aws elbv2 describe-target-groups \
>         --names ${Target_GROUP_NAME} \
>         --query 'TargetGroups[*].TargetGroupArn' \
>         --output text
> ) \
> && echo ${TARGET_GROUP_ARN}
arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target-user1/a8bc1528bb902b2e
```
### ターゲットの登録
```bash:コマンド
# ターゲットの登録
aws elbv2 register-targets \
    --target-group-arn ${TARGET_GROUP_ARN} \
    --targets Id=${EC2_ID_1}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ターゲットの登録
[cloudshell-user@ip-10-132-84-39 ~]$ aws elbv2 register-targets \
>     --target-group-arn ${TARGET_GROUP_ARN} \
>     --targets Id=${EC2_ID_1}
```
## ロードバランサー作成
### ロードバランサー作成
```bash:コマンド
# ロードバランサー作成
aws elbv2 create-load-balancer \
    --name ${LB_NAME} \
    --type application \
    --scheme internet-facing \
    --ip-address-type ipv4 \
    --subnets ${AZ1_PUB_ID} ${AZ2_PUB_ID} \
    --security-groups ${ELB_SECURITY_GROUP_ID}

# ARN取得
LB_ARN=$(
    aws elbv2 describe-load-balancers \
        --names ${LB_NAME} \
        --query 'LoadBalancers[*].LoadBalancerArn' \
        --output text
) \
&& echo ${LB_ARN}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ロードバランサー作成
[cloudshell-user@ip-10-132-84-39 ~]$ aws elbv2 create-load-balancer \
>     --name ${LB_NAME} \
>     --type application \
>     --scheme internet-facing \
>     --ip-address-type ipv4 \
>     --subnets ${AZ1_PUB_ID} ${AZ2_PUB_ID} \
>     --security-groups ${ELB_SECURITY_GROUP_ID}
{
    "LoadBalancers": [
        {
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/elb-user1/ebb545cf60231bce",
            "DNSName": "elb-user1-154512834.ap-northeast-1.elb.amazonaws.com",
            "CanonicalHostedZoneId": "Z14GRHDCWA56QT",
            "CreatedTime": "2024-08-25T09:41:49.814000+00:00",
            "LoadBalancerName": "elb-user1",
            "Scheme": "internet-facing",
            "VpcId": "vpc-02b5fbe797028d4e8",
            "State": {
                "Code": "provisioning"
            },
            "Type": "application",
            "AvailabilityZones": [
                {
                    "ZoneName": "ap-northeast-1a",
                    "SubnetId": "subnet-09ce509c9397d5932",
                    "LoadBalancerAddresses": []
                },
                {
                    "ZoneName": "ap-northeast-1c",
                    "SubnetId": "subnet-0d31beb3e7dd1140d",
                    "LoadBalancerAddresses": []
                }
            ],
            "SecurityGroups": [
                "sg-07b48cc330643f5ad"
            ],
            "IpAddressType": "ipv4"
        }
    ]
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ARN取得
[cloudshell-user@ip-10-132-84-39 ~]$ LB_ARN=$(
>     aws elbv2 describe-load-balancers \
>         --names ${LB_NAME} \
>         --query 'LoadBalancers[*].LoadBalancerArn' \
>         --output text
> ) \
> && echo ${LB_ARN}
arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/elb-user1/ebb545cf60231bce
```
### リスナーの追加
```bash:コマンド
# リスナーの追加
aws elbv2 create-listener \
    --load-balancer-arn ${LB_ARN} \
    --protocol ${LISTENER_PROTOCOL} \
    --port ${LISTENER_PORT} \
    --default-actions Type=forward,TargetGroupArn=${TARGET_GROUP_ARN}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # リスナーの追加
[cloudshell-user@ip-10-132-84-39 ~]$ aws elbv2 create-listener \
>     --load-balancer-arn ${LB_ARN} \
>     --protocol ${LISTENER_PROTOCOL} \
>     --port ${LISTENER_PORT} \
>     --default-actions Type=forward,TargetGroupArn=${TARGET_GROUP_ARN}
{
    "Listeners": [
        {
            "ListenerArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:listener/app/elb-user1/ebb545cf60231bce/eb993c4a74201432",
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/elb-user1/ebb545cf60231bce",
            "Port": 80,
            "Protocol": "HTTP",
            "DefaultActions": [
                {
                    "Type": "forward",
                    "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target-user1/a8bc1528bb902b2e",
                    "ForwardConfig": {
                        "TargetGroups": [
                            {
                                "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target-user1/a8bc1528bb902b2e",
                                "Weight": 1
                            }
                        ],
                        "TargetGroupStickinessConfig": {
                            "Enabled": false
                        }
                    }
                }
            ]
        }
    ]
}
```
## 確認
### ELB（詳細）
```bash:コマンド
# ELB（詳細）
aws elbv2 describe-load-balancers --names ${LB_NAME}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ELB（詳細）
[cloudshell-user@ip-10-132-84-39 ~]$ aws elbv2 describe-load-balancers --names ${LB_NAME}
{
    "LoadBalancers": [
        {
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/elb-user1/ebb545cf60231bce",
            "DNSName": "elb-user1-154512834.ap-northeast-1.elb.amazonaws.com",
            "CanonicalHostedZoneId": "Z14GRHDCWA56QT",
            "CreatedTime": "2024-08-25T09:41:49.814000+00:00",
            "LoadBalancerName": "elb-user1",
            "Scheme": "internet-facing",
            "VpcId": "vpc-02b5fbe797028d4e8",
            "State": {
                "Code": "active"
            },
            "Type": "application",
            "AvailabilityZones": [
                {
                    "ZoneName": "ap-northeast-1a",
                    "SubnetId": "subnet-09ce509c9397d5932",
                    "LoadBalancerAddresses": []
                },
                {
                    "ZoneName": "ap-northeast-1c",
                    "SubnetId": "subnet-0d31beb3e7dd1140d",
                    "LoadBalancerAddresses": []
                }
            ],
            "SecurityGroups": [
                "sg-07b48cc330643f5ad"
            ],
            "IpAddressType": "ipv4"
        }
    ]
}
```
### ELB（DNS名）
```bash:コマンド
# ELB（DNS名）
aws elbv2 describe-load-balancers \
    --names ${LB_NAME} \
    --query LoadBalancers[].DNSName \
    --output text

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ELB（DNS名）
[cloudshell-user@ip-10-132-84-39 ~]$ aws elbv2 describe-load-balancers \
>     --names ${LB_NAME} \
>     --query LoadBalancers[].DNSName \
>     --output text
elb-user1-154512834.ap-northeast-1.elb.amazonaws.com
```
### ターゲットグループ（詳細）
```bash:コマンド
# ターゲットグループ（詳細）
aws elbv2 describe-target-groups --names ${Target_GROUP_NAME}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ターゲットグループ（詳細）
[cloudshell-user@ip-10-132-84-39 ~]$ aws elbv2 describe-target-groups --names ${Target_GROUP_NAME}
{
    "TargetGroups": [
        {
            "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target-user1/a8bc1528bb902b2e",
            "TargetGroupName": "target-user1",
            "Protocol": "HTTP",
            "Port": 80,
            "VpcId": "vpc-02b5fbe797028d4e8",
            "HealthCheckProtocol": "HTTP",
            "HealthCheckPort": "traffic-port",
            "HealthCheckEnabled": true,
            "HealthCheckIntervalSeconds": 30,
            "HealthCheckTimeoutSeconds": 5,
            "HealthyThresholdCount": 5,
            "UnhealthyThresholdCount": 2,
            "HealthCheckPath": "/wp-includes/images/blank.gif",
            "Matcher": {
                "HttpCode": "200"
            },
            "LoadBalancerArns": [
                "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/elb-user1/ebb545cf60231bce"
            ],
            "TargetType": "instance",
            "ProtocolVersion": "HTTP1",
            "IpAddressType": "ipv4"
        }
    ]
}
```

### ターゲットグループ（ステータス）
```bash:コマンド
# ターゲットグループ（ステータス）
aws elbv2 describe-target-health \
    --target-group-arn ${TARGET_GROUP_ARN}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ターゲットグループ（ステータス）
[cloudshell-user@ip-10-132-84-39 ~]$ aws elbv2 describe-target-health \
>     --target-group-arn ${TARGET_GROUP_ARN}
{
    "TargetHealthDescriptions": [
        {
            "Target": {
                "Id": "i-0ed3b54d25b834102",
                "Port": 80
            },
            "HealthCheckPort": "80",
            "TargetHealth": {
                "State": "healthy"
            }
        }
    ]
}
```
# 06 WordPressの初期設定 ～ WordPressの初期設定を行い簡単なブログを作る ～
## EC2 Instance Connect を使用して接続
```bash:コマンド
aws ec2-instance-connect ssh --instance-id ${EC2_ID_1}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2-instance-connect ssh --instance-id ${EC2_ID_1}
The authenticity of host '3.112.34.36 (3.112.34.36)' can't be established.
ED25519 key fingerprint is SHA256:JW9Kmz/CN/UURjH30gRGFlNygLNUdzpUcCVhsJ0cQ1o.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '3.112.34.36' (ED25519) to the list of known hosts.
   ,     #_
   ~\_  ####_        Amazon Linux 2
  ~~  \_#####\
  ~~     \###|       AL2 End of Life is 2025-06-30.
  ~~       \#/ ___
   ~~       V~' '->
    ~~~         /    A newer version of Amazon Linux is available!
      ~~._.   _/
         _/ _/       Amazon Linux 2023, GA and supported until 2028-03-15.
       _/m/'           https://aws.amazon.com/linux/amazon-linux-2023/

[ec2-user@ip-10-0-0-6 ~]$ 
```
## WP-CLIのインストール
```bash:コマンド
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar

php wp-cli.phar --info

chmod +x wp-cli.phar

sudo mv wp-cli.phar /usr/local/bin/wp

wp --info

```
```bash:出力
[ec2-user@ip-10-0-0-6 ~]$ curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 6882k  100 6882k    0     0  17.6M      0 --:--:-- --:--:-- --:--:-- 17.6M
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ php wp-cli.phar --info
OS:     Linux 4.14.350-266.564.amzn2.x86_64 #1 SMP Sat Aug 10 09:56:03 UTC 2024 x86_64
Shell:  /bin/bash
PHP binary:     /usr/bin/php
PHP version:    7.4.33
php.ini used:   /etc/php.ini
MySQL binary:   /usr/bin/mysql
MySQL version:  mysql  Ver 15.1 Distrib 5.5.68-MariaDB, for Linux (x86_64) using readline 5.1
SQL modes:
WP-CLI root dir:        phar://wp-cli.phar/vendor/wp-cli/wp-cli
WP-CLI vendor dir:      phar://wp-cli.phar/vendor
WP_CLI phar path:       /home/ec2-user
WP-CLI packages dir:
WP-CLI cache dir:       /home/ec2-user/.wp-cli/cache
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 2.11.0
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ chmod +x wp-cli.phar
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ sudo mv wp-cli.phar /usr/local/bin/wp
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ wp --info
OS:     Linux 4.14.350-266.564.amzn2.x86_64 #1 SMP Sat Aug 10 09:56:03 UTC 2024 x86_64
Shell:  /bin/bash
PHP binary:     /usr/bin/php
PHP version:    7.4.33
php.ini used:   /etc/php.ini
MySQL binary:   /usr/bin/mysql
MySQL version:  mysql  Ver 15.1 Distrib 5.5.68-MariaDB, for Linux (x86_64) using readline 5.1
SQL modes:
WP-CLI root dir:        phar://wp-cli.phar/vendor/wp-cli/wp-cli
WP-CLI vendor dir:      phar://wp-cli.phar/vendor
WP_CLI phar path:       /home/ec2-user
WP-CLI packages dir:
WP-CLI cache dir:       /home/ec2-user/.wp-cli/cache
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 2.11.0
```
## 変数
```bash:コマンド
DB_NAME="wordpress" \
&& echo ${DB_NAME}

MASTER_USERNAME="admin" \
&& echo ${MASTER_USERNAME}

MASTER_USER_PASSWORD="AjO5PqEZI6IX" \
&& echo ${MASTER_USER_PASSWORD}

RDS_INSTANCE="db-user1.clacqicsiqrt.ap-northeast-1.rds.amazonaws.com" \
&& echo ${RDS_INSTANCE}

WP_URL="elb-user1-154512834.ap-northeast-1.elb.amazonaws.com" \
&& echo ${WP_URL}

WP_TITLE="はじめてのAWS" \
&& echo ${WP_TITLE}

WP_USERNAME="admin" \
&& echo ${WP_USERNAME}

WP_PASSWORD=$(< /dev/urandom tr -dc 'A-Za-z0-9' | head -c12) \
&& echo ${WP_PASSWORD}

WP_EMAIL="username@example.com" \
&& echo ${WP_EMAIL}

```
```bash:出力
[ec2-user@ip-10-0-0-6 ~]$ DB_NAME="wordpress" \
> && echo ${DB_NAME}
wordpress
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ MASTER_USERNAME="admin" \
> && echo ${MASTER_USERNAME}
admin
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ MASTER_USER_PASSWORD="AjO5PqEZI6IX" \
> && echo ${MASTER_USER_PASSWORD}
AjO5PqEZI6IX
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ RDS_INSTANCE="db-user1.clacqicsiqrt.ap-northeast-1.rds.amazonaws.com" \
> && echo ${RDS_INSTANCE}
db-user1.clacqicsiqrt.ap-northeast-1.rds.amazonaws.com
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ WP_URL="elb-user1-154512834.ap-northeast-1.elb.amazonaws.com" \
> && echo ${WP_URL}
elb-user1-154512834.ap-northeast-1.elb.amazonaws.com
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ WP_TITLE="はじめてのAWS" \
> && echo ${WP_TITLE}
はじめてのAWS
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ WP_USERNAME="admin" \
> && echo ${WP_USERNAME}
admin
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ WP_PASSWORD=$(< /dev/urandom tr -dc 'A-Za-z0-9' | head -c12) \
> && echo ${WP_PASSWORD}
m2NouEqLPS5d
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ WP_EMAIL="username@example.com" \
> && echo ${WP_EMAIL}
username@example.com
```
## WordPressの初期設定
```bash:コマンド
# WordPressの初期設定
wp core download

sudo -u apache /usr/local/bin/wp config create \
    --path=/var/www/html \
    --dbname=${DB_NAME} \
    --dbuser=${MASTER_USERNAME} \
    --dbpass=${MASTER_USER_PASSWORD} \
    --dbhost=${RDS_INSTANCE} \
    --dbprefix=wp_

wp core install \
    --url=http://${WP_URL} \
    --title="${WP_TITLE}" \
    --admin_user=${WP_USERNAME} \
    --admin_password=${WP_PASSWORD} \
    --admin_email=${WP_EMAIL}

wp option update blog_public 0

```
```bash:出力
[ec2-user@ip-10-0-0-6 ~]$ # WordPressの初期設定
[ec2-user@ip-10-0-0-6 ~]$ wp core download
Downloading WordPress 6.6.1 (en_US)...
md5 hash verified: a15f676931133623b7b347f1fabc966b
Success: WordPress downloaded.
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ wp config create \
>     --dbname=${DB_NAME} \
>     --dbuser=${MASTER_USERNAME} \
>     --dbpass=${MASTER_USER_PASSWORD} \
>     --dbhost=${RDS_INSTANCE} \
>     --dbprefix=wp_
Success: Generated 'wp-config.php' file.
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ wp core install \
>     --url=http://${WP_URL} \
>     --title="${WP_TITLE}" \
>     --admin_user=${WP_USERNAME} \
>     --admin_password=${WP_PASSWORD} \
>     --admin_email=${WP_EMAIL}
Success: WordPress installed successfully.
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ sudo cp -p wp-config.php /var/www/html
[ec2-user@ip-10-0-0-6 ~]$ wp core install \
>     --url=http://${WP_URL} \
>     --title="${WP_TITLE}" \
>     --admin_user=${WP_USERNAME} \
>     --admin_password=${WP_PASSWORD} \
>     --admin_email=${WP_EMAIL}
WordPress is already installed.
[ec2-user@ip-10-0-0-6 ~]$ 
[ec2-user@ip-10-0-0-6 ~]$ wp option update blog_public 0
Success: Updated 'blog_public' option.
```
## EC2 Instance Connect 切断
```bash:コマンド
exit
```
```bash:出力
[ec2-user@ip-10-0-0-6 ~]$ exit
logout
Connection to 3.112.34.36 closed.
```
# 6. 07 AMIの作成と作成したAMIから2つ目のEC2インスタンスの起動
## 変数
```bash:コマンド
# イメージ名
AMI_NAME='wordpress-user1' \
&& echo ${AMI_NAME}

# EC2インスタンス名 2
EC2_NAME_2='webserver#2-user1' \
&& echo ${EC2_NAME_2}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # イメージ名
[cloudshell-user@ip-10-132-84-39 ~]$ AMI_NAME='wordpress-user1' \
> && echo ${AMI_NAME}
wordpress-user1
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # EC2インスタンス名 2
[cloudshell-user@ip-10-132-84-39 ~]$ EC2_NAME_2='webserver#2-user1' \
> && echo ${EC2_NAME_2}
webserver#2-user1
```
## AMI の作成
```bash:コマンド
# AMI作成
aws ec2 create-image \
    --instance-id ${EC2_ID_1} \
    --name "${AMI_NAME}"

# ID取得
IMAGE_ID=$(
    aws ec2 describe-images \
        --filters "Name=name,Values=${AMI_NAME}" \
        --query 'Images[0].ImageId' \
        --output text
) \
&& echo ${IMAGE_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # AMI作成
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 create-image \
>     --instance-id ${EC2_ID_1} \
>     --name "${AMI_NAME}"
{
    "ImageId": "ami-0dd3897e244f061da"
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ID取得
[cloudshell-user@ip-10-132-84-39 ~]$ IMAGE_ID=$(
>     aws ec2 describe-images \
>         --filters "Name=name,Values=${AMI_NAME}" \
>         --query 'Images[0].ImageId' \
>         --output text
> ) \
> && echo ${IMAGE_ID}
ami-0dd3897e244f061da
```
## 2つ⽬の EC2 インスタンスの作成
```bash:コマンド
# EC2インスタンス作成
aws ec2 run-instances \
    --image-id ${IMAGE_ID}  \
    --instance-type ${EC2_INSTANCE_TYPE} \
    --security-group-ids ${EC2_SECURITY_GROUP_ID} \
    --subnet-id ${AZ2_PUB_ID} \
    --associate-public-ip-address \
    --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${EC2_NAME_2}}]" \
    --no-cli-pager

# インスタンスID
EC2_ID_2=$( \
    aws ec2 describe-instances \
        --filters Name=tag:Name,Values=${EC2_NAME_2}  \
        --query "Reservations[*].Instances[*].[InstanceId]" \
        --output text
) \
&& echo ${EC2_ID_2} 

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # EC2インスタンス作成
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 run-instances \
>     --image-id ${IMAGE_ID}  \
>     --instance-type ${EC2_INSTANCE_TYPE} \
>     --security-group-ids ${EC2_SECURITY_GROUP_ID} \
>     --subnet-id ${AZ2_PUB_ID} \
>     --associate-public-ip-address \
>     --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${EC2_NAME_2}}]" \
>     --no-cli-pager
{
    "Groups": [],
    "Instances": [
        {
            "AmiLaunchIndex": 0,
            "ImageId": "ami-0dd3897e244f061da",
            "InstanceId": "i-05d36122200065fdb",
            "InstanceType": "t2.micro",
            "LaunchTime": "2024-08-25T10:56:35+00:00",
            "Monitoring": {
                "State": "disabled"
            },
            "Placement": {
                "AvailabilityZone": "ap-northeast-1c",
                "GroupName": "",
                "Tenancy": "default"
            },
            "PrivateDnsName": "ip-10-0-1-86.ap-northeast-1.compute.internal",
            "PrivateIpAddress": "10.0.1.86",
            "ProductCodes": [],
            "PublicDnsName": "",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "StateTransitionReason": "",
            "SubnetId": "subnet-0d31beb3e7dd1140d",
            "VpcId": "vpc-02b5fbe797028d4e8",
            "Architecture": "x86_64",
            "BlockDeviceMappings": [],
            "ClientToken": "4f91e9c3-878c-410e-9b7f-4c2e8afef03e",
            "EbsOptimized": false,
            "EnaSupport": true,
            "Hypervisor": "xen",
            "NetworkInterfaces": [
                {
                    "Attachment": {
                        "AttachTime": "2024-08-25T10:56:35+00:00",
                        "AttachmentId": "eni-attach-0d3c0eb282a9800ca",
                        "DeleteOnTermination": true,
                        "DeviceIndex": 0,
                        "Status": "attaching",
                        "NetworkCardIndex": 0
                    },
                    "Description": "",
                    "Groups": [
                        {
                            "GroupName": "web-user1",
                            "GroupId": "sg-0f13aa5ebac4e8118"
                        }
                    ],
                    "Ipv6Addresses": [],
                    "MacAddress": "0a:c5:5e:53:dc:9f",
                    "NetworkInterfaceId": "eni-058844cac8665e433",
                    "OwnerId": "999999999999",
                    "PrivateIpAddress": "10.0.1.86",
                    "PrivateIpAddresses": [
                        {
                            "Primary": true,
                            "PrivateIpAddress": "10.0.1.86"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Status": "in-use",
                    "SubnetId": "subnet-0d31beb3e7dd1140d",
                    "VpcId": "vpc-02b5fbe797028d4e8",
                    "InterfaceType": "interface"
                }
            ],
            "RootDeviceName": "/dev/xvda",
            "RootDeviceType": "ebs",
            "SecurityGroups": [
                {
                    "GroupName": "web-user1",
                    "GroupId": "sg-0f13aa5ebac4e8118"
                }
            ],
            "SourceDestCheck": true,
            "StateReason": {
                "Code": "pending",
                "Message": "pending"
            },
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "webserver#2-user1"
                }
            ],
            "VirtualizationType": "hvm",
            "CpuOptions": {
                "CoreCount": 1,
                "ThreadsPerCore": 1
            },
            "CapacityReservationSpecification": {
                "CapacityReservationPreference": "open"
            },
            "MetadataOptions": {
                "State": "pending",
                "HttpTokens": "optional",
                "HttpPutResponseHopLimit": 1,
                "HttpEndpoint": "enabled",
                "HttpProtocolIpv6": "disabled",
                "InstanceMetadataTags": "disabled"
            },
            "EnclaveOptions": {
                "Enabled": false
            },
            "PrivateDnsNameOptions": {
                "HostnameType": "ip-name",
                "EnableResourceNameDnsARecord": false,
                "EnableResourceNameDnsAAAARecord": false
            },
            "MaintenanceOptions": {
                "AutoRecovery": "default"
            },
            "CurrentInstanceBootMode": "legacy-bios"
        }
    ],
    "OwnerId": "999999999999",
    "ReservationId": "r-029ca72ab07d2a83c"
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # インスタンスID
[cloudshell-user@ip-10-132-84-39 ~]$ EC2_ID_2=$( \
>     aws ec2 describe-instances \
>         --filters Name=tag:Name,Values=${EC2_NAME_2}  \
>         --query "Reservations[*].Instances[*].[InstanceId]" \
>         --output text
> ) \
> && echo ${EC2_ID_2} 
i-05d36122200065fdb
```
## 2つ目のEC2インスタンスをELBに登録
```bash:コマンド
aws elbv2 register-targets \
    --target-group-arn ${TARGET_GROUP_ARN} \
    --targets Id=${EC2_ID_2}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ aws elbv2 register-targets \
>     --target-group-arn ${TARGET_GROUP_ARN} \
>     --targets Id=${EC2_ID_2}
```
## ターゲットグループ（ステータス）
```bash:コマンド
# ターゲットグループ（ステータス）
aws elbv2 describe-target-health \
    --target-group-arn ${TARGET_GROUP_ARN}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ターゲットグループ（ステータス）
[cloudshell-user@ip-10-132-84-39 ~]$ aws elbv2 describe-target-health \
>     --target-group-arn ${TARGET_GROUP_ARN}
{
    "TargetHealthDescriptions": [
        {
            "Target": {
                "Id": "i-05d36122200065fdb",
                "Port": 80
            },
            "HealthCheckPort": "80",
            "TargetHealth": {
                "State": "healthy"
            }
        },
        {
            "Target": {
                "Id": "i-0ed3b54d25b834102",
                "Port": 80
            },
            "HealthCheckPort": "80",
            "TargetHealth": {
                "State": "healthy"
            }
        }
    ]
}
```
# 08 RDSのマルチAZ配置 〜 すでに作成済みのRDS DB インスタンスのマルチAZ化を行う 〜
## RDS変更
```bash:コマンド
aws rds modify-db-instance \
    --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
    --multi-az \
    --apply-immediately \
    --no-cli-pager

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ aws rds modify-db-instance \
>     --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
>     --multi-az \
>     --apply-immediately \
>     --no-cli-pager
{
    "DBInstance": {
        "DBInstanceIdentifier": "db-user1",
        "DBInstanceClass": "db.t3.micro",
        "Engine": "mysql",
        "DBInstanceStatus": "available",
        "MasterUsername": "admin",
        "DBName": "wordpress",
        "Endpoint": {
            "Address": "db-user1.clacqicsiqrt.ap-northeast-1.rds.amazonaws.com",
            "Port": 3306,
            "HostedZoneId": "Z24O6O9L7SGTNB"
        },
        "AllocatedStorage": 20,
        "InstanceCreateTime": "2024-08-25T09:35:37.302000+00:00",
        "PreferredBackupWindow": "13:43-14:13",
        "BackupRetentionPeriod": 0,
        "DBSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-08c2854a9b34f089b",
                "Status": "active"
            }
        ],
        "DBParameterGroups": [
            {
                "DBParameterGroupName": "default.mysql8.0",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "AvailabilityZone": "ap-northeast-1a",
        "DBSubnetGroup": {
            "DBSubnetGroupName": "db-subnet-user1",
            "DBSubnetGroupDescription": "RDS for MySQL",
            "VpcId": "vpc-02b5fbe797028d4e8",
            "SubnetGroupStatus": "Complete",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-04ef02ee504c79f77",
                    "SubnetAvailabilityZone": {
                        "Name": "ap-northeast-1a"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-06ddf6a468a549ff8",
                    "SubnetAvailabilityZone": {
                        "Name": "ap-northeast-1c"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                }
            ]
        },
        "PreferredMaintenanceWindow": "sun:15:03-sun:15:33",
        "PendingModifiedValues": {
            "MultiAZ": true
        },
        "MultiAZ": false,
        "EngineVersion": "8.0.35",
        "AutoMinorVersionUpgrade": true,
        "ReadReplicaDBInstanceIdentifiers": [],
        "LicenseModel": "general-public-license",
        "OptionGroupMemberships": [
            {
                "OptionGroupName": "default:mysql-8-0",
                "Status": "in-sync"
            }
        ],
        "PubliclyAccessible": false,
        "StorageType": "gp2",
        "DbInstancePort": 0,
        "StorageEncrypted": true,
        "KmsKeyId": "arn:aws:kms:ap-northeast-1:999999999999:key/951b3fa0-aedb-4215-a2e6-9b7c2f5292e5",
        "DbiResourceId": "db-JLWEZ2TQ2U6TEYZGZWHYZ7R3L4",
        "CACertificateIdentifier": "rds-ca-rsa2048-g1",
        "DomainMemberships": [],
        "CopyTagsToSnapshot": false,
        "MonitoringInterval": 0,
        "DBInstanceArn": "arn:aws:rds:ap-northeast-1:999999999999:db:db-user1",
        "IAMDatabaseAuthenticationEnabled": false,
        "PerformanceInsightsEnabled": false,
        "DeletionProtection": false,
        "AssociatedRoles": [],
        "MaxAllocatedStorage": 1000,
        "TagList": [],
        "CustomerOwnedIpEnabled": false,
        "BackupTarget": "region",
        "NetworkType": "IPV4",
        "StorageThroughput": 0,
        "CertificateDetails": {
            "CAIdentifier": "rds-ca-rsa2048-g1",
            "ValidTill": "2025-08-25T09:34:46+00:00"
        },
        "DedicatedLogVolume": false,
        "EngineLifecycleSupport": "open-source-rds-extended-support"
    }
}
```
# 09 Webシステム全体の可用性の確認 〜 EC2インスタンスの停止やRDSのフェイルオーバーを行う 〜
## オプション 1:EC2 インスタンスを1つ停⽌させ、全体の可⽤性の確認
### EC2インスタンス停止
```bash:コマンド
aws ec2 stop-instances --instance-ids ${EC2_ID_1}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 stop-instances --instance-ids ${EC2_ID_1}
{
    "StoppingInstances": [
        {
            "CurrentState": {
                "Code": 64,
                "Name": "stopping"
            },
            "InstanceId": "i-0ed3b54d25b834102",
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}
```
### 通信確認
```bash:コマンド（別タブで実施）
url=http://elb-user1-154512834.ap-northeast-1.elb.amazonaws.com/
while true; do TZ=JST-9 date; curl -o /dev/null -s -w "%{http_code}\n" ${url} ; sleep 1s; done

```
```bash:出力（別タブで実施）
[cloudshell-user@ip-10-132-84-39 ~]$ url=http://elb-user1-154512834.ap-northeast-1.elb.amazonaws.com/
[cloudshell-user@ip-10-132-84-39 ~]$ while true; do TZ=JST-9 date; curl -o /dev/null -s -w "%{http_code}\n" ${url} ; sleep 1s; done
Sun Aug 25 08:29:23 PM JST 2024
200
Sun Aug 25 08:29:25 PM JST 2024
200
Sun Aug 25 08:29:26 PM JST 2024
200
Sun Aug 25 08:29:27 PM JST 2024
200
Sun Aug 25 08:29:29 PM JST 2024
200
Sun Aug 25 08:29:30 PM JST 2024
200
Sun Aug 25 08:29:31 PM JST 2024
200
Sun Aug 25 08:29:33 PM JST 2024
200
Sun Aug 25 08:29:34 PM JST 2024
200
Sun Aug 25 08:29:35 PM JST 2024
200
Sun Aug 25 08:29:37 PM JST 2024
200
Sun Aug 25 08:29:38 PM JST 2024
200
Sun Aug 25 08:29:39 PM JST 2024
200
Sun Aug 25 08:29:41 PM JST 2024
200
Sun Aug 25 08:29:42 PM JST 2024
200
Sun Aug 25 08:29:43 PM JST 2024
200
Sun Aug 25 08:29:45 PM JST 2024
502
Sun Aug 25 08:29:46 PM JST 2024
502
Sun Aug 25 08:29:47 PM JST 2024
200
Sun Aug 25 08:29:48 PM JST 2024
200
Sun Aug 25 08:29:50 PM JST 2024
504
Sun Aug 25 08:30:01 PM JST 2024
200
Sun Aug 25 08:30:03 PM JST 2024
200
Sun Aug 25 08:30:04 PM JST 2024
504
Sun Aug 25 08:30:15 PM JST 2024
504
Sun Aug 25 08:30:26 PM JST 2024
200
Sun Aug 25 08:30:28 PM JST 2024
200
Sun Aug 25 08:30:29 PM JST 2024
200
Sun Aug 25 08:30:30 PM JST 2024
200
Sun Aug 25 08:30:32 PM JST 2024
200
Sun Aug 25 08:30:33 PM JST 2024
200
Sun Aug 25 08:30:34 PM JST 2024
200
Sun Aug 25 08:30:36 PM JST 2024
200
Sun Aug 25 08:30:37 PM JST 2024
200
Sun Aug 25 08:30:38 PM JST 2024
200
Sun Aug 25 08:30:40 PM JST 2024
200
Sun Aug 25 08:30:41 PM JST 2024
200
Sun Aug 25 08:30:43 PM JST 2024
200
Sun Aug 25 08:30:44 PM JST 2024
200
Sun Aug 25 08:30:45 PM JST 2024
200
Sun Aug 25 08:30:47 PM JST 2024
200
Sun Aug 25 08:30:48 PM JST 2024
200
Sun Aug 25 08:30:49 PM JST 2024
200
Sun Aug 25 08:30:51 PM JST 2024
200
Sun Aug 25 08:30:52 PM JST 2024
200
Sun Aug 25 08:30:53 PM JST 2024
200
Sun Aug 25 08:30:55 PM JST 2024
200
Sun Aug 25 08:30:56 PM JST 2024
200
Sun Aug 25 08:30:58 PM JST 2024
200
Sun Aug 25 08:30:59 PM JST 2024
200
Sun Aug 25 08:31:00 PM JST 2024
200
Sun Aug 25 08:31:02 PM JST 2024
200
Sun Aug 25 08:31:03 PM JST 2024
200
Sun Aug 25 08:31:04 PM JST 2024
200
Sun Aug 25 08:31:06 PM JST 2024
200
Sun Aug 25 08:31:07 PM JST 2024
200
Sun Aug 25 08:31:08 PM JST 2024
200
Sun Aug 25 08:31:10 PM JST 2024
200
Sun Aug 25 08:31:11 PM JST 2024
200
Sun Aug 25 08:31:13 PM JST 2024
200
Sun Aug 25 08:31:14 PM JST 2024
200
Sun Aug 25 08:31:15 PM JST 2024
200
Sun Aug 25 08:31:17 PM JST 2024
200
Sun Aug 25 08:31:18 PM JST 2024
200
Sun Aug 25 08:31:19 PM JST 2024
200
Sun Aug 25 08:31:21 PM JST 2024
200
Sun Aug 25 08:31:22 PM JST 2024
200
Sun Aug 25 08:31:23 PM JST 2024
200
Sun Aug 25 08:31:25 PM JST 2024
200
Sun Aug 25 08:31:26 PM JST 2024
200
Sun Aug 25 08:31:27 PM JST 2024
200
Sun Aug 25 08:31:29 PM JST 2024
200
Sun Aug 25 08:31:30 PM JST 2024
200
Sun Aug 25 08:31:31 PM JST 2024
200
Sun Aug 25 08:31:33 PM JST 2024
200
Sun Aug 25 08:31:34 PM JST 2024
200
Sun Aug 25 08:31:36 PM JST 2024
200
Sun Aug 25 08:31:37 PM JST 2024
200
Sun Aug 25 08:31:38 PM JST 2024
200
Sun Aug 25 08:31:40 PM JST 2024
200
Sun Aug 25 08:31:41 PM JST 2024
200
Sun Aug 25 08:31:42 PM JST 2024
200
Sun Aug 25 08:31:44 PM JST 2024
200
Sun Aug 25 08:31:45 PM JST 2024
200
Sun Aug 25 08:31:47 PM JST 2024
200
Sun Aug 25 08:31:48 PM JST 2024
200
Sun Aug 25 08:31:49 PM JST 2024
200
Sun Aug 25 08:31:51 PM JST 2024
200
Sun Aug 25 08:31:52 PM JST 2024
200
Sun Aug 25 08:31:53 PM JST 2024
200
Sun Aug 25 08:31:55 PM JST 2024
200
Sun Aug 25 08:31:56 PM JST 2024
200
Sun Aug 25 08:31:58 PM JST 2024
200
Sun Aug 25 08:31:59 PM JST 2024
200
Sun Aug 25 08:32:00 PM JST 2024
200
Sun Aug 25 08:32:02 PM JST 2024
200
Sun Aug 25 08:32:03 PM JST 2024
200
Sun Aug 25 08:32:04 PM JST 2024
200
Sun Aug 25 08:32:06 PM JST 2024
200
Sun Aug 25 08:32:07 PM JST 2024
200
Sun Aug 25 08:32:08 PM JST 2024
200
Sun Aug 25 08:32:10 PM JST 2024
200
Sun Aug 25 08:32:11 PM JST 2024
200
Sun Aug 25 08:32:12 PM JST 2024
200
Sun Aug 25 08:32:13 PM JST 2024
200
Sun Aug 25 08:32:15 PM JST 2024
200
Sun Aug 25 08:32:16 PM JST 2024
200
Sun Aug 25 08:32:18 PM JST 2024
200
Sun Aug 25 08:32:19 PM JST 2024
200
Sun Aug 25 08:32:20 PM JST 2024
200
Sun Aug 25 08:32:22 PM JST 2024
200
Sun Aug 25 08:32:23 PM JST 2024
200
Sun Aug 25 08:32:24 PM JST 2024
200
Sun Aug 25 08:32:25 PM JST 2024
200
Sun Aug 25 08:32:27 PM JST 2024
200
Sun Aug 25 08:32:28 PM JST 2024
200
Sun Aug 25 08:32:29 PM JST 2024
200
Sun Aug 25 08:32:31 PM JST 2024
200
Sun Aug 25 08:32:32 PM JST 2024
^C
```
### EC2インスタンス開始
```bash:コマンド
aws ec2 start-instances --instance-ids ${EC2_ID_1}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 start-instances --instance-ids ${EC2_ID_1}
{
    "StartingInstances": [
        {
            "CurrentState": {
                "Code": 0,
                "Name": "pending"
            },
            "InstanceId": "i-0ed3b54d25b834102",
            "PreviousState": {
                "Code": 80,
                "Name": "stopped"
            }
        }
    ]
}
```
```bash:コマンド（別タブで実施）
url=http://elb-user1-154512834.ap-northeast-1.elb.amazonaws.com/
while true; do TZ=JST-9 date; curl -o /dev/null -s -w "%{http_code}\n" ${url} ; sleep 1s; done

```
```bash:出力（別タブで実施）
[cloudshell-user@ip-10-132-84-39 ~]$ url=http://elb-user1-154512834.ap-northeast-1.elb.amazonaws.com/
[cloudshell-user@ip-10-132-84-39 ~]$ while true; do TZ=JST-9 date; curl -o /dev/null -s -w "%{http_code}\n" ${url} ; sleep 1s; done
Sun Aug 25 08:29:23 PM JST 2024
200
Sun Aug 25 08:29:25 PM JST 2024
200
Sun Aug 25 08:29:26 PM JST 2024
200
Sun Aug 25 08:29:27 PM JST 2024
200
Sun Aug 25 08:29:29 PM JST 2024
200
Sun Aug 25 08:29:30 PM JST 2024
200
Sun Aug 25 08:29:31 PM JST 2024
200
Sun Aug 25 08:29:33 PM JST 2024
200
Sun Aug 25 08:29:34 PM JST 2024
200
Sun Aug 25 08:29:35 PM JST 2024
200
Sun Aug 25 08:29:37 PM JST 2024
200
Sun Aug 25 08:29:38 PM JST 2024
200
Sun Aug 25 08:29:39 PM JST 2024
200
Sun Aug 25 08:29:41 PM JST 2024
200
Sun Aug 25 08:29:42 PM JST 2024
200
Sun Aug 25 08:29:43 PM JST 2024
200
Sun Aug 25 08:29:45 PM JST 2024
502
Sun Aug 25 08:29:46 PM JST 2024
502
Sun Aug 25 08:29:47 PM JST 2024
200
Sun Aug 25 08:29:48 PM JST 2024
200
Sun Aug 25 08:29:50 PM JST 2024
504
Sun Aug 25 08:30:01 PM JST 2024
200
Sun Aug 25 08:30:03 PM JST 2024
200
Sun Aug 25 08:30:04 PM JST 2024
504
Sun Aug 25 08:30:15 PM JST 2024
504
Sun Aug 25 08:30:26 PM JST 2024
200
Sun Aug 25 08:30:28 PM JST 2024
200
Sun Aug 25 08:30:29 PM JST 2024
200
Sun Aug 25 08:30:30 PM JST 2024
200
Sun Aug 25 08:30:32 PM JST 2024
200
Sun Aug 25 08:30:33 PM JST 2024
200
Sun Aug 25 08:30:34 PM JST 2024
200
Sun Aug 25 08:30:36 PM JST 2024
200
Sun Aug 25 08:30:37 PM JST 2024
200
Sun Aug 25 08:30:38 PM JST 2024
200
Sun Aug 25 08:30:40 PM JST 2024
200
Sun Aug 25 08:30:41 PM JST 2024
200
Sun Aug 25 08:30:43 PM JST 2024
200
Sun Aug 25 08:30:44 PM JST 2024
200
Sun Aug 25 08:30:45 PM JST 2024
200
Sun Aug 25 08:30:47 PM JST 2024
200
Sun Aug 25 08:30:48 PM JST 2024
200
Sun Aug 25 08:30:49 PM JST 2024
200
Sun Aug 25 08:30:51 PM JST 2024
200
Sun Aug 25 08:30:52 PM JST 2024
200
Sun Aug 25 08:30:53 PM JST 2024
200
Sun Aug 25 08:30:55 PM JST 2024
200
Sun Aug 25 08:30:56 PM JST 2024
200
Sun Aug 25 08:30:58 PM JST 2024
200
Sun Aug 25 08:30:59 PM JST 2024
200
Sun Aug 25 08:31:00 PM JST 2024
200
Sun Aug 25 08:31:02 PM JST 2024
200
Sun Aug 25 08:31:03 PM JST 2024
200
Sun Aug 25 08:31:04 PM JST 2024
200
Sun Aug 25 08:31:06 PM JST 2024
200
Sun Aug 25 08:31:07 PM JST 2024
200
Sun Aug 25 08:31:08 PM JST 2024
200
Sun Aug 25 08:31:10 PM JST 2024
200
Sun Aug 25 08:31:11 PM JST 2024
200
Sun Aug 25 08:31:13 PM JST 2024
200
Sun Aug 25 08:31:14 PM JST 2024
200
Sun Aug 25 08:31:15 PM JST 2024
200
Sun Aug 25 08:31:17 PM JST 2024
200
Sun Aug 25 08:31:18 PM JST 2024
200
Sun Aug 25 08:31:19 PM JST 2024
200
Sun Aug 25 08:31:21 PM JST 2024
200
Sun Aug 25 08:31:22 PM JST 2024
200
Sun Aug 25 08:31:23 PM JST 2024
200
Sun Aug 25 08:31:25 PM JST 2024
200
Sun Aug 25 08:31:26 PM JST 2024
200
Sun Aug 25 08:31:27 PM JST 2024
200
Sun Aug 25 08:31:29 PM JST 2024
200
Sun Aug 25 08:31:30 PM JST 2024
200
Sun Aug 25 08:31:31 PM JST 2024
200
Sun Aug 25 08:31:33 PM JST 2024
200
Sun Aug 25 08:31:34 PM JST 2024
200
Sun Aug 25 08:31:36 PM JST 2024
200
Sun Aug 25 08:31:37 PM JST 2024
200
Sun Aug 25 08:31:38 PM JST 2024
200
Sun Aug 25 08:31:40 PM JST 2024
200
Sun Aug 25 08:31:41 PM JST 2024
200
Sun Aug 25 08:31:42 PM JST 2024
200
Sun Aug 25 08:31:44 PM JST 2024
200
Sun Aug 25 08:31:45 PM JST 2024
200
Sun Aug 25 08:31:47 PM JST 2024
200
Sun Aug 25 08:31:48 PM JST 2024
200
Sun Aug 25 08:31:49 PM JST 2024
200
Sun Aug 25 08:31:51 PM JST 2024
200
Sun Aug 25 08:31:52 PM JST 2024
200
Sun Aug 25 08:31:53 PM JST 2024
200
Sun Aug 25 08:31:55 PM JST 2024
200
Sun Aug 25 08:31:56 PM JST 2024
200
Sun Aug 25 08:31:58 PM JST 2024
200
Sun Aug 25 08:31:59 PM JST 2024
200
Sun Aug 25 08:32:00 PM JST 2024
200
Sun Aug 25 08:32:02 PM JST 2024
200
Sun Aug 25 08:32:03 PM JST 2024
200
Sun Aug 25 08:32:04 PM JST 2024
200
Sun Aug 25 08:32:06 PM JST 2024
200
Sun Aug 25 08:32:07 PM JST 2024
200
Sun Aug 25 08:32:08 PM JST 2024
200
Sun Aug 25 08:32:10 PM JST 2024
200
Sun Aug 25 08:32:11 PM JST 2024
200
Sun Aug 25 08:32:12 PM JST 2024
200
Sun Aug 25 08:32:13 PM JST 2024
200
Sun Aug 25 08:32:15 PM JST 2024
200
Sun Aug 25 08:32:16 PM JST 2024
200
Sun Aug 25 08:32:18 PM JST 2024
200
Sun Aug 25 08:32:19 PM JST 2024
200
Sun Aug 25 08:32:20 PM JST 2024
200
Sun Aug 25 08:32:22 PM JST 2024
200
Sun Aug 25 08:32:23 PM JST 2024
200
Sun Aug 25 08:32:24 PM JST 2024
200
Sun Aug 25 08:32:25 PM JST 2024
200
Sun Aug 25 08:32:27 PM JST 2024
200
Sun Aug 25 08:32:28 PM JST 2024
200
Sun Aug 25 08:32:29 PM JST 2024
200
Sun Aug 25 08:32:31 PM JST 2024
200
Sun Aug 25 08:32:32 PM JST 2024
^C
```
## オプション 2:RDS DB インスタンスのフェイルオーバーを⾏い、全体の可⽤性を確認
### DBインスタンス再起動
```bash:コマンド
aws rds reboot-db-instance \
    --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
    --force-failover \
    --no-cli-pager

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ aws rds reboot-db-instance \
>     --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
>     --force-failover
>     --no-cli-pager
{
    "DBInstance": {
        "DBInstanceIdentifier": "db-user1",
        "DBInstanceClass": "db.t3.micro",
        "Engine": "mysql",
        "DBInstanceStatus": "rebooting",
        "MasterUsername": "admin",
        "DBName": "wordpress",
        "Endpoint": {
            "Address": "db-user1.clacqicsiqrt.ap-northeast-1.rds.amazonaws.com",
            "Port": 3306,
            "HostedZoneId": "Z24O6O9L7SGTNB"
        },
        "AllocatedStorage": 20,
        "InstanceCreateTime": "2024-08-25T09:35:37.302000+00:00",
        "PreferredBackupWindow": "13:43-14:13",
        "BackupRetentionPeriod": 0,
        "DBSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-08c2854a9b34f089b",
                "Status": "active"
            }
        ],
        "DBParameterGroups": [
            {
                "DBParameterGroupName": "default.mysql8.0",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "AvailabilityZone": "ap-northeast-1a",
        "DBSubnetGroup": {
            "DBSubnetGroupName": "db-subnet-user1",
            "DBSubnetGroupDescription": "RDS for MySQL",
            "VpcId": "vpc-02b5fbe797028d4e8",
            "SubnetGroupStatus": "Complete",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-04ef02ee504c79f77",
                    "SubnetAvailabilityZone": {
                        "Name": "ap-northeast-1a"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-06ddf6a468a549ff8",
                    "SubnetAvailabilityZone": {
                        "Name": "ap-northeast-1c"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                }
            ]
        },
        "PreferredMaintenanceWindow": "sun:15:03-sun:15:33",
        "PendingModifiedValues": {},
        "MultiAZ": true,
        "EngineVersion": "8.0.35",
        "AutoMinorVersionUpgrade": true,
        "ReadReplicaDBInstanceIdentifiers": [],
        "LicenseModel": "general-public-license",
        "OptionGroupMemberships": [
            {
                "OptionGroupName": "default:mysql-8-0",
                "Status": "in-sync"
            }
        ],
        "SecondaryAvailabilityZone": "ap-northeast-1c",
        "PubliclyAccessible": false,
        "StorageType": "gp2",
        "DbInstancePort": 0,
        "StorageEncrypted": true,
        "KmsKeyId": "arn:aws:kms:ap-northeast-1:999999999999:key/951b3fa0-aedb-4215-a2e6-9b7c2f5292e5",
        "DbiResourceId": "db-JLWEZ2TQ2U6TEYZGZWHYZ7R3L4",
        "CACertificateIdentifier": "rds-ca-rsa2048-g1",
        "DomainMemberships": [],
        "CopyTagsToSnapshot": false,
        "MonitoringInterval": 0,
        "DBInstanceArn": "arn:aws:rds:ap-northeast-1:999999999999:db:db-user1",
        "IAMDatabaseAuthenticationEnabled": false,
        "PerformanceInsightsEnabled": false,
        "DeletionProtection": false,
        "AssociatedRoles": [],
        "MaxAllocatedStorage": 1000,
        "TagList": [],
        "CustomerOwnedIpEnabled": false,
        "BackupTarget": "region",
        "NetworkType": "IPV4",
        "StorageThroughput": 0,
        "CertificateDetails": {
            "CAIdentifier": "rds-ca-rsa2048-g1",
            "ValidTill": "2025-08-25T09:34:46+00:00"
        },
        "DedicatedLogVolume": false,
        "EngineLifecycleSupport": "open-source-rds-extended-support"
    }
}
```
```bash:コマンド（別タブで実施）
url=http://elb-user1-154512834.ap-northeast-1.elb.amazonaws.com/
while true; do TZ=JST-9 date; curl -o /dev/null -s -w "%{http_code}\n" ${url} ; sleep 1s; done

```
```bash:出力（別タブで実施）
[cloudshell-user@ip-10-132-84-39 ~]$ url=http://elb-user1-154512834.ap-northeast-1.elb.amazonaws.com/
[cloudshell-user@ip-10-132-84-39 ~]$ while true; do TZ=JST-9 date; curl -o /dev/null -s -w "%{http_code}\n" ${url} ; sleep 1s; done
Sun Aug 25 08:37:40 PM JST 2024
200
Sun Aug 25 08:37:42 PM JST 2024
200
Sun Aug 25 08:37:43 PM JST 2024
200
Sun Aug 25 08:37:44 PM JST 2024
200
Sun Aug 25 08:37:46 PM JST 2024
200
Sun Aug 25 08:37:47 PM JST 2024
200
Sun Aug 25 08:37:48 PM JST 2024
200
Sun Aug 25 08:37:50 PM JST 2024
200
Sun Aug 25 08:37:51 PM JST 2024
200
Sun Aug 25 08:37:52 PM JST 2024
200
Sun Aug 25 08:37:54 PM JST 2024
200
Sun Aug 25 08:37:55 PM JST 2024
200
Sun Aug 25 08:37:56 PM JST 2024
200
Sun Aug 25 08:37:58 PM JST 2024
200
Sun Aug 25 08:37:59 PM JST 2024
200
Sun Aug 25 08:38:00 PM JST 2024 ←１分間通信断
504
Sun Aug 25 08:39:01 PM JST 2024
200
Sun Aug 25 08:39:03 PM JST 2024
200
Sun Aug 25 08:39:04 PM JST 2024
200
Sun Aug 25 08:39:05 PM JST 2024
200
Sun Aug 25 08:39:07 PM JST 2024
200
Sun Aug 25 08:39:08 PM JST 2024
200
Sun Aug 25 08:39:09 PM JST 2024
200
Sun Aug 25 08:39:11 PM JST 2024
200
Sun Aug 25 08:39:12 PM JST 2024
200
Sun Aug 25 08:39:13 PM JST 2024
200
Sun Aug 25 08:39:15 PM JST 2024
200
Sun Aug 25 08:39:16 PM JST 2024
200
Sun Aug 25 08:39:17 PM JST 2024
200
Sun Aug 25 08:39:19 PM JST 2024
200
Sun Aug 25 08:39:20 PM JST 2024
200
Sun Aug 25 08:39:21 PM JST 2024
200
Sun Aug 25 08:39:23 PM JST 2024
200
Sun Aug 25 08:39:24 PM JST 2024
200
Sun Aug 25 08:39:25 PM JST 2024
200
Sun Aug 25 08:39:27 PM JST 2024
200
Sun Aug 25 08:39:28 PM JST 2024
200
Sun Aug 25 08:39:29 PM JST 2024
200
Sun Aug 25 08:39:31 PM JST 2024
200
Sun Aug 25 08:39:32 PM JST 2024
200
Sun Aug 25 08:39:33 PM JST 2024
200
Sun Aug 25 08:39:34 PM JST 2024
200
Sun Aug 25 08:39:36 PM JST 2024
200
Sun Aug 25 08:39:37 PM JST 2024
200
Sun Aug 25 08:39:38 PM JST 2024
200
Sun Aug 25 08:39:40 PM JST 2024
200
Sun Aug 25 08:39:41 PM JST 2024
200
Sun Aug 25 08:39:43 PM JST 2024
200
Sun Aug 25 08:39:44 PM JST 2024
200
Sun Aug 25 08:39:45 PM JST 2024
200
```
### イベント確認
```bash:コマンド
aws rds describe-events \
    --source-identifier ${DB_INSTANCE_IDENTIFIER} \
    --source-type db-instance \
    --output table \
    --no-cli-pager

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ aws rds describe-events \
>     --source-identifier ${DB_INSTANCE_IDENTIFIER} \
>     --source-type db-instance \
>     --output table \
>     --no-cli-pager
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|                                                                                            DescribeEvents                                                                                             |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
||                                                                                               Events                                                                                                ||
|+------------------------------------+-----------------------------------------------------------------+---------------------------------------------------------+--------------------+---------------+|
||                Date                |                             Message                             |                        SourceArn                        | SourceIdentifier   |  SourceType   ||
|+------------------------------------+-----------------------------------------------------------------+---------------------------------------------------------+--------------------+---------------+|
||  2024-08-25T11:06:52.329000+00:00  |  Applying modification to convert to a Multi-AZ DB Instance     |  arn:aws:rds:ap-northeast-1:999999999999:db:db-user1    |  db-user1          |  db-instance  ||
|+------------------------------------+-----------------------------------------------------------------+---------------------------------------------------------+--------------------+---------------+|
|||                                                                                          EventCategories                                                                                          |||
||+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+||
|||  configuration change                                                                                                                                                                             |||
||+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+||
||                                                                                               Events                                                                                                ||
|+----------------------------------+-----------------------------------------------------------------------+-------------------------------------------------------+-------------------+--------------+|
||               Date               |                                Message                                |                       SourceArn                       | SourceIdentifier  | SourceType   ||
|+----------------------------------+-----------------------------------------------------------------------+-------------------------------------------------------+-------------------+--------------+|
||  2024-08-25T11:15:35.168000+00:00|  Finished applying modification to convert to a Multi-AZ DB Instance  |  arn:aws:rds:ap-northeast-1:999999999999:db:db-user1  |  db-user1         |  db-instance ||
|+----------------------------------+-----------------------------------------------------------------------+-------------------------------------------------------+-------------------+--------------+|
|||                                                                                          EventCategories                                                                                          |||
||+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+||
|||  configuration change                                                                                                                                                                             |||
||+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+||
||                                                                                               Events                                                                                                ||
|+-----------------------------------------+-----------------------------------------------+-----------------------------------------------------------------+-----------------------+-----------------+|
||                  Date                   |                    Message                    |                            SourceArn                            |   SourceIdentifier    |   SourceType    ||
|+-----------------------------------------+-----------------------------------------------+-----------------------------------------------------------------+-----------------------+-----------------+|
||  2024-08-25T11:38:00.724000+00:00       |  Multi-AZ instance failover started.          |  arn:aws:rds:ap-northeast-1:999999999999:db:db-user1            |  db-user1             |  db-instance    ||
|+-----------------------------------------+-----------------------------------------------+-----------------------------------------------------------------+-----------------------+-----------------+|
|||                                                                                          EventCategories                                                                                          |||
||+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+||
|||  failover                                                                                                                                                                                         |||
||+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+||
||                                                                                               Events                                                                                                ||
|+---------------------------------------------+--------------------------------+-----------------------------------------------------------------------+-------------------------+--------------------+|
||                    Date                     |            Message             |                               SourceArn                               |    SourceIdentifier     |    SourceType      ||
|+---------------------------------------------+--------------------------------+-----------------------------------------------------------------------+-------------------------+--------------------+|
||  2024-08-25T11:38:16.147000+00:00           |  DB instance restarted         |  arn:aws:rds:ap-northeast-1:999999999999:db:db-user1                  |  db-user1               |  db-instance       ||
|+---------------------------------------------+--------------------------------+-----------------------------------------------------------------------+-------------------------+--------------------+|
|||                                                                                          EventCategories                                                                                          |||
||+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+||
|||  availability                                                                                                                                                                                     |||
||+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+||
||                                                                                               Events                                                                                                ||
|+---------------------------------------------+--------------------------------+-----------------------------------------------------------------------+-------------------------+--------------------+|
||                    Date                     |            Message             |                               SourceArn                               |    SourceIdentifier     |    SourceType      ||
|+---------------------------------------------+--------------------------------+-----------------------------------------------------------------------+-------------------------+--------------------+|
||  2024-08-25T11:38:21.678000+00:00           |  DB instance restarted         |  arn:aws:rds:ap-northeast-1:999999999999:db:db-user1                  |  db-user1               |  db-instance       ||
|+---------------------------------------------+--------------------------------+-----------------------------------------------------------------------+-------------------------+--------------------+|
|||                                                                                          EventCategories                                                                                          |||
||+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+||
|||  availability                                                                                                                                                                                     |||
||+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+||
||                                                                                               Events                                                                                                ||
|+-----------------------------------------+-----------------------------------------------+-----------------------------------------------------------------+-----------------------+-----------------+|
||                  Date                   |                    Message                    |                            SourceArn                            |   SourceIdentifier    |   SourceType    ||
|+-----------------------------------------+-----------------------------------------------+-----------------------------------------------------------------+-----------------------+-----------------+|
||  2024-08-25T11:38:34.615000+00:00       |  Multi-AZ instance failover completed         |  arn:aws:rds:ap-northeast-1:999999999999:db:db-user1            |  db-user1             |  db-instance    ||
|+-----------------------------------------+-----------------------------------------------+-----------------------------------------------------------------+-----------------------+-----------------+|
|||                                                                                          EventCategories                                                                                          |||
||+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+||
|||  failover                                                                                                                                                                                         |||
||+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+||
||                                                                                               Events                                                                                                ||
|+--------------------------------------+----------------------------------------------------------+------------------------------------------------------------+---------------------+----------------+|
||                 Date                 |                         Message                          |                         SourceArn                          |  SourceIdentifier   |  SourceType    ||
|+--------------------------------------+----------------------------------------------------------+------------------------------------------------------------+---------------------+----------------+|
||  2024-08-25T11:38:34.615000+00:00    |  The user requested a failover of the DB instance.       |  arn:aws:rds:ap-northeast-1:999999999999:db:db-user1       |  db-user1           |  db-instance   ||
|+--------------------------------------+----------------------------------------------------------+------------------------------------------------------------+---------------------+----------------+|
```
### 詳細
```bash:コマンド
# 詳細
aws rds describe-db-instances \
    --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
    --no-cli-pager

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # 詳細
[cloudshell-user@ip-10-132-84-39 ~]$ aws rds describe-db-instances \
>     --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
>     --no-cli-pager
{
    "DBInstances": [
        {
            "DBInstanceIdentifier": "db-user1",
            "DBInstanceClass": "db.t3.micro",
            "Engine": "mysql",
            "DBInstanceStatus": "available",
            "MasterUsername": "admin",
            "DBName": "wordpress",
            "Endpoint": {
                "Address": "db-user1.clacqicsiqrt.ap-northeast-1.rds.amazonaws.com",
                "Port": 3306,
                "HostedZoneId": "Z24O6O9L7SGTNB"
            },
            "AllocatedStorage": 20,
            "InstanceCreateTime": "2024-08-25T09:35:37.302000+00:00",
            "PreferredBackupWindow": "13:43-14:13",
            "BackupRetentionPeriod": 0,
            "DBSecurityGroups": [],
            "VpcSecurityGroups": [
                {
                    "VpcSecurityGroupId": "sg-08c2854a9b34f089b",
                    "Status": "active"
                }
            ],
            "DBParameterGroups": [
                {
                    "DBParameterGroupName": "default.mysql8.0",
                    "ParameterApplyStatus": "in-sync"
                }
            ],
            "AvailabilityZone": "ap-northeast-1c",
            "DBSubnetGroup": {
                "DBSubnetGroupName": "db-subnet-user1",
                "DBSubnetGroupDescription": "RDS for MySQL",
                "VpcId": "vpc-02b5fbe797028d4e8",
                "SubnetGroupStatus": "Complete",
                "Subnets": [
                    {
                        "SubnetIdentifier": "subnet-04ef02ee504c79f77",
                        "SubnetAvailabilityZone": {
                            "Name": "ap-northeast-1a"
                        },
                        "SubnetOutpost": {},
                        "SubnetStatus": "Active"
                    },
                    {
                        "SubnetIdentifier": "subnet-06ddf6a468a549ff8",
                        "SubnetAvailabilityZone": {
                            "Name": "ap-northeast-1c"
                        },
                        "SubnetOutpost": {},
                        "SubnetStatus": "Active"
                    }
                ]
            },
            "PreferredMaintenanceWindow": "sun:15:03-sun:15:33",
            "PendingModifiedValues": {},
            "MultiAZ": true,
            "EngineVersion": "8.0.35",
            "AutoMinorVersionUpgrade": true,
            "ReadReplicaDBInstanceIdentifiers": [],
            "LicenseModel": "general-public-license",
            "OptionGroupMemberships": [
                {
                    "OptionGroupName": "default:mysql-8-0",
                    "Status": "in-sync"
                }
            ],
            "SecondaryAvailabilityZone": "ap-northeast-1a",
            "PubliclyAccessible": false,
            "StorageType": "gp2",
            "DbInstancePort": 0,
            "StorageEncrypted": true,
            "KmsKeyId": "arn:aws:kms:ap-northeast-1:999999999999:key/951b3fa0-aedb-4215-a2e6-9b7c2f5292e5",
            "DbiResourceId": "db-JLWEZ2TQ2U6TEYZGZWHYZ7R3L4",
            "CACertificateIdentifier": "rds-ca-rsa2048-g1",
            "DomainMemberships": [],
            "CopyTagsToSnapshot": false,
            "MonitoringInterval": 0,
            "DBInstanceArn": "arn:aws:rds:ap-northeast-1:999999999999:db:db-user1",
            "IAMDatabaseAuthenticationEnabled": false,
            "PerformanceInsightsEnabled": false,
            "DeletionProtection": false,
            "AssociatedRoles": [],
            "MaxAllocatedStorage": 1000,
            "TagList": [],
            "CustomerOwnedIpEnabled": false,
            "ActivityStreamStatus": "stopped",
            "BackupTarget": "region",
            "NetworkType": "IPV4",
            "StorageThroughput": 0,
            "CertificateDetails": {
                "CAIdentifier": "rds-ca-rsa2048-g1",
                "ValidTill": "2025-08-25T09:34:46+00:00"
            },
            "DedicatedLogVolume": false,
            "IsStorageConfigUpgradeAvailable": false,
            "EngineLifecycleSupport": "open-source-rds-extended-support"
        }
    ]
}
```
# 10 補足 & まとめ & 今後のラーニングパスについて
## RDS削除
```bash:コマンド
# RDS削除
aws rds delete-db-instance \
    --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
    --skip-final-snapshot \
    --delete-automated-backups \
    --no-cli-pager

# サブネットグループ削除
aws rds delete-db-subnet-group --db-subnet-group-name ${DB_SUBNET_GROUP_NAME}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # RDS削除
[cloudshell-user@ip-10-132-84-39 ~]$ aws rds delete-db-instance \
>     --db-instance-identifier ${DB_INSTANCE_IDENTIFIER} \
>     --skip-final-snapshot \
>     --delete-automated-backups \
>     --no-cli-pager
{
    "DBInstance": {
        "DBInstanceIdentifier": "db-user1",
        "DBInstanceClass": "db.t3.micro",
        "Engine": "mysql",
        "DBInstanceStatus": "deleting",
        "MasterUsername": "admin",
        "DBName": "wordpress",
        "Endpoint": {
            "Address": "db-user1.clacqicsiqrt.ap-northeast-1.rds.amazonaws.com",
            "Port": 3306,
            "HostedZoneId": "Z24O6O9L7SGTNB"
        },
        "AllocatedStorage": 20,
        "InstanceCreateTime": "2024-08-25T09:35:37.302000+00:00",
        "PreferredBackupWindow": "13:43-14:13",
        "BackupRetentionPeriod": 0,
        "DBSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-08c2854a9b34f089b",
                "Status": "active"
            }
        ],
        "DBParameterGroups": [
            {
                "DBParameterGroupName": "default.mysql8.0",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "AvailabilityZone": "ap-northeast-1c",
        "DBSubnetGroup": {
            "DBSubnetGroupName": "db-subnet-user1",
            "DBSubnetGroupDescription": "RDS for MySQL",
            "VpcId": "vpc-02b5fbe797028d4e8",
            "SubnetGroupStatus": "Complete",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-04ef02ee504c79f77",
                    "SubnetAvailabilityZone": {
                        "Name": "ap-northeast-1a"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-06ddf6a468a549ff8",
                    "SubnetAvailabilityZone": {
                        "Name": "ap-northeast-1c"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                }
            ]
        },
        "PreferredMaintenanceWindow": "sun:15:03-sun:15:33",
        "PendingModifiedValues": {},
        "MultiAZ": true,
        "EngineVersion": "8.0.35",
        "AutoMinorVersionUpgrade": true,
        "ReadReplicaDBInstanceIdentifiers": [],
        "LicenseModel": "general-public-license",
        "OptionGroupMemberships": [
            {
                "OptionGroupName": "default:mysql-8-0",
                "Status": "in-sync"
            }
        ],
        "SecondaryAvailabilityZone": "ap-northeast-1a",
        "PubliclyAccessible": false,
        "StorageType": "gp2",
        "DbInstancePort": 0,
        "StorageEncrypted": true,
        "KmsKeyId": "arn:aws:kms:ap-northeast-1:999999999999:key/951b3fa0-aedb-4215-a2e6-9b7c2f5292e5",
        "DbiResourceId": "db-JLWEZ2TQ2U6TEYZGZWHYZ7R3L4",
        "CACertificateIdentifier": "",
        "DomainMemberships": [],
        "CopyTagsToSnapshot": false,
        "MonitoringInterval": 0,
        "DBInstanceArn": "arn:aws:rds:ap-northeast-1:999999999999:db:db-user1",
        "IAMDatabaseAuthenticationEnabled": false,
        "PerformanceInsightsEnabled": false,
        "DeletionProtection": false,
        "AssociatedRoles": [],
        "MaxAllocatedStorage": 1000,
        "TagList": [],
        "CustomerOwnedIpEnabled": false,
        "BackupTarget": "region",
        "NetworkType": "IPV4",
        "StorageThroughput": 0,
        "DedicatedLogVolume": false,
        "EngineLifecycleSupport": "open-source-rds-extended-support"
    }
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # サブネットグループ削除
[cloudshell-user@ip-10-132-84-39 ~]$ aws rds delete-db-subnet-group --db-subnet-group-name ${DB_SUBNET_GROUP_NAME}
```
## EC2削除
```bash:コマンド
# EC2インスタンス削除
aws ec2 terminate-instances --instance-ids ${EC2_ID_1} ${EC2_ID_2}

# スナップショットID取得
SNAPSHOT_ID=$( \
    aws ec2 describe-images \
        --image-ids ${IMAGE_ID} \
        --query Images[].BlockDeviceMappings[].Ebs.SnapshotId \
        --output text
) \
&& echo ${SNAPSHOT_ID}

# AMI削除
aws ec2 deregister-image --image-id ${IMAGE_ID}

# スナップショットを削除する
aws ec2 delete-snapshot --snapshot-id ${SNAPSHOT_ID}
```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # EC2インスタンス削除
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 terminate-instances --instance-ids ${EC2_ID_1} ${EC2_ID_2}
{
    "TerminatingInstances": [
        {
            "CurrentState": {
                "Code": 32,
                "Name": "shutting-down"
            },
            "InstanceId": "i-05d36122200065fdb",
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        },
        {
            "CurrentState": {
                "Code": 32,
                "Name": "shutting-down"
            },
            "InstanceId": "i-0ed3b54d25b834102",
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # スナップショットID取得
[cloudshell-user@ip-10-132-84-39 ~]$ SNAPSHOT_ID=$( \
>     aws ec2 describe-images \
>         --image-ids ${IMAGE_ID} \
>         --query Images[].BlockDeviceMappings[].Ebs.SnapshotId \
>         --output text
> ) \
> && echo ${SNAPSHOT_ID}
snap-0c96f46dc1fe85e4a
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # AMI削除
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 deregister-image --image-id ${IMAGE_ID}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # スナップショットを削除する
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 delete-snapshot --snapshot-id ${SNAPSHOT_ID}
```
## ロードバランサー削除
```bash:コマンド
# ロードバランサー削除
aws elbv2 delete-load-balancer --load-balancer-arn ${LB_ARN}

# ターゲットグループ削除
aws elbv2 delete-target-group --target-group-arn ${TARGET_GROUP_ARN}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # ロードバランサー削除
[cloudshell-user@ip-10-132-84-39 ~]$ aws elbv2 delete-load-balancer --load-balancer-arn ${LB_ARN}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ターゲットグループ削除
[cloudshell-user@ip-10-132-84-39 ~]$ aws elbv2 delete-target-group --target-group-arn ${TARGET_GROUP_ARN}
```
## VPC削除
```bash:コマンド

# セキュリティグループ削除
aws ec2 delete-security-group --group-id ${ELB_SECURITY_GROUP_ID}
aws ec2 delete-security-group --group-id ${RDS_SG_ID}
aws ec2 delete-security-group --group-id ${EC2_SECURITY_GROUP_ID}

# インターネットゲートウェイ デタッチ
aws ec2 detach-internet-gateway \
    --internet-gateway-id ${IGW_ID}\
    --vpc-id ${VPC_ID}

# インターネットゲートウェイ削除
aws ec2 delete-internet-gateway --internet-gateway-id ${IGW_ID}

# Subnet 削除
aws ec2 delete-subnet --subnet-id ${AZ1_PUB_ID}
aws ec2 delete-subnet --subnet-id ${AZ2_PUB_ID}
aws ec2 delete-subnet --subnet-id ${AZ1_PRI_ID}
aws ec2 delete-subnet --subnet-id ${AZ2_PRI_ID}

# ルートテーブル削除
aws ec2 delete-route-table --route-table-id ${PUB_RT_ID}

# VPC削除
aws ec2 delete-vpc --vpc-id ${VPC_ID}

```
```bash:出力
[cloudshell-user@ip-10-132-84-39 ~]$ # セキュリティグループ削除
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 delete-security-group --group-id ${ELB_SECURITY_GROUP_ID}
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 delete-security-group --group-id ${RDS_SG_ID}
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 delete-security-group --group-id ${EC2_SECURITY_GROUP_ID}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # インターネットゲートウェイ デタッチ
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 detach-internet-gateway \
>     --internet-gateway-id ${IGW_ID}\
>     --vpc-id ${VPC_ID}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # インターネットゲートウェイ削除
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 delete-internet-gateway --internet-gateway-id ${IGW_ID}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # Subnet 削除
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 delete-subnet --subnet-id ${AZ1_PUB_ID}
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 delete-subnet --subnet-id ${AZ2_PUB_ID}
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 delete-subnet --subnet-id ${AZ1_PRI_ID}
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 delete-subnet --subnet-id ${AZ2_PRI_ID}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # ルートテーブル削除
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 delete-route-table --route-table-id ${PUB_RT_ID}
[cloudshell-user@ip-10-132-84-39 ~]$ 
[cloudshell-user@ip-10-132-84-39 ~]$ # VPC削除
[cloudshell-user@ip-10-132-84-39 ~]$ aws ec2 delete-vpc --vpc-id ${VPC_ID}
```