LoginSignup
0
0

AWS Hands-on for Beginners Network編#1 をAWS CLIでやってみる

Last updated at Posted at 2024-02-16

AWS 初心者向けハンズオン
「Network編#1 AWS上にセキュアなプライベートネットワーク空間を作成する」をAWS CLIで実施してみました。

目的

  • CLIで実施することによりAPIの理解を深める
  • オブジェクトのID値はdescribeコマンドで取得しfiltersオプションやqueryオプションを使用して出力し、変数で設定する
    ※filterやqueryの使い方を覚える

完成系
hands-on-beginers_1.drawio.png

Amazon VPC ハンズオン① Amazon VPC の作成とインターネット接続環境の構築

VPCを作成する

(変数設定)VPC名

コマンド
EC2_VPC_TAG_NAME='handson'

(変数設定)VPC CIDR

コマンド
EC2_VPC_CIDR='10.0.0.0/16'

VPC作成

コマンド
aws ec2 create-vpc \
  --cidr-block ${EC2_VPC_CIDR} \
  --tag-specifications "ResourceType=vpc,Tags=[{Key=Name,Value=${EC2_VPC_TAG_NAME}}]"
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-vpc \
  --cidr-block ${EC2_VPC_CIDR} \
  --tag-specifications "ResourceType=vpc,Tags=[{Key=Name,Value=${EC2_VPC_TAG_NAME}}]"
{
    "Vpc": {
        "CidrBlock": "10.0.0.0/16",
        "DhcpOptionsId": "dopt-0bfe6fa7c42bfd4ea",
        "State": "pending",
        "VpcId": "vpc-04e2b134f3596a7fa",
        "OwnerId": "************",
        "InstanceTenancy": "default",
        "Ipv6CidrBlockAssociationSet": [],
        "CidrBlockAssociationSet": [
            {
                "AssociationId": "vpc-cidr-assoc-00f060a14f86fbc3e",
                "CidrBlock": "10.0.0.0/16",
                "CidrBlockState": {
                    "State": "associated"
                }
            }
        ],
        "IsDefault": false,
        "Tags": [
            {
                "Key": "Name",
                "Value": "handson"
            }
        ]
    }
}

(変数設定)VPC ID取得

コマンド
EC2_VPC_ID=$( \
  aws ec2 describe-vpcs \
    --filters Name=tag:Name,Values=${EC2_VPC_TAG_NAME}  \
    --query 'Vpcs[].VpcId' \
    --output text \
) \
  && echo ${EC2_VPC_ID}
出力
[ec2-user@ip-172-31-12-138%]$ EC2_VPC_ID=$( \
  aws ec2 describe-vpcs \
    --filters Name=tag:Name,Values=${EC2_VPC_TAG_NAME}  \
    --query 'Vpcs[].VpcId' \
    --output text \
) \
  && echo ${EC2_VPC_ID}
vpc-04e2b134f3596a7fa

VPC内にサブネットを作成する

(変数設定)サブネット名

コマンド
EC2_SUBNET_TAG_NAME_1="Public subnet - a"
EC2_SUBNET_TAG_NAME_2="Public subnet - c"
EC2_SUBNET_TAG_NAME_3="Private subnet - a"
EC2_SUBNET_TAG_NAME_4="Private subnet - c"

(変数設定)アベイラビリティゾーン

コマンド
EC2_AZ_NAME_1="ap-northeast-1a"
EC2_AZ_NAME_2="ap-northeast-1c"
EC2_AZ_NAME_3="ap-northeast-1a"
EC2_AZ_NAME_4="ap-northeast-1c"

(変数設定)IPv4 CIDR ブロック

コマンド
EC2_SUBNET_CIDR_1='10.0.1.0/24'
EC2_SUBNET_CIDR_2='10.0.2.0/24'
EC2_SUBNET_CIDR_3='10.0.11.0/24'
EC2_SUBNET_CIDR_4='10.0.12.0/24'

パブリック サブネット作成①

コマンド
aws ec2 create-subnet \
  --vpc-id ${EC2_VPC_ID} \
  --cidr-block ${EC2_SUBNET_CIDR_1} \
  --availability-zone ${EC2_AZ_NAME_1} \
  --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${EC2_SUBNET_TAG_NAME_1}}]"
出力
ec2-user@ip-172-31-12-138%]$ aws ec2 create-subnet \
  --vpc-id ${EC2_VPC_ID} \
  --cidr-block ${EC2_SUBNET_CIDR_1} \
  --availability-zone ${EC2_AZ_NAME_1} \
  --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${EC2_SUBNET_TAG_NAME_1}}]"
{
    "Subnet": {
        "AvailabilityZone": "ap-northeast-1a",
        "AvailabilityZoneId": "apne1-az4",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.1.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-09cdec9ba1f0cfc9d",
        "VpcId": "vpc-04e2b134f3596a7fa",
        "OwnerId": "************",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [],
        "Tags": [
            {
                "Key": "Name",
                "Value": "Public subnet - a"
            }
        ],
        "SubnetArn": "arn:aws:ec2:ap-northeast-1:************:subnet/subnet-09cdec9ba1f0cfc9d",
        "EnableDns64": false,
        "Ipv6Native": false,
        "PrivateDnsNameOptionsOnLaunch": {
            "HostnameType": "ip-name",
            "EnableResourceNameDnsARecord": false,
            "EnableResourceNameDnsAAAARecord": false
        }
    }
}

(変数設定)パブリック サブネットID取得①

コマンド
EC2_SUBNET_ID_1=$( \
  aws ec2 describe-subnets \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
                Name=tag:Name,Values="${EC2_SUBNET_TAG_NAME_1}" \
    --query "Subnets[].SubnetId" \
    --output text \
) \
&& echo ${EC2_SUBNET_ID_1}
出力
[ec2-user@ip-172-31-12-138%]$ EC2_SUBNET_ID_1=$( \
  aws ec2 describe-subnets \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
                Name=tag:Name,Values="${EC2_SUBNET_TAG_NAME_1}" \
    --query "Subnets[].SubnetId" \
    --output text \
) \
&& echo ${EC2_SUBNET_ID_1}
subnet-09cdec9ba1f0cfc9d

パブリック サブネット作成②

コマンド
aws ec2 create-subnet \
  --vpc-id ${EC2_VPC_ID} \
  --cidr-block ${EC2_SUBNET_CIDR_2} \
  --availability-zone ${EC2_AZ_NAME_2} \
  --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${EC2_SUBNET_TAG_NAME_2}}]"
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-subnet \
  --vpc-id ${EC2_VPC_ID} \
  --cidr-block ${EC2_SUBNET_CIDR_2} \
  --availability-zone ${EC2_AZ_NAME_2} \
  --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${EC2_SUBNET_TAG_NAME_2}}]"
{
    "Subnet": {
        "AvailabilityZone": "ap-northeast-1c",
        "AvailabilityZoneId": "apne1-az1",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.2.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-0e3ef0a4057d99dac",
        "VpcId": "vpc-04e2b134f3596a7fa",
        "OwnerId": "************",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [],
        "Tags": [
            {
                "Key": "Name",
                "Value": "Public subnet - c"
            }
        ],
        "SubnetArn": "arn:aws:ec2:ap-northeast-1:************:subnet/subnet-0e3ef0a4057d99dac",
        "EnableDns64": false,
        "Ipv6Native": false,
        "PrivateDnsNameOptionsOnLaunch": {
            "HostnameType": "ip-name",
            "EnableResourceNameDnsARecord": false,
            "EnableResourceNameDnsAAAARecord": false
        }
    }
}

(変数設定)パブリック サブネットID取得②

コマンド
EC2_SUBNET_ID_2=$( \
  aws ec2 describe-subnets \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
                Name=tag:Name,Values="${EC2_SUBNET_TAG_NAME_2}" \
    --query "Subnets[].SubnetId" \
    --output text \
) \
&& echo ${EC2_SUBNET_ID_2}
出力
[ec2-user@ip-172-31-12-138%]$ EC2_SUBNET_ID_2=$( \
  aws ec2 describe-subnets \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
                Name=tag:Name,Values="${EC2_SUBNET_TAG_NAME_2}" \
    --query "Subnets[].SubnetId" \
    --output text \
) \
&& echo ${EC2_SUBNET_ID_2}
subnet-0e3ef0a4057d99dac

プライベート サブネット作成①

コマンド
aws ec2 create-subnet \
  --vpc-id ${EC2_VPC_ID} \
  --cidr-block ${EC2_SUBNET_CIDR_3} \
  --availability-zone ${EC2_AZ_NAME_3} \
  --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${EC2_SUBNET_TAG_NAME_3}}]"
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-subnet \
  --vpc-id ${EC2_VPC_ID} \
  --cidr-block ${EC2_SUBNET_CIDR_3} \
  --availability-zone ${EC2_AZ_NAME_3} \
  --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${EC2_SUBNET_TAG_NAME_3}}]"
{
    "Subnet": {
        "AvailabilityZone": "ap-northeast-1a",
        "AvailabilityZoneId": "apne1-az4",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.11.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-007997bd2fba2cd5a",
        "VpcId": "vpc-04e2b134f3596a7fa",
        "OwnerId": "************",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [],
        "Tags": [
            {
                "Key": "Name",
                "Value": "Private subnet - a"
            }
        ],
        "SubnetArn": "arn:aws:ec2:ap-northeast-1:************:subnet/subnet-007997bd2fba2cd5a",
        "EnableDns64": false,
        "Ipv6Native": false,
        "PrivateDnsNameOptionsOnLaunch": {
            "HostnameType": "ip-name",
            "EnableResourceNameDnsARecord": false,
            "EnableResourceNameDnsAAAARecord": false
        }
    }
}

(変数設定)プライベート サブネットID取得①

コマンド
EC2_SUBNET_ID_3=$( \
  aws ec2 describe-subnets \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
                Name=tag:Name,Values="${EC2_SUBNET_TAG_NAME_3}" \
    --query "Subnets[].SubnetId" \
    --output text \
) \
&& echo ${EC2_SUBNET_ID_3}
出力
[ec2-user@ip-172-31-12-138%]$ EC2_SUBNET_ID_3=$( \
  aws ec2 describe-subnets \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
                Name=tag:Name,Values="${EC2_SUBNET_TAG_NAME_3}" \
    --query "Subnets[].SubnetId" \
    --output text \
) \
&& echo ${EC2_SUBNET_ID_3}
subnet-007997bd2fba2cd5a

プライベート サブネット作成②

コマンド
aws ec2 create-subnet \
  --vpc-id ${EC2_VPC_ID} \
  --cidr-block ${EC2_SUBNET_CIDR_4} \
  --availability-zone ${EC2_AZ_NAME_4} \
  --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${EC2_SUBNET_TAG_NAME_4}}]"
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-subnet \
  --vpc-id ${EC2_VPC_ID} \
  --cidr-block ${EC2_SUBNET_CIDR_4} \
  --availability-zone ${EC2_AZ_NAME_4} \
  --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${EC2_SUBNET_TAG_NAME_4}}]"
{
    "Subnet": {
        "AvailabilityZone": "ap-northeast-1c",
        "AvailabilityZoneId": "apne1-az1",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.12.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-0af7f30e458edd880",
        "VpcId": "vpc-04e2b134f3596a7fa",
        "OwnerId": "************",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [],
        "Tags": [
            {
                "Key": "Name",
                "Value": "Private subnet - c"
            }
        ],
        "SubnetArn": "arn:aws:ec2:ap-northeast-1:************:subnet/subnet-0af7f30e458edd880",
        "EnableDns64": false,
        "Ipv6Native": false,
        "PrivateDnsNameOptionsOnLaunch": {
            "HostnameType": "ip-name",
            "EnableResourceNameDnsARecord": false,
            "EnableResourceNameDnsAAAARecord": false
        }
    }
}

(変数設定)プライベート サブネットID取得②

コマンド
EC2_SUBNET_ID_4=$( \
  aws ec2 describe-subnets \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
                Name=tag:Name,Values="${EC2_SUBNET_TAG_NAME_4}" \
    --query "Subnets[].SubnetId" \
    --output text \
) \
&& echo ${EC2_SUBNET_ID_4}
出力
[ec2-user@ip-172-31-12-138%]$ EC2_SUBNET_ID_4=$( \
  aws ec2 describe-subnets \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
                Name=tag:Name,Values="${EC2_SUBNET_TAG_NAME_4}" \
    --query "Subnets[].SubnetId" \
    --output text \
) \
&& echo ${EC2_SUBNET_ID_4}
subnet-0af7f30e458edd880

Internet Gatewayの作成とアタッチ

(変数設定)Internet Gateway名

コマンド
EC2_INTERNET_GATEWAY_TAG_NAME='handson-igw'

Internet Gateway作成

コマンド
aws ec2 create-internet-gateway \
  --tag-specifications "ResourceType=internet-gateway,Tags=[{Key=Name,Value=${EC2_INTERNET_GATEWAY_TAG_NAME}}]"
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-internet-gateway \
  --tag-specifications "ResourceType=internet-gateway,Tags=[{Key=Name,Value=${EC2_INTERNET_GATEWAY_TAG_NAME}}]"
{
    "InternetGateway": {
        "Attachments": [],
        "InternetGatewayId": "igw-03b240325cf3419bd",
        "OwnerId": "************",
        "Tags": [
            {
                "Key": "Name",
                "Value": "handson-igw"
            }
        ]
    }
}

(変数設定)Internet Gateway ID取得

コマンド
EC2_INTERNET_GATEWAY_ID=$( \
  aws ec2 describe-internet-gateways \
      --filters Name=tag:Name,Values=${EC2_INTERNET_GATEWAY_TAG_NAME} \
      --query "InternetGateways[].InternetGatewayId" \
      --output text \
) \
&& echo ${EC2_INTERNET_GATEWAY_ID}
出力
[ec2-user@ip-172-31-12-138%]$ EC2_INTERNET_GATEWAY_ID=$( \
  aws ec2 describe-internet-gateways \
      --filters Name=tag:Name,Values=${EC2_INTERNET_GATEWAY_TAG_NAME} \
      --query "InternetGateways[].InternetGatewayId" \
      --output text \
) \
&& echo ${EC2_INTERNET_GATEWAY_ID}
igw-03b240325cf3419bd

Internet GatewayをVPCにアタッチ

コマンド
aws ec2 attach-internet-gateway \
  --vpc-id ${EC2_VPC_ID} \
  --internet-gateway-id ${EC2_INTERNET_GATEWAY_ID}

Route tableの作成と関連付け

  • [パブリック ルートテーブル]
    インターネットGWへのデフォルトルートがある
  • [プライベート ルートテーブル(メイン ルートテーブル)]
    インターネットGWへのデフォルトルートがない
    ※メイン ルートテーブルはサブネット作成直後に自動で紐づけられるルートテーブル

(変数設定)パブリック ルートテーブル名

コマンド
EC2_ROUTE_TABLE_TAG_NAME='Public Route Table'

パブリック ルートテーブル作成

コマンド
aws ec2 create-route-table \
  --vpc-id ${EC2_VPC_ID} \
  --tag-specifications "ResourceType=route-table,Tags=[{Key=Name,Value=${EC2_ROUTE_TABLE_TAG_NAME}}]"
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-route-table \
  --vpc-id ${EC2_VPC_ID} \
  --tag-specifications "ResourceType=route-table,Tags=[{Key=Name,Value=${EC2_ROUTE_TABLE_TAG_NAME}}]"
{
    "RouteTable": {
        "Associations": [],
        "PropagatingVgws": [],
        "RouteTableId": "rtb-091437895557c837b",
        "Routes": [
            {
                "DestinationCidrBlock": "10.0.0.0/16",
                "GatewayId": "local",
                "Origin": "CreateRouteTable",
                "State": "active"
            }
        ],
        "Tags": [
            {
                "Key": "Name",
                "Value": "Public Route Table"
            }
        ],
        "VpcId": "vpc-04e2b134f3596a7fa",
        "OwnerId": "************"
    },
    "ClientToken": "cbe3b154-9c7f-4195-a9a8-8509e41bb3be"
}

(変数設定)パブリック ルートテーブルID取得

コマンド
EC2_ROUTE_TABLE_ID=$( \
  aws ec2 describe-route-tables \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
              Name=tag:Name,Values="${EC2_ROUTE_TABLE_TAG_NAME}" \
    --query "RouteTables[].RouteTableId" \
    --output text \
) \
&& echo ${EC2_ROUTE_TABLE_ID}
出力
[ec2-user@ip-172-31-12-138%]$ EC2_ROUTE_TABLE_ID=$( \
  aws ec2 describe-route-tables \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
              Name=tag:Name,Values="${EC2_ROUTE_TABLE_TAG_NAME}" \
    --query "RouteTables[].RouteTableId" \
    --output text \
) \
&& echo ${EC2_ROUTE_TABLE_ID}
rtb-091437895557c837b

(変数設定)デフォルトルート指定

コマンド
EC2_ROUTE_DESTINATION_CIDR='0.0.0.0/0'

デフォルトルート作成

コマンド
aws ec2 create-route \
  --route-table-id ${EC2_ROUTE_TABLE_ID} \
  --destination-cidr-block ${EC2_ROUTE_DESTINATION_CIDR} \
  --gateway-id ${EC2_INTERNET_GATEWAY_ID}
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-route \
  --route-table-id ${EC2_ROUTE_TABLE_ID} \
  --destination-cidr-block ${EC2_ROUTE_DESTINATION_CIDR} \
  --gateway-id ${EC2_INTERNET_GATEWAY_ID}
{
    "Return": true
}

(変数設定)メインルートテーブルID取得

コマンド
EC2_ROUTE_TABLE_MAIN_ID=$( \
  aws ec2 describe-route-tables \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
              Name=association.main,Values=true \
    --query "RouteTables[].RouteTableId" \
    --output text \
) \
&& echo ${EC2_ROUTE_TABLE_MAIN_ID}
出力
[ec2-user@ip-172-31-12-138%]$ EC2_ROUTE_TABLE_MAIN_ID=$( \
  aws ec2 describe-route-tables \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
              Name=association.main,Values=true \
    --query "RouteTables[].RouteTableId" \
    --output text \
) \
&& echo ${EC2_ROUTE_TABLE_MAIN_ID}
rtb-07ed7e843af9ac31a

(変数設定)プライベート ルートテーブル名

コマンド
EC2_ROUTE_TABLE_PRIVATE_TAG_NAME='Private Route Table'

メイン ルートテーブル名 変更

コマンド
aws ec2 create-tags \
    --resources ${EC2_ROUTE_TABLE_MAIN_ID} \
    --tags Key=Name,Value="${EC2_ROUTE_TABLE_PRIVATE_TAG_NAME}"

パブリック ルートテーブルの関連付け①

コマンド
aws ec2 associate-route-table \
  --subnet-id ${EC2_SUBNET_ID_1} \
  --route-table-id ${EC2_ROUTE_TABLE_ID}
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 associate-route-table \
  --subnet-id ${EC2_SUBNET_ID_1} \
  --route-table-id ${EC2_ROUTE_TABLE_ID}
{
    "AssociationId": "rtbassoc-05768cbface70ec48",
    "AssociationState": {
        "State": "associated"
    }
}

パブリック ルートテーブルの関連付け②

コマンド
aws ec2 associate-route-table \
  --subnet-id ${EC2_SUBNET_ID_2} \
  --route-table-id ${EC2_ROUTE_TABLE_ID}
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 associate-route-table \
  --subnet-id ${EC2_SUBNET_ID_2} \
  --route-table-id ${EC2_ROUTE_TABLE_ID}
{
    "AssociationId": "rtbassoc-0f63f1d16baf65d83",
    "AssociationState": {
        "State": "associated"
    }
}

プライベート ルートテーブルの関連付け①

コマンド
aws ec2 associate-route-table \
  --subnet-id ${EC2_SUBNET_ID_3} \
  --route-table-id ${EC2_ROUTE_TABLE_MAIN_ID}
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 associate-route-table \
  --subnet-id ${EC2_SUBNET_ID_3} \
  --route-table-id ${EC2_ROUTE_TABLE_MAIN_ID}
{
    "AssociationId": "rtbassoc-04d86f68a8fdc5623",
    "AssociationState": {
        "State": "associated"
    }
}

プライベート ルートテーブルの関連付け②

コマンド
aws ec2 associate-route-table \
  --subnet-id ${EC2_SUBNET_ID_4} \
  --route-table-id ${EC2_ROUTE_TABLE_MAIN_ID}
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 associate-route-table \
  --subnet-id ${EC2_SUBNET_ID_4} \
  --route-table-id ${EC2_ROUTE_TABLE_MAIN_ID}
{
    "AssociationId": "rtbassoc-083bfe4b59f627a67",
    "AssociationState": {
        "State": "associated"
    }
}

Amazon VPC ハンズオン② ルートテーブルによる経路設定を理解する

Assume Role (IAMロール) 作成

※役割の割り当て

Assume Roleドキュメントの作成(ヒアドキュメント)

コマンド
cat << EOF > handson-ssm.json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "sts:AssumeRole"
            ],
            "Principal": {
                "Service": [
                    "ec2.amazonaws.com"
                ]
            }
        }
    ]
}
EOF

Assume-roleの作成

コマンド
aws iam create-role \
  --role-name handson-ssm \
  --assume-role-policy-document file://${HOME}/handson-ssm.json
出力
[ec2-user@ip-172-31-12-138%]$ aws iam create-role \
  --role-name handson-ssm \
  --assume-role-policy-document file://${HOME}/handson-ssm.json
{
    "Role": {
        "Path": "/",
        "RoleName": "handson-ssm",
        "RoleId": "AROATCKAQKZPLSISBAWUT",
        "Arn": "arn:aws:iam::************:role/handson-ssm",
        "CreateDate": "2024-02-14T06:21:35+00:00",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "sts:AssumeRole"
                    ],
                    "Principal": {
                        "Service": [
                            "ec2.amazonaws.com"
                        ]
                    }
                }
            ]
        }
    }
}

Asume Roleに管理ポリシーをアタッチ

コマンド
aws iam attach-role-policy \
  --role-name handson-ssm \
  --policy-arn arn:aws:iam::aws:policy/AmazonSSMFullAccess

インスタンスプロファイルを作成する

※インスタンスプロファイルによってオブジェクトとAsume Roleを関連付ける

コマンド
aws iam create-instance-profile --instance-profile-name handson-ssm
出力
[ec2-user@ip-172-31-12-138%]$ aws iam create-instance-profile --instance-profile-name handson-ssm
{
    "InstanceProfile": {
        "Path": "/",
        "InstanceProfileName": "handson-ssm",
        "InstanceProfileId": "AIPATCKAQKZPMDBHQX5CD",
        "Arn": "arn:aws:iam::************:instance-profile/handson-ssm",
        "CreateDate": "2024-02-14T06:22:42+00:00",
        "Roles": []
    }
}

Asume Roleをインスタンスプロファイルに追加

コマンド
aws iam add-role-to-instance-profile --role-name handson-ssm --instance-profile-name handson-ssm

EC2作成

(変数設定)セキュリティグループ名

コマンド
EC2_SECURITY_GROUP_NAME='beginers-handson-sg'

(変数設定)セキュリティグループ説明

コマンド
EC2_SECURITY_GROUP_DESCRIPTION='beginers-handson SecurityGroup.'

セキュリティグループ作成

コマンド
aws ec2 create-security-group \
  --group-name ${EC2_SECURITY_GROUP_NAME} \
  --description "${EC2_SECURITY_GROUP_DESCRIPTION}" \
  --vpc-id ${EC2_VPC_ID}
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-security-group \
  --group-name ${EC2_SECURITY_GROUP_NAME} \
  --description "${EC2_SECURITY_GROUP_DESCRIPTION}" \
  --vpc-id ${EC2_VPC_ID}
{
    "GroupId": "sg-0d460bf3bb321e770"
}

(変数設定)セキュリティグループID取得

コマンド
EC2_SECURITY_GROUP_ID=$( \
  aws ec2 describe-security-groups \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
              Name=group-name,Values=${EC2_SECURITY_GROUP_NAME} \
    --query "SecurityGroups[].GroupId" \
    --output text \
) \
&& echo ${EC2_SECURITY_GROUP_ID}
出力
[ec2-user@ip-172-31-12-138%]$ EC2_SECURITY_GROUP_ID=$( \
  aws ec2 describe-security-groups \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
              Name=group-name,Values=${EC2_SECURITY_GROUP_NAME} \
    --query "SecurityGroups[].GroupId" \
    --output text \
) \
&& echo ${EC2_SECURITY_GROUP_ID}
sg-0d460bf3bb321e770

セキュリティグループ ルール追加

コマンド
aws ec2 authorize-security-group-ingress \
  --group-id ${EC2_SECURITY_GROUP_ID} \
  --protocol tcp \
  --port 80 \
  --cidr 0.0.0.0/0
出力
[ec2-user@ip-172-31-12-138%]$ 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-02f1b8fc22bf094a3",
            "GroupId": "sg-0d460bf3bb321e770",
            "GroupOwnerId": "************",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 80,
            "ToPort": 80,
            "CidrIpv4": "0.0.0.0/0"
        }
    ]
}

ユーザーデータ作成(ヒアドキュメント)

コマンド
cat << EOF > user_data.txt
#!/bin/bash

yum -y update
yum -y install httpd
systemctl enable httpd.service
systemctl start httpd.service
EOF

パブリック EC2作成

コマンド
aws ec2 run-instances \
  --image-id \
    resolve:ssm:"/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64" \
  --count 1 \
  --instance-type t2.micro \
  --associate-public-ip-address \
  --security-group-ids ${EC2_SECURITY_GROUP_ID} \
  --subnet-id ${EC2_SUBNET_ID_1} \
  --region ap-northeast-1 \
  --user-data file://user_data.txt \
  --iam-instance-profile Name=handson-ssm
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 run-instances \
  --image-id \
    resolve:ssm:"/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64" \
  --count 1 \
  --instance-type t2.micro \
  --associate-public-ip-address \
  --security-group-ids ${EC2_SECURITY_GROUP_ID} \
  --subnet-id ${EC2_SUBNET_ID_1} \
  --region ap-northeast-1 \
  --user-data file://user_data.txt \
  --iam-instance-profile Name=handson-ssm
{
    "Groups": [],
    "Instances": [
        {
            "AmiLaunchIndex": 0,
            "ImageId": "ami-0b5c74e235ed808b9",
            "InstanceId": "i-052d55832c3618c67",
            "InstanceType": "t2.micro",
            "LaunchTime": "2024-02-15T05:56:20+00:00",
            "Monitoring": {
                "State": "disabled"
            },
            "Placement": {
                "AvailabilityZone": "ap-northeast-1a",
                "GroupName": "",
                "Tenancy": "default"
            },
            "PrivateDnsName": "ip-10-0-1-74.ap-northeast-1.compute.internal",
            "PrivateIpAddress": "10.0.1.74",
            "ProductCodes": [],
            "PublicDnsName": "",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "StateTransitionReason": "",
            "SubnetId": "subnet-09cdec9ba1f0cfc9d",
            "VpcId": "vpc-04e2b134f3596a7fa",
            "Architecture": "x86_64",
            "BlockDeviceMappings": [],
            "ClientToken": "8154bc0d-3dcf-4b4e-b850-2720bfcf9ef7",
            "EbsOptimized": false,
            "EnaSupport": true,
            "Hypervisor": "xen",
            "IamInstanceProfile": {
                "Arn": "arn:aws:iam::************:instance-profile/handson-ssm",
                "Id": "AIPATCKAQKZPMDBHQX5CD"
            },
            "NetworkInterfaces": [
                {
                    "Attachment": {
                        "AttachTime": "2024-02-15T05:56:20+00:00",
                        "AttachmentId": "eni-attach-0244a343eaf0c7b85",
                        "DeleteOnTermination": true,
                        "DeviceIndex": 0,
                        "Status": "attaching",
                        "NetworkCardIndex": 0
                    },
                    "Description": "",
                    "Groups": [
                        {
                            "GroupName": "beginers-handson-sg",
                            "GroupId": "sg-0d460bf3bb321e770"
                        }
                    ],
                    "Ipv6Addresses": [],
                    "MacAddress": "06:53:4c:27:25:03",
                    "NetworkInterfaceId": "eni-0e61911cf731ed259",
                    "OwnerId": "************",
                    "PrivateIpAddress": "10.0.1.74",
                    "PrivateIpAddresses": [
                        {
                            "Primary": true,
                            "PrivateIpAddress": "10.0.1.74"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Status": "in-use",
                    "SubnetId": "subnet-09cdec9ba1f0cfc9d",
                    "VpcId": "vpc-04e2b134f3596a7fa",
                    "InterfaceType": "interface"
                }
            ],
            "RootDeviceName": "/dev/xvda",
            "RootDeviceType": "ebs",
            "SecurityGroups": [
                {
                    "GroupName": "beginers-handson-sg",
                    "GroupId": "sg-0d460bf3bb321e770"
                }
            ],
            "SourceDestCheck": true,
            "StateReason": {
                "Code": "pending",
                "Message": "pending"
            },
            "VirtualizationType": "hvm",
            "CpuOptions": {
                "CoreCount": 1,
                "ThreadsPerCore": 1
            },
            "CapacityReservationSpecification": {
                "CapacityReservationPreference": "open"
            },
            "MetadataOptions": {
                "State": "pending",
                "HttpTokens": "required",
                "HttpPutResponseHopLimit": 2,
                "HttpEndpoint": "enabled",
                "HttpProtocolIpv6": "disabled",
                "InstanceMetadataTags": "disabled"
            },
            "EnclaveOptions": {
                "Enabled": false
            },
            "BootMode": "uefi-preferred",
            "PrivateDnsNameOptions": {
                "HostnameType": "ip-name",
                "EnableResourceNameDnsARecord": false,
                "EnableResourceNameDnsAAAARecord": false
            },
            "MaintenanceOptions": {
                "AutoRecovery": "default"
            },
            "CurrentInstanceBootMode": "legacy-bios"
        }
    ],
    "OwnerId": "************",
    "ReservationId": "r-0b94ce31f9da63b2c"
}

(変数設定)パブリックEC2 インスタンスID 取得

コマンド
EC2_INSTANCE_ID=$( \
  aws ec2 describe-instances \
    --filters Name=subnet-id,Values=${EC2_SUBNET_ID_1} \
    --query "Reservations[*].Instances[*].[InstanceId]" \
    --output text
) \
&& echo ${EC2_INSTANCE_ID}  
出力
[ec2-user@ip-172-31-12-138%]$ EC2_INSTANCE_ID=$( \
  aws ec2 describe-instances \
    --filters Name=subnet-id,Values=${EC2_SUBNET_ID_1} \
    --query "Reservations[*].Instances[*].[InstanceId]" \
    --output text
) \
&& echo ${EC2_INSTANCE_ID} 
i-052d55832c3618c67

パブリックEC2 インスタンス名変更

コマンド
aws ec2 create-tags \
  --resources ${EC2_INSTANCE_ID} \
  --tags "Key=Name,Value=Web"

パブリックEC2 接続確認(インターネット側から実施)

hands-on-beginers-Step1.drawio.png

コマンド
curl 54.238.230.80
出力
user01@WIN-CCVQU8G9E71:~$ curl 54.238.230.80
<html><body><h1>It works!</h1></body></html>

Amazon VPC ハンズオン③ プライベートサブネットからインターネットへのアクセス方法

EC2作成

プライベート EC2作成

コマンド
aws ec2 run-instances \
  --image-id \
    resolve:ssm:"/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64" \
  --count 1 \
  --instance-type t2.micro \
  --security-group-ids ${EC2_SECURITY_GROUP_ID} \
  --subnet-id ${EC2_SUBNET_ID_4} \
  --region ap-northeast-1 \
  --iam-instance-profile Name=handson-ssm
出力
aws ec2 run-instances \
  --image-id \
    resolve:ssm:"/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64" \
  --count 1 \
  --instance-type t2.micro \
  --security-group-ids ${EC2_SECURITY_GROUP_ID} \
  --subnet-id ${EC2_SUBNET_ID_4} \
  --region ap-northeast-1 \
  --iam-instance-profile Name=handson-ssm
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 run-instances \
  --image-id \
    resolve:ssm:"/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64" \
  --count 1 \
  --instance-type t2.micro \
  --security-group-ids ${EC2_SECURITY_GROUP_ID} \
  --subnet-id ${EC2_SUBNET_ID_4} \
  --region ap-northeast-1 \
> ^C
[ec2-user@ip-172-31-12-138%]$ aws ec2 run-instances \
  --image-id \
    resolve:ssm:"/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64" \
  --count 1 \
  --instance-type t2.micro \
  --security-group-ids ${EC2_SECURITY_GROUP_ID} \
  --subnet-id ${EC2_SUBNET_ID_4} \
  --region ap-northeast-1
{
    "Groups": [],
    "Instances": [
        {
            "AmiLaunchIndex": 0,
            "ImageId": "ami-0b5c74e235ed808b9",
            "InstanceId": "i-0b1384a2548400e9f",
            "InstanceType": "t2.micro",
            "LaunchTime": "2024-02-14T10:36:30+00:00",
            "Monitoring": {
                "State": "disabled"
            },
            "Placement": {
                "AvailabilityZone": "ap-northeast-1c",
                "GroupName": "",
                "Tenancy": "default"
            },
            "PrivateDnsName": "ip-10-0-12-59.ap-northeast-1.compute.internal",
            "PrivateIpAddress": "10.0.12.59",
            "ProductCodes": [],
            "PublicDnsName": "",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "StateTransitionReason": "",
            "SubnetId": "subnet-0af7f30e458edd880",
            "VpcId": "vpc-04e2b134f3596a7fa",
            "Architecture": "x86_64",
            "BlockDeviceMappings": [],
            "ClientToken": "674c56cf-56af-4af7-a0fd-cd2b741a566f",
            "EbsOptimized": false,
            "EnaSupport": true,
            "Hypervisor": "xen",
            "NetworkInterfaces": [
                {
                    "Attachment": {
                        "AttachTime": "2024-02-14T10:36:30+00:00",
                        "AttachmentId": "eni-attach-0fd931a232d8983cf",
                        "DeleteOnTermination": true,
                        "DeviceIndex": 0,
                        "Status": "attaching",
                        "NetworkCardIndex": 0
                    },
                    "Description": "",
                    "Groups": [
                        {
                            "GroupName": "default",
                            "GroupId": "sg-078ced1e87f2cf73e"
                        }
                    ],
                    "Ipv6Addresses": [],
                    "MacAddress": "0a:8c:56:be:4b:43",
                    "NetworkInterfaceId": "eni-09e96433efddd87ef",
                    "OwnerId": "************",
                    "PrivateIpAddress": "10.0.12.59",
                    "PrivateIpAddresses": [
                        {
                            "Primary": true,
                            "PrivateIpAddress": "10.0.12.59"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Status": "in-use",
                    "SubnetId": "subnet-0af7f30e458edd880",
                    "VpcId": "vpc-04e2b134f3596a7fa",
                    "InterfaceType": "interface"
                }
            ],
            "RootDeviceName": "/dev/xvda",
            "RootDeviceType": "ebs",
            "SecurityGroups": [
                {
                    "GroupName": "default",
                    "GroupId": "sg-078ced1e87f2cf73e"
                }
            ],
            "SourceDestCheck": true,
            "StateReason": {
                "Code": "pending",
                "Message": "pending"
            },
            "VirtualizationType": "hvm",
            "CpuOptions": {
                "CoreCount": 1,
                "ThreadsPerCore": 1
            },
            "CapacityReservationSpecification": {
                "CapacityReservationPreference": "open"
            },
            "MetadataOptions": {
                "State": "pending",
                "HttpTokens": "required",
                "HttpPutResponseHopLimit": 2,
                "HttpEndpoint": "enabled",
                "HttpProtocolIpv6": "disabled",
                "InstanceMetadataTags": "disabled"
            },
            "EnclaveOptions": {
                "Enabled": false
            },
            "BootMode": "uefi-preferred",
            "PrivateDnsNameOptions": {
                "HostnameType": "ip-name",
                "EnableResourceNameDnsARecord": false,
                "EnableResourceNameDnsAAAARecord": false
            },
            "MaintenanceOptions": {
                "AutoRecovery": "default"
            },
            "CurrentInstanceBootMode": "legacy-bios"
        }
    ],
    "OwnerId": "************",
    "ReservationId": "r-02d6d81bade32f62c"
}

(変数設定)プライベートEC2 インスタンスID 取得

コマンド
Private_EC2_INSTANCE_ID=$( \
  aws ec2 describe-instances \
    --filters Name=subnet-id,Values=${EC2_SUBNET_ID_4} \
    --query "Reservations[*].Instances[*].[InstanceId]" \
    --output text
) \
&& echo ${Private_EC2_INSTANCE_ID} 
出力
[ec2-user@ip-172-31-12-138%]$ Private_EC2_INSTANCE_ID=$( \
  aws ec2 describe-instances \
    --filters Name=subnet-id,Values=${EC2_SUBNET_ID_4} \
    --query "Reservations[*].Instances[*].[InstanceId]" \
    --output text
) \
&& echo ${Private_EC2_INSTANCE_ID} 
i-0661675e581acab6c

プライベートEC2 インスタンス名変更

コマンド
aws ec2 create-tags \
  --resources ${Private_EC2_INSTANCE_ID} \
  --tags "Key=Name,Value=Internal"

NATゲートウェイ作成

NATゲートウェイは1年間の無料枠があっても、費用がかかります。
※検証後は必ず削除すること。

Elastic IP アドレス割当

コマンド
aws ec2 allocate-address
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 allocate-address
{
    "PublicIp": "35.75.100.179",
    "AllocationId": "eipalloc-00df47b9beefb84f5",
    "PublicIpv4Pool": "amazon",
    "NetworkBorderGroup": "ap-northeast-1",
    "Domain": "vpc"
}

(変数設定)Elastic IP アドレスID 取得

コマンド
EC2_ELASTIC_IP_ID=$( \
  aws ec2 describe-addresses \
    --query "Addresses[].AllocationId" \
    --output text \
) \
&& echo ${EC2_ELASTIC_IP_ID}
出力
[ec2-user@ip-172-31-12-138%]$ EC2_ELASTIC_IP_ID=$( \
  aws ec2 describe-addresses \
    --query "Addresses[].AllocationId" \
    --output text \
) \
&& echo ${EC2_ELASTIC_IP_ID}
eipalloc-00df47b9beefb84f5

NATゲートウェイ作成

コマンド
aws ec2 create-nat-gateway \
  --subnet-id ${EC2_SUBNET_ID_2} \
  --connectivity-type public \
  --allocation-id ${EC2_ELASTIC_IP_ID}
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-nat-gateway \
  --subnet-id ${EC2_SUBNET_ID_2} \
  --connectivity-type public \
  --allocation-id ${EC2_ELASTIC_IP_ID}
{
    "ClientToken": "b7e5e3b4-ad46-4d38-bf23-8c53461d6685",
    "NatGateway": {
        "CreateTime": "2024-02-15T06:09:38+00:00",
        "NatGatewayAddresses": [
            {
                "AllocationId": "eipalloc-00df47b9beefb84f5",
                "IsPrimary": true,
                "Status": "associating"
            }
        ],
        "NatGatewayId": "nat-07ab3507790c39d60",
        "State": "pending",
        "SubnetId": "subnet-0e3ef0a4057d99dac",
        "VpcId": "vpc-04e2b134f3596a7fa",
        "ConnectivityType": "public"
    }
}

(変数設定)NATゲートウェイID 取得

コマンド
NATGATEWAY_ID=$( \
  aws ec2 describe-nat-gateways \
    --query "NatGateways[].NatGatewayId" \
    --output text \
) \
&& echo ${NATGATEWAY_ID}
出力
[ec2-user@ip-172-31-12-138%]$ NATGATEWAY_ID=$( \
  aws ec2 describe-nat-gateways \
    --query "NatGateways[].NatGatewayId" \
    --output text \
) \
&& echo ${NATGATEWAY_ID}
nat-07ab3507790c39d60

NATゲートウェイ名前変更

コマンド
aws ec2 create-tags \
  --resources ${NATGATEWAY_ID} \
  --tags "Key=Name,Value=handson-natgateway"

プライベート ルートテーブル デフォルトルート作成

コマンド
aws ec2 create-route \
  --route-table-id ${EC2_ROUTE_TABLE_MAIN_ID} \
  --destination-cidr-block ${EC2_ROUTE_DESTINATION_CIDR} \
  --gateway-id ${NATGATEWAY_ID}
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-route \
  --route-table-id ${EC2_ROUTE_TABLE_MAIN_ID} \
  --destination-cidr-block ${EC2_ROUTE_DESTINATION_CIDR} \
  --gateway-id ${NATGATEWAY_ID}
{
    "Return": true
}

セッションマネージャ接続確認

hands-on-beginers-Step2.drawio.png
セッションマネージャー(SSM)はVPCの外側にあるため、プライベートEC2 → NATゲートウェイ→ Internet Gatewayを通過してセッションマネージャに到達する

コマンド
whoami
出力
sh-5.2$ whoami
ssm-user

Amazon VPC ハンズオン④ VPC外サービスへの接続方法 - 1

Interface型Endpoint (AWS PrivateLink)

プライベート ルートテーブル デフォルトルート削除

コマンド
aws ec2 delete-route \
  --route-table-id ${EC2_ROUTE_TABLE_MAIN_ID} \
  --destination-cidr-block ${EC2_ROUTE_DESTINATION_CIDR}

VPCのDNSホスト名を有効化

コマンド
aws ec2 modify-vpc-attribute \
  --region ap-northeast-1 \
  --vpc-id ${EC2_VPC_ID} \
  --enable-dns-hostnames '{"Value":true}'

(変数設定)セキュリティグループ名(VPCエンドポイント用)

コマンド
EC2_SECURITY_GROUP_NAME_2='ssm'

(変数設定)セキュリティグループ説明(VPCエンドポイント用)

コマンド
EC2_SECURITY_GROUP_DESCRIPTION_2='ssm'

セキュリティグループ作成(VPCエンドポイント用)

コマンド
aws ec2 create-security-group \
  --group-name ${EC2_SECURITY_GROUP_NAME_2} \
  --description "${EC2_SECURITY_GROUP_DESCRIPTION_2}" \
  --vpc-id ${EC2_VPC_ID}
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-security-group \
  --group-name ${EC2_SECURITY_GROUP_NAME_2} \
  --description "${EC2_SECURITY_GROUP_DESCRIPTION_2}" \
  --vpc-id ${EC2_VPC_ID}
{
    "GroupId": "sg-0d0d8aa11953dde1a"
}

(変数設定)セキュリティグループID(VPCエンドポイント用)

コマンド
EC2_SECURITY_GROUP_ID_2=$( \
  aws ec2 describe-security-groups \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
              Name=group-name,Values=${EC2_SECURITY_GROUP_NAME_2} \
    --query "SecurityGroups[].GroupId" \
    --output text \
) \
&& echo ${EC2_SECURITY_GROUP_ID_2}
出力
[ec2-user@ip-172-31-12-138%]$ EC2_SECURITY_GROUP_ID_2=$( \
  aws ec2 describe-security-groups \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
              Name=group-name,Values=${EC2_SECURITY_GROUP_NAME_2} \
    --query "SecurityGroups[].GroupId" \
    --output text \
) \
&& echo ${EC2_SECURITY_GROUP_ID_2}
sg-0d0d8aa11953dde1a

セキュリティグループ ルール追加(VPCエンドポイント用)

コマンド
aws ec2 authorize-security-group-ingress \
  --group-id ${EC2_SECURITY_GROUP_ID_2} \
  --protocol 'tcp' \
  --port '443' \
  --cidr '10.0.0.0/16'
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 authorize-security-group-ingress \
  --group-id ${EC2_SECURITY_GROUP_ID_2} \
  --protocol 'tcp' \
  --port '443' \
  --cidr '10.0.0.0/16'
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-0d53962e6c9c1b57f",
            "GroupId": "sg-0d0d8aa11953dde1a",
            "GroupOwnerId": "************",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 443,
            "ToPort": 443,
            "CidrIpv4": "10.0.0.0/16"
        }
    ]
}

VPCエンドポイント作成① (ssm)

コマンド
aws ec2 create-vpc-endpoint \
  --vpc-endpoint-type Interface \
  --vpc-id ${EC2_VPC_ID} \
  --subnet-ids ${EC2_SUBNET_ID_2} \
  --security-group-ids ${EC2_SECURITY_GROUP_ID_2} \
  --service-name com.amazonaws.ap-northeast-1.ssm
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-vpc-endpoint \
  --vpc-endpoint-type Interface \
  --vpc-id ${EC2_VPC_ID} \
  --subnet-ids ${EC2_SUBNET_ID_2} \
  --security-group-ids ${EC2_SECURITY_GROUP_ID_2} \
  --service-name com.amazonaws.ap-northeast-1.ssm
{
    "VpcEndpoint": {
        "VpcEndpointId": "vpce-02f5c18bd84d06f4f",
        "VpcEndpointType": "Interface",
        "VpcId": "vpc-04e2b134f3596a7fa",
        "ServiceName": "com.amazonaws.ap-northeast-1.ssm",
        "State": "pending",
        "RouteTableIds": [],
        "SubnetIds": [
            "subnet-0e3ef0a4057d99dac"
        ],
        "Groups": [
            {
                "GroupId": "sg-0d0d8aa11953dde1a",
                "GroupName": "ssm"
            }
        ],
        "IpAddressType": "ipv4",
        "DnsOptions": {
            "DnsRecordIpType": "ipv4"
        },
        "PrivateDnsEnabled": true,
        "RequesterManaged": false,
        "NetworkInterfaceIds": [
            "eni-0837da7f92aec65e2"
        ],
        "DnsEntries": [
            {
                "DnsName": "vpce-02f5c18bd84d06f4f-h9rx30pt.ssm.ap-northeast-1.vpce.amazonaws.com",
                "HostedZoneId": "Z2E726K9Y6RL4W"
            },
            {
                "DnsName": "vpce-02f5c18bd84d06f4f-h9rx30pt-ap-northeast-1c.ssm.ap-northeast-1.vpce.amazonaws.com",
                "HostedZoneId": "Z2E726K9Y6RL4W"
            },
            {
                "DnsName": "ssm.ap-northeast-1.amazonaws.com",
                "HostedZoneId": "ZONEIDPENDING"
            }
        ],
        "CreationTimestamp": "2024-02-15T09:00:01.544000+00:00",
        "OwnerId": "************"
    }
}

VPCエンドポイントID 取得① (ssm)

コマンド
VPC_ENDPOINT_ID_1=$( \
  aws ec2 describe-vpc-endpoints \
    --filters Name=service-name,Values="com.amazonaws.ap-northeast-1.ssm" \
    --query "VpcEndpoints[].VpcEndpointId" \
    --output text \
) \
&& echo ${VPC_ENDPOINT_ID_1}
出力
[ec2-user@ip-172-31-12-138%]$ VPC_ENDPOINT_ID_1=$( \
  aws ec2 describe-vpc-endpoints \
    --filters Name=service-name,Values="com.amazonaws.ap-northeast-1.ssm" \
    --query "VpcEndpoints[].VpcEndpointId" \
    --output text \
) \
&& echo ${VPC_ENDPOINT_ID_1}
vpce-02f5c18bd84d06f4f

VPCエンドポイント名前変更① (ssm)

コマンド
aws ec2 create-tags \
  --resources ${VPC_ENDPOINT_ID_1} \
  --tags "Key=Name,Value=ssm"

VPCエンドポイント作成② (ssmmessages)

コマンド
aws ec2 create-vpc-endpoint \
  --vpc-endpoint-type Interface \
  --vpc-id ${EC2_VPC_ID} \
  --subnet-ids ${EC2_SUBNET_ID_2} \
  --security-group-ids ${EC2_SECURITY_GROUP_ID_2} \
  --service-name com.amazonaws.ap-northeast-1.ssmmessages
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-vpc-endpoint \
  --vpc-endpoint-type Interface \
  --vpc-id ${EC2_VPC_ID} \
  --subnet-ids ${EC2_SUBNET_ID_2} \
  --security-group-ids ${EC2_SECURITY_GROUP_ID_2} \
  --service-name com.amazonaws.ap-northeast-1.ssmmessages
{
    "VpcEndpoint": {
        "VpcEndpointId": "vpce-02dffc7b59c51f193",
        "VpcEndpointType": "Interface",
        "VpcId": "vpc-04e2b134f3596a7fa",
        "ServiceName": "com.amazonaws.ap-northeast-1.ssmmessages",
        "State": "pending",
        "RouteTableIds": [],
        "SubnetIds": [
            "subnet-0e3ef0a4057d99dac"
        ],
        "Groups": [
            {
                "GroupId": "sg-0d0d8aa11953dde1a",
                "GroupName": "ssm"
            }
        ],
        "IpAddressType": "ipv4",
        "DnsOptions": {
            "DnsRecordIpType": "ipv4"
        },
        "PrivateDnsEnabled": true,
        "RequesterManaged": false,
        "NetworkInterfaceIds": [
            "eni-0ad0de9840cd1fdfa"
        ],
        "DnsEntries": [
            {
                "DnsName": "vpce-02dffc7b59c51f193-p2jx8c88.ssmmessages.ap-northeast-1.vpce.amazonaws.com",
                "HostedZoneId": "Z2E726K9Y6RL4W"
            },
            {
                "DnsName": "vpce-02dffc7b59c51f193-p2jx8c88-ap-northeast-1c.ssmmessages.ap-northeast-1.vpce.amazonaws.com",
                "HostedZoneId": "Z2E726K9Y6RL4W"
            },
            {
                "DnsName": "ssmmessages.ap-northeast-1.amazonaws.com",
                "HostedZoneId": "ZONEIDPENDING"
            }
        ],
        "CreationTimestamp": "2024-02-15T09:34:33.947000+00:00",
        "OwnerId": "************"
    }
}

VPCエンドポイントID 取得② (ssmmessages)

コマンド
VPC_ENDPOINT_ID_2=$( \
  aws ec2 describe-vpc-endpoints \
    --filters Name=service-name,Values="com.amazonaws.ap-northeast-1.ssmmessages" \
    --query "VpcEndpoints[].VpcEndpointId" \
    --output text \
) \
&& echo ${VPC_ENDPOINT_ID_2}
出力
[ec2-user@ip-172-31-12-138%]$ VPC_ENDPOINT_ID_2=$( \
  aws ec2 describe-vpc-endpoints \
    --filters Name=service-name,Values="com.amazonaws.ap-northeast-1.ssmmessages" \
    --query "VpcEndpoints[].VpcEndpointId" \
    --output text \
) \
&& echo ${VPC_ENDPOINT_ID_2}
vpce-02dffc7b59c51f193

VPCエンドポイント名前変更② (ssmmessages)

コマンド
aws ec2 create-tags \
  --resources ${VPC_ENDPOINT_ID_2} \
  --tags "Key=Name,Value=ssm-messages"

VPCエンドポイント作成③ (ec2messages)

コマンド
aws ec2 create-vpc-endpoint \
  --vpc-endpoint-type Interface \
  --vpc-id ${EC2_VPC_ID} \
  --subnet-ids ${EC2_SUBNET_ID_2} \
  --security-group-ids ${EC2_SECURITY_GROUP_ID_2} \
  --service-name com.amazonaws.ap-northeast-1.ec2messages
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-vpc-endpoint \
  --vpc-endpoint-type Interface \
  --vpc-id ${EC2_VPC_ID} \
  --subnet-ids ${EC2_SUBNET_ID_2} \
  --security-group-ids ${EC2_SECURITY_GROUP_ID_2} \
  --service-name com.amazonaws.ap-northeast-1.ec2messages
{
    "VpcEndpoint": {
        "VpcEndpointId": "vpce-0cd1d9078e3c578b2",
        "VpcEndpointType": "Interface",
        "VpcId": "vpc-04e2b134f3596a7fa",
        "ServiceName": "com.amazonaws.ap-northeast-1.ec2messages",
        "State": "pending",
        "RouteTableIds": [],
        "SubnetIds": [
            "subnet-0e3ef0a4057d99dac"
        ],
        "Groups": [
            {
                "GroupId": "sg-0d0d8aa11953dde1a",
                "GroupName": "ssm"
            }
        ],
        "IpAddressType": "ipv4",
        "DnsOptions": {
            "DnsRecordIpType": "ipv4"
        },
        "PrivateDnsEnabled": true,
        "RequesterManaged": false,
        "NetworkInterfaceIds": [
            "eni-0d86de6c676025ee6"
        ],
        "DnsEntries": [
            {
                "DnsName": "vpce-0cd1d9078e3c578b2-kdwmz3gg.ec2messages.ap-northeast-1.vpce.amazonaws.com",
                "HostedZoneId": "Z2E726K9Y6RL4W"
            },
            {
                "DnsName": "vpce-0cd1d9078e3c578b2-kdwmz3gg-ap-northeast-1c.ec2messages.ap-northeast-1.vpce.amazonaws.com",
                "HostedZoneId": "Z2E726K9Y6RL4W"
            },
            {
                "DnsName": "ec2messages.ap-northeast-1.amazonaws.com",
                "HostedZoneId": "ZONEIDPENDING"
            }
        ],
        "CreationTimestamp": "2024-02-15T09:39:51.968000+00:00",
        "OwnerId": "************"
    }
}

VPCエンドポイントID 取得③ (ec2messages)

コマンド
VPC_ENDPOINT_ID_3=$( \
  aws ec2 describe-vpc-endpoints \
    --filters Name=service-name,Values="com.amazonaws.ap-northeast-1.ec2messages" \
    --query "VpcEndpoints[].VpcEndpointId" \
    --output text \
) \
&& echo ${VPC_ENDPOINT_ID_3}
出力
[ec2-user@ip-172-31-12-138%]$ VPC_ENDPOINT_ID_3=$( \
  aws ec2 describe-vpc-endpoints \
    --filters Name=service-name,Values="com.amazonaws.ap-northeast-1.ec2messages" \
    --query "VpcEndpoints[].VpcEndpointId" \
    --output text \
) \
&& echo ${VPC_ENDPOINT_ID_3}
vpce-0cd1d9078e3c578b2

VPCエンドポイント名前変更③ (ec2messages)

コマンド
aws ec2 create-tags \
  --resources ${VPC_ENDPOINT_ID_3} \
  --tags "Key=Name,Value=ec2messages"

セッションマネージャ接続確認

hands-on-beginers-Step3.drawio.png
セッションマネージャでログインできることを確認

コマンド
whoami
出力
sh-5.2$ whoami
ssm-user

Amazon VPC ハンズオン⑤ VPC外サービスへの接続方法 - 2

Gateway型 Endpoint

S3バケット作成

コマンド
aws s3 mb s3://hands-on-beginners-bucket-20240215
出力
[ec2-user@ip-172-31-12-138%]$ aws s3 mb s3://hands-on-beginners-bucket-20240215
make_bucket: hands-on-beginners-bucket-20240215

IAMロール(handson-ssm)にS3管理ポリシーをアタッチ

コマンド
aws iam attach-role-policy \
  --role-name handson-ssm \
  --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
出力
[ec2-user@ip-172-31-12-138%]$ aws iam attach-role-policy \
  --role-name handson-ssm \
  --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

S3エンドポイント作成

コマンド
aws ec2 create-vpc-endpoint \
  --vpc-endpoint-type Gateway \
  --vpc-id ${EC2_VPC_ID} \
  --route-table-ids ${EC2_ROUTE_TABLE_ID} ${EC2_ROUTE_TABLE_MAIN_ID} \
  --service-name com.amazonaws.ap-northeast-1.s3
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 create-vpc-endpoint \
  --vpc-endpoint-type Gateway \
  --vpc-id ${EC2_VPC_ID} \
  --route-table-ids ${EC2_ROUTE_TABLE_ID} ${EC2_ROUTE_TABLE_MAIN_ID} \
  --service-name com.amazonaws.ap-northeast-1.s3
{
    "VpcEndpoint": {
        "VpcEndpointId": "vpce-071f7439e32b555d9",
        "VpcEndpointType": "Gateway",
        "VpcId": "vpc-04e2b134f3596a7fa",
        "ServiceName": "com.amazonaws.ap-northeast-1.s3",
        "State": "available",
        "PolicyDocument": "{\"Version\":\"2008-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"*\",\"Resource\":\"*\"}]}",
        "RouteTableIds": [
            "rtb-07ed7e843af9ac31a",
            "rtb-091437895557c837b"
        ],
        "SubnetIds": [],
        "Groups": [],
        "PrivateDnsEnabled": false,
        "RequesterManaged": false,
        "NetworkInterfaceIds": [],
        "DnsEntries": [],
        "CreationTimestamp": "2024-02-15T10:53:20+00:00",
        "OwnerId": "************"
    }
}

S3エンドポイント ID取得

コマンド
VPC_ENDPOINT_ID_4=$( \
  aws ec2 describe-vpc-endpoints \
    --filters Name=service-name,Values="com.amazonaws.ap-northeast-1.s3" \
    --query "VpcEndpoints[].VpcEndpointId" \
    --output text \
) \
&& echo ${VPC_ENDPOINT_ID_4}
出力
[ec2-user@ip-172-31-12-138%]$ VPC_ENDPOINT_ID_4=$( \
  aws ec2 describe-vpc-endpoints \
    --filters Name=service-name,Values="com.amazonaws.ap-northeast-1.s3" \
    --query "VpcEndpoints[].VpcEndpointId" \
    --output text \
) \
&& echo ${VPC_ENDPOINT_ID_4}
vpce-071f7439e32b555d9

S3エンドポイント名前変更

コマンド
aws ec2 create-tags \
  --resources ${VPC_ENDPOINT_ID_4} \
  --tags "Key=Name,Value=s3-gateway"

S3接続確認

hands-on-beginers-Step4.drawio.png

コマンド
aws s3 ls --region ap-northeast-1
出力
sh-5.2$ aws s3 ls --region ap-northeast-1
2024-02-15 10:29:28 hands-on-beginners-bucket-20240215

環境削除

VPCエンドポイント削除

コマンド
aws ec2 delete-vpc-endpoints \
  --vpc-endpoint-ids \
  ${VPC_ENDPOINT_ID_1} \
  ${VPC_ENDPOINT_ID_2} \
  ${VPC_ENDPOINT_ID_3} \
  ${VPC_ENDPOINT_ID_4}
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 delete-vpc-endpoints \
  --vpc-endpoint-ids \
  ${VPC_ENDPOINT_ID_1} \
  ${VPC_ENDPOINT_ID_2} \
  ${VPC_ENDPOINT_ID_3} \
  ${VPC_ENDPOINT_ID_4}
{
    "Unsuccessful": []
}

S3バケット削除

コマンド
aws s3 rb s3://hands-on-beginners-bucket-20240215 --force  
出力
[ec2-user@ip-172-31-12-138%]$ aws s3 rb s3://hands-on-beginners-bucket-20240215 --force 
remove_bucket: hands-on-beginners-bucket-20240215

EC2 ID確認

コマンド
EC2_INSTANCE_ID=$( \
  aws ec2 describe-instances \
    --filters Name=tag:Name,Values="Web"  \
    --query "Reservations[*].Instances[*].[InstanceId]" \
    --output text
) \
&& echo ${EC2_INSTANCE_ID} 

Private_EC2_INSTANCE_ID=$( \
  aws ec2 describe-instances \
    --filters Name=tag:Name,Values="Internal"  \
    --query "Reservations[*].Instances[*].[InstanceId]" \
    --output text
) \
&& echo ${Private_EC2_INSTANCE_ID} 
出力
[ec2-user@ip-172-31-12-138%]$ EC2_INSTANCE_ID=$( \
  aws ec2 describe-instances \
    --filters Name=tag:Name,Values="Web"  \
    --query "Reservations[*].Instances[*].[InstanceId]" \
    --output text
) \
&& echo ${EC2_INSTANCE_ID} 

Private_EC2_INSTANCE_ID=$( \
  aws ec2 describe-instances \
    --filters Name=tag:Name,Values="Internal"  \
    --query "Reservations[*].Instances[*].[InstanceId]" \
    --output text
) \
&& echo ${Private_EC2_INSTANCE_ID} 
i-052d55832c3618c67
i-0661675e581acab6c

EC2削除

コマンド
aws ec2 terminate-instances \
  --region ap-northeast-1 \
  --instance-ids ${EC2_INSTANCE_ID}  ${Private_EC2_INSTANCE_ID} 
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 terminate-instances \
  --region ap-northeast-1 \
  --instance-ids ${EC2_INSTANCE_ID}  ${Private_EC2_INSTANCE_ID}
{
    "TerminatingInstances": [
        {
            "CurrentState": {
                "Code": 32,
                "Name": "shutting-down"
            },
            "InstanceId": "i-052d55832c3618c67",
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        },
        {
            "CurrentState": {
                "Code": 32,
                "Name": "shutting-down"
            },
            "InstanceId": "i-0661675e581acab6c",
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}

Security Group 削除

コマンド
aws ec2 delete-security-group \
  --group-id ${EC2_SECURITY_GROUP_ID}

aws ec2 delete-security-group \
  --group-id ${EC2_SECURITY_GROUP_ID_2}

IAM ROLEからインスタンスプロファイルを削除

コマンド
aws iam remove-role-from-instance-profile \
  --role-name handson-ssm \
  --instance-profile-name handson-ssm

インスタンスプロファイル削除

コマンド
aws iam delete-instance-profile \
  --instance-profile-name handson-ssm

IAMロールから管理ポリシーをでタッチ

コマンド
aws iam detach-role-policy \
  --role-name handson-ssm \
  --policy-arn arn:aws:iam::aws:policy/AmazonSSMFullAccess

aws iam detach-role-policy \
  --role-name handson-ssm \
  --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

IAM Role 削除

コマンド
aws iam delete-role --role-name handson-ssm

NAT Gateway 削除

コマンド
aws ec2 delete-nat-gateway \
  --nat-gateway-id ${NATGATEWAY_ID}
出力
[ec2-user@ip-172-31-12-138%]$ aws ec2 delete-nat-gateway \
  --nat-gateway-id ${NATGATEWAY_ID}
{
    "NatGatewayId": "nat-07ab3507790c39d60"
}

Elastic IP 削除(解放)

コマンド
aws ec2 release-address --allocation-id ${EC2_ELASTIC_IP_ID}

サブネット削除

コマンド
aws ec2 delete-subnet --subnet-id ${EC2_SUBNET_ID_1}
aws ec2 delete-subnet --subnet-id ${EC2_SUBNET_ID_2}
aws ec2 delete-subnet --subnet-id ${EC2_SUBNET_ID_3}
aws ec2 delete-subnet --subnet-id ${EC2_SUBNET_ID_4}

ルーティングテーブル削除

コマンド
aws ec2 delete-route-table --route-table-id ${EC2_ROUTE_TABLE_ID}

Internet Gatewayを VPC からデタッチ

コマンド
aws ec2 detach-internet-gateway --internet-gateway-id ${EC2_INTERNET_GATEWAY_ID} --vpc-id ${EC2_VPC_ID}

Internet Gateway削除

コマンド
aws ec2 delete-internet-gateway --internet-gateway-id ${EC2_INTERNET_GATEWAY_ID}

VPC削除

コマンド
aws ec2 delete-vpc --vpc-id ${EC2_VPC_ID}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0