「AWS Hands-on for Beginners AWS Systems Managerを使ったサーバ管理はじめの一歩編」をAWS CLIでやってみる

https://pages.awscloud.com/JAPAN-event-OE-Hands-on-for-Beginners-systems-manager-2022-reg-event.html?trk=aws_introduction_page

上記、「AWS Hands-on for Beginners AWS Systems Managerを使ったサーバ管理はじめの一歩編」 をAWS CLIでやってみる
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3297641/80af7d1f-f5cb-4cb0-4d0e-1c2775acc1e3.png)
ハンズオンから引用

# 02 ハンズオンの事前準備
## 変数設定
```bash:コマンド
# スタック名
STACK_NAME="h4b-stack" \
&& echo ${STACK_NAME}

# スタックテンプレート名
TEMPLATE_NAME="h4b_ssm_basic_template.json" \
&& echo ${TEMPLATE_NAME}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # スタック名
[cloudshell-user@ip-10-134-0-112 ~]$ STACK_NAME="h4b-stack" \
> && echo ${STACK_NAME}
h4b-stack
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # スタックテンプレート名
[cloudshell-user@ip-10-134-0-112 ~]$ TEMPLATE_NAME="h4b_ssm_basic_template.json" \
> && echo ${TEMPLATE_NAME}
h4b_ssm_basic_template.json
```
## CloudFomation スタックの作成
```bash:コマンド
aws cloudformation create-stack \
    --stack-name ${STACK_NAME} \
    --template-body file://${TEMPLATE_NAME}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws cloudformation create-stack \
>     --stack-name ${STACK_NAME} \
>     --template-body file://${TEMPLATE_NAME}
{
    "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b"
}
```
## リソース一覧の確認
```bash:コマンド
aws cloudformation describe-stack-resources \
    --stack-name ${STACK_NAME} \
    --no-cli-pager
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws cloudformation describe-stack-resources \
>     --stack-name ${STACK_NAME} \
>     --no-cli-pager
{
    "StackResources": [
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "AttachGateway",
            "PhysicalResourceId": "IGW|vpc-06476bfe5756ad44f",
            "ResourceType": "AWS::EC2::VPCGatewayAttachment",
            "Timestamp": "2024-08-04T05:19:19.243000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "EC2SecurityGroup",
            "PhysicalResourceId": "sg-0e9c7e1e3b2a8bc4b",
            "ResourceType": "AWS::EC2::SecurityGroup",
            "Timestamp": "2024-08-04T05:19:19.937000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "EIP",
            "PhysicalResourceId": "54.248.12.156",
            "ResourceType": "AWS::EC2::EIP",
            "Timestamp": "2024-08-04T05:19:20.242000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "InternetGateway",
            "PhysicalResourceId": "igw-088524bd1be9d06c7",
            "ResourceType": "AWS::EC2::InternetGateway",
            "Timestamp": "2024-08-04T05:19:20.388000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "NATGateway",
            "PhysicalResourceId": "nat-0b5a40688a24a7daa",
            "ResourceType": "AWS::EC2::NatGateway",
            "Timestamp": "2024-08-04T05:21:25.038000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "PrivateSubnet",
            "PhysicalResourceId": "subnet-0cb61d3b492f22bf3",
            "ResourceType": "AWS::EC2::Subnet",
            "Timestamp": "2024-08-04T05:19:21.387000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "PublicSubnet",
            "PhysicalResourceId": "subnet-0db11eaa0e0dbcb85",
            "ResourceType": "AWS::EC2::Subnet",
            "Timestamp": "2024-08-04T05:19:21.421000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "RouteForPrivate",
            "PhysicalResourceId": "rtb-0224117b045b9f147|0.0.0.0/0",
            "ResourceType": "AWS::EC2::Route",
            "Timestamp": "2024-08-04T05:21:27.474000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "RouteForPublic",
            "PhysicalResourceId": "rtb-0b4cad6abbec038e1|0.0.0.0/0",
            "ResourceType": "AWS::EC2::Route",
            "Timestamp": "2024-08-04T05:19:30.418000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "RouteTableforPrivate",
            "PhysicalResourceId": "rtb-0224117b045b9f147",
            "ResourceType": "AWS::EC2::RouteTable",
            "Timestamp": "2024-08-04T05:19:28.326000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "RouteTableforPublic",
            "PhysicalResourceId": "rtb-0b4cad6abbec038e1",
            "ResourceType": "AWS::EC2::RouteTable",
            "Timestamp": "2024-08-04T05:19:28.327000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "SubnetRouteTableAssociation1",
            "PhysicalResourceId": "rtbassoc-0f865ab62bc8e11b3",
            "ResourceType": "AWS::EC2::SubnetRouteTableAssociation",
            "Timestamp": "2024-08-04T05:19:24.334000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "SubnetRouteTableAssociation2",
            "PhysicalResourceId": "rtbassoc-018cf8ac61281b346",
            "ResourceType": "AWS::EC2::SubnetRouteTableAssociation",
            "Timestamp": "2024-08-04T05:19:21.417000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "h4b-stack",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/h4b-stack/0e3d1fe0-5221-11ef-a207-0a6ce16f513b",
            "LogicalResourceId": "VPC",
            "PhysicalResourceId": "vpc-06476bfe5756ad44f",
            "ResourceType": "AWS::EC2::VPC",
            "Timestamp": "2024-08-04T05:19:16.147000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        }
    ]
}
```
# 03 Systems Manager環境のセットアップ
## IAMロール設定
### 変数設定
```bash:コマンド
# IAMロール名
IAM_ROLE_NAME="h4b-role" \
&& echo ${IAM_ROLE_NAME}

# アタッチポリシー名
IAM_ATTACH_POLICY_NAME="AmazonSSMManagedInstanceCore" \
&& echo ${IAM_ATTACH_POLICY_NAME}

# アタッチポリシーARN
IAM_POLICY_ARN="arn:aws:iam::aws:policy/${IAM_ATTACH_POLICY_NAME}" \
&& echo ${IAM_POLICY_ARN}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # IAMロール名
[cloudshell-user@ip-10-134-0-112 ~]$ IAM_ROLE_NAME="h4b-role" \
> && echo ${IAM_ROLE_NAME}
h4b-role
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # アタッチポリシー名
[cloudshell-user@ip-10-134-0-112 ~]$ IAM_ATTACH_POLICY_NAME="AmazonSSMManagedInstanceCore" \
> && echo ${IAM_ATTACH_POLICY_NAME}
AmazonSSMManagedInstanceCore
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # アタッチポリシーARN
[cloudshell-user@ip-10-134-0-112 ~]$ IAM_POLICY_ARN="arn:aws:iam::aws:policy/${IAM_ATTACH_POLICY_NAME}" \
> && echo ${IAM_POLICY_ARN}
arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
```
### IAMロールの作成
```bash:コマンド
# 信頼関係ポリシードキュメントの作成
ASSUME_ROLE_POLICY_DOCUMENT=$(cat << EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "ec2.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
EOF
) \
&& echo ${ASSUME_ROLE_POLICY_DOCUMENT}

# JSONフォーマットの確認
echo ${ASSUME_ROLE_POLICY_DOCUMENT} | python -m json.tool

# IAMロールの作成
aws iam create-role \
    --role-name ${IAM_ROLE_NAME} \
    --assume-role-policy-document "${ASSUME_ROLE_POLICY_DOCUMENT}"

# ARN取得
IAM_ROLE_ARN=$(
    aws iam get-role \
        --role-name ${IAM_ROLE_NAME} \
        --query 'Role.Arn' \
        --output text
) \
&& echo ${IAM_ROLE_ARN}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # 信頼関係ポリシードキュメントの作成
[cloudshell-user@ip-10-134-0-112 ~]$ ASSUME_ROLE_POLICY_DOCUMENT=$(cat << EOF
> {
>     "Version": "2012-10-17",
>     "Statement": [
>         {
>             "Effect": "Allow",
>             "Principal": {
>                 "Service": "ec2.amazonaws.com"
>             },
>             "Action": "sts:AssumeRole"
>         }
>     ]
> }
> EOF
> ) \
> && echo ${ASSUME_ROLE_POLICY_DOCUMENT}
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-134-0-112 ~]$ echo ${ASSUME_ROLE_POLICY_DOCUMENT} | python -m json.tool
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "ec2.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # IAMロールの作成
[cloudshell-user@ip-10-134-0-112 ~]$ aws iam create-role \
>     --role-name ${IAM_ROLE_NAME} \
>     --assume-role-policy-document "${ASSUME_ROLE_POLICY_DOCUMENT}"
{
    "Role": {
        "Path": "/",
        "RoleName": "h4b-role",
        "RoleId": "AROAWFKRCMKOYIP4APEYP",
        "Arn": "arn:aws:iam::999999999999:role/h4b-role",
        "CreateDate": "2024-08-04T05:22:52+00:00",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "ec2.amazonaws.com"
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        }
    }
}
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # ARN取得
[cloudshell-user@ip-10-134-0-112 ~]$ IAM_ROLE_ARN=$(
>     aws iam get-role \
>         --role-name ${IAM_ROLE_NAME} \
>         --query 'Role.Arn' \
>         --output text
> ) \
> && echo ${IAM_ROLE_ARN}
arn:aws:iam::999999999999:role/h4b-role
```
### IAMポリシーのアタッチ
```bash:コマンド
# IAMロールにポリシーをアタッチ
aws iam attach-role-policy \
    --role-name ${IAM_ROLE_NAME} \
    --policy-arn ${IAM_POLICY_ARN}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # IAMロールにポリシーをアタッチ
[cloudshell-user@ip-10-134-0-112 ~]$ aws iam attach-role-policy \
>     --role-name ${IAM_ROLE_NAME} \
>     --policy-arn ${IAM_POLICY_ARN}
```
## EC2インスタンスの作成
### 変数の設定
```bash:コマンド
# EC2インスタンス名
EC2_INSTANCE_NAME="h4b-instance" \
&& echo ${EC2_INSTANCE_NAME}

# インスタンスプロファイル名
IAM_INSTANCE_PROFILE_NAME="h4b-profile" \
&& echo ${IAM_INSTANCE_PROFILE_NAME}

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

# EC2インスタンスイメージ
EC2_IMAGE_ID="resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2" \
&& echo ${EC2_IMAGE_ID}

# セキュリティグループID
LOGICAL_RESOURCE_ID="EC2SecurityGroup" \
&& echo ${LOGICAL_RESOURCE_ID}

EC2_SECURITY_GROUP_ID=$(
    aws cloudformation describe-stack-resources \
        --stack-name ${STACK_NAME} \
        --logical-resource-id ${LOGICAL_RESOURCE_ID} \
        --query "StackResources[*].PhysicalResourceId" \
        --output text
) \
&& echo ${EC2_SECURITY_GROUP_ID}

# サブネットID
LOGICAL_RESOURCE_ID="PrivateSubnet" \
&& echo ${LOGICAL_RESOURCE_ID}

PRIVATE_SUBNET_ID=$(
    aws cloudformation describe-stack-resources \
        --stack-name ${STACK_NAME} \
        --logical-resource-id ${LOGICAL_RESOURCE_ID} \
        --query "StackResources[*].PhysicalResourceId" \
        --output text
) \
&& echo ${PRIVATE_SUBNET_ID}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # EC2インスタンス名
[cloudshell-user@ip-10-134-0-112 ~]$ EC2_INSTANCE_NAME="h4b-instance" \
> && echo ${EC2_INSTANCE_NAME}
h4b-instance
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # インスタンスプロファイル名
[cloudshell-user@ip-10-134-0-112 ~]$ IAM_INSTANCE_PROFILE_NAME="h4b-profile" \
> && echo ${IAM_INSTANCE_PROFILE_NAME}
h4b-profile
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # EC2インスタンスタイプ
[cloudshell-user@ip-10-134-0-112 ~]$ EC2_INSTANCE_TYPE="t2.micro" \
> && echo ${EC2_INSTANCE_TYPE}
t2.micro
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # EC2インスタンスイメージ
[cloudshell-user@ip-10-134-0-112 ~]$ 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-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # セキュリティグループID
[cloudshell-user@ip-10-134-0-112 ~]$ LOGICAL_RESOURCE_ID="EC2SecurityGroup" \
> && echo ${LOGICAL_RESOURCE_ID}
EC2SecurityGroup
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ EC2_SECURITY_GROUP_ID=$(
>     aws cloudformation describe-stack-resources \
>         --stack-name ${STACK_NAME} \
>         --logical-resource-id ${LOGICAL_RESOURCE_ID} \
>         --query "StackResources[*].PhysicalResourceId" \
>         --output text
> ) \
> && echo ${EC2_SECURITY_GROUP_ID}
sg-0e9c7e1e3b2a8bc4b
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # サブネットID
[cloudshell-user@ip-10-134-0-112 ~]$ LOGICAL_RESOURCE_ID="PrivateSubnet" \
> && echo ${LOGICAL_RESOURCE_ID}
PrivateSubnet
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ PRIVATE_SUBNET_ID=$(
>     aws cloudformation describe-stack-resources \
>         --stack-name ${STACK_NAME} \
>         --logical-resource-id ${LOGICAL_RESOURCE_ID} \
>         --query "StackResources[*].PhysicalResourceId" \
>         --output text
> ) \
> && echo ${PRIVATE_SUBNET_ID}
subnet-0cb61d3b492f22bf3
```
### EC2インスタンス作成
```bash:コマンド
# インスタンスプロファイル作成
aws iam create-instance-profile \
    --instance-profile-name ${IAM_INSTANCE_PROFILE_NAME}

# インスタンスプロファイルへのロールのアタッチ
aws iam add-role-to-instance-profile \
    --instance-profile-name ${IAM_INSTANCE_PROFILE_NAME} \
    --role-name ${IAM_ROLE_NAME}

# インスタンス作成
aws ec2 run-instances \
    --image-id ${EC2_IMAGE_ID} \
    --instance-type ${EC2_INSTANCE_TYPE} \
    --security-group-ids ${EC2_SECURITY_GROUP_ID} \
    --subnet-id ${PRIVATE_SUBNET_ID} \
    --iam-instance-profile Name=${IAM_INSTANCE_PROFILE_NAME} \
    --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${EC2_INSTANCE_NAME}}]" \
    --no-cli-pager

# インスタンスID
EC2_INSTANCE_ID=$( \
    aws ec2 describe-instances \
        --filters Name=tag:Name,Values=${EC2_INSTANCE_NAME}  \
        --query "Reservations[*].Instances[*].[InstanceId]" \
        --output text
) \
&& echo ${EC2_INSTANCE_ID} 
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # インスタンスプロファイル作成
[cloudshell-user@ip-10-134-0-112 ~]$ aws iam create-instance-profile \
>     --instance-profile-name ${IAM_INSTANCE_PROFILE_NAME}
{
    "InstanceProfile": {
        "Path": "/",
        "InstanceProfileName": "h4b-profile",
        "InstanceProfileId": "AIPAWFKRCMKO6YENL5V3I",
        "Arn": "arn:aws:iam::999999999999:instance-profile/h4b-profile",
        "CreateDate": "2024-08-04T05:24:13+00:00",
        "Roles": []
    }
}
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # インスタンスプロファイルへのロールのアタッチ
[cloudshell-user@ip-10-134-0-112 ~]$ aws iam add-role-to-instance-profile \
>     --instance-profile-name ${IAM_INSTANCE_PROFILE_NAME} \
>     --role-name ${IAM_ROLE_NAME}
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # インスタンス作成
[cloudshell-user@ip-10-134-0-112 ~]$ aws ec2 run-instances \
>     --image-id ${EC2_IMAGE_ID} \
>     --instance-type ${EC2_INSTANCE_TYPE} \
>     --security-group-ids ${EC2_SECURITY_GROUP_ID} \
>     --subnet-id ${PRIVATE_SUBNET_ID} \
>     --iam-instance-profile Name=${IAM_INSTANCE_PROFILE_NAME} \
>     --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${EC2_INSTANCE_NAME}}]" \
>     --no-cli-pager
{
    "Groups": [],
    "Instances": [
        {
            "AmiLaunchIndex": 0,
            "ImageId": "ami-092957e65e64cc357",
            "InstanceId": "i-05a444e226ac72648",
            "InstanceType": "t2.micro",
            "LaunchTime": "2024-08-04T05:24:26+00:00",
            "Monitoring": {
                "State": "disabled"
            },
            "Placement": {
                "AvailabilityZone": "ap-northeast-1c",
                "GroupName": "",
                "Tenancy": "default"
            },
            "PrivateDnsName": "ip-10-0-1-180.ap-northeast-1.compute.internal",
            "PrivateIpAddress": "10.0.1.180",
            "ProductCodes": [],
            "PublicDnsName": "",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "StateTransitionReason": "",
            "SubnetId": "subnet-0cb61d3b492f22bf3",
            "VpcId": "vpc-06476bfe5756ad44f",
            "Architecture": "x86_64",
            "BlockDeviceMappings": [],
            "ClientToken": "4188ea30-66f3-4a14-9357-51b0937f6c04",
            "EbsOptimized": false,
            "EnaSupport": true,
            "Hypervisor": "xen",
            "IamInstanceProfile": {
                "Arn": "arn:aws:iam::999999999999:instance-profile/h4b-profile",
                "Id": "AIPAWFKRCMKO6YENL5V3I"
            },
            "NetworkInterfaces": [
                {
                    "Attachment": {
                        "AttachTime": "2024-08-04T05:24:26+00:00",
                        "AttachmentId": "eni-attach-0651e4d2959874a27",
                        "DeleteOnTermination": true,
                        "DeviceIndex": 0,
                        "Status": "attaching",
                        "NetworkCardIndex": 0
                    },
                    "Description": "",
                    "Groups": [
                        {
                            "GroupName": "h4b-ec2-sg",
                            "GroupId": "sg-0e9c7e1e3b2a8bc4b"
                        }
                    ],
                    "Ipv6Addresses": [],
                    "MacAddress": "0a:20:0a:e8:a8:73",
                    "NetworkInterfaceId": "eni-0a7a7a159a9f0d537",
                    "OwnerId": "999999999999",
                    "PrivateDnsName": "ip-10-0-1-180.ap-northeast-1.compute.internal",
                    "PrivateIpAddress": "10.0.1.180",
                    "PrivateIpAddresses": [
                        {
                            "Primary": true,
                            "PrivateDnsName": "ip-10-0-1-180.ap-northeast-1.compute.internal",
                            "PrivateIpAddress": "10.0.1.180"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Status": "in-use",
                    "SubnetId": "subnet-0cb61d3b492f22bf3",
                    "VpcId": "vpc-06476bfe5756ad44f",
                    "InterfaceType": "interface"
                }
            ],
            "RootDeviceName": "/dev/xvda",
            "RootDeviceType": "ebs",
            "SecurityGroups": [
                {
                    "GroupName": "h4b-ec2-sg",
                    "GroupId": "sg-0e9c7e1e3b2a8bc4b"
                }
            ],
            "SourceDestCheck": true,
            "StateReason": {
                "Code": "pending",
                "Message": "pending"
            },
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "h4b-instance"
                }
            ],
            "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-0a9c865186d0797ab"
}
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # インスタンスID
[cloudshell-user@ip-10-134-0-112 ~]$ EC2_INSTANCE_ID=$( \
>     aws ec2 describe-instances \
>         --filters Name=tag:Name,Values=${EC2_INSTANCE_NAME}  \
>         --query "Reservations[*].Instances[*].[InstanceId]" \
>         --output text
> ) \
> && echo ${EC2_INSTANCE_ID} 
i-05a444e226ac72648
```
## フリートマネージャー
### インスタンスの管理
```bash:コマンド
# インスタンスの管理
aws ssm describe-instance-information
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # インスタンスの管理
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm describe-instance-information
{
    "InstanceInformationList": [
        {
            "InstanceId": "i-05a444e226ac72648",
            "PingStatus": "Online",
            "LastPingDateTime": "2024-08-04T05:24:56.963000+00:00",
            "AgentVersion": "3.3.380.0",
            "IsLatestVersion": false,
            "PlatformType": "Linux",
            "PlatformName": "Amazon Linux",
            "PlatformVersion": "2",
            "ResourceType": "EC2Instance",
            "IPAddress": "10.0.1.180",
            "ComputerName": "ip-10-0-1-180.ap-northeast-1.compute.internal",
            "SourceId": "i-05a444e226ac72648",
            "SourceType": "AWS::EC2::Instance"
        }
    ]
}
```
# 04 SSM Agentの自動更新とインベントリデータの収集
## SSM Agentの自動更新
### SSM Agentの自動更新
```bash:コマンド
aws ssm create-association \
    --name "AWS-UpdateSSMAgent" \
    --targets "Key=InstanceIds,Values=*" \
    --schedule-expression "rate(14 days)" \
    --association-name "SystemAssociationForSsmAgentUpdate"
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm create-association \
>     --name "AWS-UpdateSSMAgent" \
>     --targets "Key=InstanceIds,Values=*" \
>     --schedule-expression "rate(14 days)" \
>     --association-name "SystemAssociationForSsmAgentUpdate"
{
    "AssociationDescription": {
        "Name": "AWS-UpdateSSMAgent",
        "AssociationVersion": "1",
        "Date": "2024-08-04T05:25:37.245000+00:00",
        "LastUpdateAssociationDate": "2024-08-04T05:25:37.245000+00:00",
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Creating"
        },
        "DocumentVersion": "$DEFAULT",
        "AssociationId": "56f1b789-41b9-485f-8ecc-e03eb3078bcf",
        "Targets": [
            {
                "Key": "InstanceIds",
                "Values": [
                    "*"
                ]
            }
        ],
        "ScheduleExpression": "rate(14 days)",
        "AssociationName": "SystemAssociationForSsmAgentUpdate",
        "ApplyOnlyAtCronInterval": false
    }
}
```
### Agentがバージョンアップされたことの確認
```bash:コマンド
# インスタンスの管理
aws ssm describe-instance-information
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # インスタンスの管理
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm describe-instance-information
{
    "InstanceInformationList": [
        {
            "InstanceId": "i-05a444e226ac72648",
            "PingStatus": "Online",
            "LastPingDateTime": "2024-08-04T05:25:58.907000+00:00",
            "AgentVersion": "3.3.551.0",
            "IsLatestVersion": true,
            "PlatformType": "Linux",
            "PlatformName": "Amazon Linux",
            "PlatformVersion": "2",
            "ResourceType": "EC2Instance",
            "IPAddress": "10.0.1.180",
            "ComputerName": "ip-10-0-1-180.ap-northeast-1.compute.internal",
            "AssociationStatus": "Success",
            "LastAssociationExecutionDate": "2024-08-04T05:26:03.372000+00:00",
            "LastSuccessfulAssociationExecutionDate": "2024-08-04T05:26:03.372000+00:00",
            "AssociationOverview": {
                "DetailedStatus": "Success",
                "InstanceAssociationStatusAggregatedCount": {
                    "Success": 1
                }
            },
            "SourceId": "i-05a444e226ac72648",
            "SourceType": "AWS::EC2::Instance"
        }
    ]
}
```
## インベントリの設定
### インベントリの設定
```bash:コマンド
# インベントリの設定
aws ssm create-association \
    --name "AWS-GatherSoftwareInventory" \
    --targets "Key=InstanceIds,Values=*" \
    --parameters "applications=Enabled,awsComponents=Enabled,billingInfo=Enabled,customInventory=Enabled,files='',instanceDetailedInformation=Enabled,networkConfig=Enabled,services=Enabled,windowsRegistry='',windowsRoles=Enabled,windowsUpdates=Enabled" \
    --schedule-expression "rate(30 minutes)" \
    --association-name "Inventory-Association" \
    --no-cli-pager
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # インベントリの設定
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm create-association \
>     --name "AWS-GatherSoftwareInventory" \
>     --targets "Key=InstanceIds,Values=*" \
>     --parameters "applications=Enabled,awsComponents=Enabled,billingInfo=Enabled,customInventory=Enabled,files='',instanceDetailedInformation=Enabled,networkConfig=Enabled,services=Enabled,windowsRegistry='',windowsRoles=Enabled,windowsUpdates=Enabled" \
>     --schedule-expression "rate(30 minutes)" \
>     --association-name "Inventory-Association" \
>     --no-cli-pager
{
    "AssociationDescription": {
        "Name": "AWS-GatherSoftwareInventory",
        "AssociationVersion": "1",
        "Date": "2024-08-04T05:26:55.692000+00:00",
        "LastUpdateAssociationDate": "2024-08-04T05:26:55.692000+00:00",
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Creating"
        },
        "DocumentVersion": "$DEFAULT",
        "Parameters": {
            "applications": [
                "Enabled"
            ],
            "awsComponents": [
                "Enabled"
            ],
            "billingInfo": [
                "Enabled"
            ],
            "customInventory": [
                "Enabled"
            ],
            "files": [
                ""
            ],
            "instanceDetailedInformation": [
                "Enabled"
            ],
            "networkConfig": [
                "Enabled"
            ],
            "services": [
                "Enabled"
            ],
            "windowsRegistry": [
                ""
            ],
            "windowsRoles": [
                "Enabled"
            ],
            "windowsUpdates": [
                "Enabled"
            ]
        },
        "AssociationId": "d273a574-d672-494d-9e61-d10eb5c8d2c7",
        "Targets": [
            {
                "Key": "InstanceIds",
                "Values": [
                    "*"
                ]
            }
        ],
        "ScheduleExpression": "rate(30 minutes)",
        "AssociationName": "Inventory-Association",
        "ApplyOnlyAtCronInterval": false
    }
}
```
### インベントリの検索
```bash:コマンド
aws ssm get-inventory \
    --query "Entities[?Data.\"AWS:InstanceInformation\".Content[?AgentType=='amazon-ssm-agent' && AgentVersion<'3.4' && AgentVersion>'3.3.200']]"
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm get-inventory \
>     --query "Entities[?Data.\"AWS:InstanceInformation\".Content[?AgentType=='amazon-ssm-agent' && AgentVersion<'3.4' && AgentVersion>'3.3.200']]"
[
    {
        "Id": "i-05a444e226ac72648",
        "Data": {
            "AWS:InstanceInformation": {
                "TypeName": "AWS:InstanceInformation",
                "SchemaVersion": "1.0",
                "CaptureTime": "2024-08-04T05:25:58Z",
                "Content": [
                    {
                        "AgentType": "amazon-ssm-agent",
                        "AgentVersion": "3.3.551.0",
                        "ComputerName": "ip-10-0-1-180.ap-northeast-1.compute.internal",
                        "InstanceId": "i-05a444e226ac72648",
                        "InstanceStatus": "Active",
                        "IpAddress": "10.0.1.180",
                        "PlatformName": "Amazon Linux",
                        "PlatformType": "Linux",
                        "PlatformVersion": "2",
                        "ResourceType": "EC2Instance"
                    }
                ]
            }
        }
    }
]
```
## ステートマネージャーの確認
```bash:コマンド
# State Managerの確認
aws ssm list-associations
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # State Managerの確認
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm list-associations
{
    "Associations": [
        {
            "Name": "AWS-UpdateSSMAgent",
            "AssociationId": "56f1b789-41b9-485f-8ecc-e03eb3078bcf",
            "AssociationVersion": "1",
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "*"
                    ]
                }
            ],
            "LastExecutionDate": "2024-08-04T05:26:03.372000+00:00",
            "Overview": {
                "Status": "Success",
                "DetailedStatus": "Success",
                "AssociationStatusAggregatedCount": {
                    "Success": 1
                }
            },
            "ScheduleExpression": "rate(14 days)",
            "AssociationName": "SystemAssociationForSsmAgentUpdate"
        },
        {
            "Name": "AWS-GatherSoftwareInventory",
            "AssociationId": "d273a574-d672-494d-9e61-d10eb5c8d2c7",
            "AssociationVersion": "1",
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "*"
                    ]
                }
            ],
            "LastExecutionDate": "2024-08-04T05:27:04.697000+00:00",
            "Overview": {
                "Status": "Success",
                "AssociationStatusAggregatedCount": {
                    "Success": 1
                }
            },
            "ScheduleExpression": "rate(30 minutes)",
            "AssociationName": "Inventory-Association"
        }
    ]
}
```
# 05 セッションマネージャーを使ったサーバ接続
## セッションマネージャーを使ったサーバログイン
```bash:コマンド
aws ssm start-session \
    --target ${EC2_INSTANCE_ID} 
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm start-session \
>     --target ${EC2_INSTANCE_ID} 

Starting session with SessionId: admin-hkkxvenmjmrvis6odrqsyy4kvm
sh-4.2$ pwd
/usr/bin
sh-4.2$ whoami
ssm-user
sh-4.2$ exit
exit


Exiting session with sessionId: admin-hkkxvenmjmrvis6odrqsyy4kvm.
```
## ログ出力設定
### 変数設定
```bash:コマンド
# ロググループ名
LOG_GROUP_NAME="h4b-log" \
&& echo ${LOG_GROUP_NAME}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # ロググループ名
[cloudshell-user@ip-10-134-0-112 ~]$ LOG_GROUP_NAME="h4b-log" \
> && echo ${LOG_GROUP_NAME}
h4b-log
```
### ロググループ作成
```bash:コマンド
aws logs create-log-group \
    --log-group-name ${LOG_GROUP_NAME}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws logs create-log-group \
>     --log-group-name ${LOG_GROUP_NAME}
```
## セッションマネージャー設定
```bash:コマンド
DOCUMENT_NAME="SSM-SessionManagerRunShell" \
&& echo ${DOCUMENT_NAME}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ DOCUMENT_NAME="SSM-SessionManagerRunShell" \
> && echo ${DOCUMENT_NAME}
SSM-SessionManagerRunShell
```
### 変数設定
```bash:コマンド
DOCUMENT_NAME="SSM-SessionManagerRunShell" \
&& echo ${DOCUMENT_NAME}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ DOCUMENT_NAME="SSM-SessionManagerRunShell" \
> && echo ${DOCUMENT_NAME}
SSM-SessionManagerRunShell
```
### ドキュメント用JSON
```bash:コマンド
# JSONの作成
DOCUMENT_JSON=$(cat << EOF
{
    "schemaVersion": "1.0",
    "description": "Document to hold regional settings for Session Manager",
    "sessionType": "Standard_Stream",
    "inputs": {
        "s3BucketName": "",
        "s3KeyPrefix": "",
        "s3EncryptionEnabled": true,
        "cloudWatchLogGroupName": "${LOG_GROUP_NAME}",
        "cloudWatchEncryptionEnabled": false,
        "cloudWatchStreamingEnabled": true,
        "idleSessionTimeout": "20",
        "maxSessionDuration": "",
        "kmsKeyId": "",
        "runAsEnabled": false,
        "runAsDefaultUser": "",
        "shellProfile": {
            "windows": "",
            "linux": ""
        }
    }
}
EOF
) \
&& echo ${DOCUMENT_JSON}

# JSONフォーマットの確認
echo ${DOCUMENT_JSON} | python -m json.tool
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # JSONの作成
[cloudshell-user@ip-10-134-0-112 ~]$ DOCUMENT_JSON=$(cat << EOF
> {
>     "schemaVersion": "1.0",
>     "description": "Document to hold regional settings for Session Manager",
>     "sessionType": "Standard_Stream",
>     "inputs": {
>         "s3BucketName": "",
>         "s3KeyPrefix": "",
>         "s3EncryptionEnabled": true,
>         "cloudWatchLogGroupName": "${LOG_GROUP_NAME}",
>         "cloudWatchEncryptionEnabled": false,
>         "cloudWatchStreamingEnabled": true,
>         "idleSessionTimeout": "20",
>         "maxSessionDuration": "",
>         "kmsKeyId": "",
>         "runAsEnabled": false,
>         "runAsDefaultUser": "",
>         "shellProfile": {
>             "windows": "",
>             "linux": ""
>         }
>     }
> }
> EOF
> ) \
> && echo ${DOCUMENT_JSON}
{ "schemaVersion": "1.0", "description": "Document to hold regional settings for Session Manager", "sessionType": "Standard_Stream", "inputs": { "s3BucketName": "", "s3KeyPrefix": "", "s3EncryptionEnabled": true, "cloudWatchLogGroupName": "h4b-log", "cloudWatchEncryptionEnabled": false, "cloudWatchStreamingEnabled": true, "idleSessionTimeout": "20", "maxSessionDuration": "", "kmsKeyId": "", "runAsEnabled": false, "runAsDefaultUser": "", "shellProfile": { "windows": "", "linux": "" } } }
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-134-0-112 ~]$ echo ${DOCUMENT_JSON} | python -m json.tool
{
    "schemaVersion": "1.0",
    "description": "Document to hold regional settings for Session Manager",
    "sessionType": "Standard_Stream",
    "inputs": {
        "s3BucketName": "",
        "s3KeyPrefix": "",
        "s3EncryptionEnabled": true,
        "cloudWatchLogGroupName": "h4b-log",
        "cloudWatchEncryptionEnabled": false,
        "cloudWatchStreamingEnabled": true,
        "idleSessionTimeout": "20",
        "maxSessionDuration": "",
        "kmsKeyId": "",
        "runAsEnabled": false,
        "runAsDefaultUser": "",
        "shellProfile": {
            "windows": "",
            "linux": ""
        }
    }
}
```
### ドキュメント作成
```bash:コマンド
aws ssm create-document \
    --name ${DOCUMENT_NAME} \
    --content "${DOCUMENT_JSON}" \
    --document-type "Session" \
    --document-format JSON
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm create-document \
>     --name ${DOCUMENT_NAME} \
>     --content "${DOCUMENT_JSON}" \
>     --document-type "Session" \
>     --document-format JSON
{
    "DocumentDescription": {
        "Hash": "db5f811e949a9c080f343839eb27fe1c150750fc4457acf0b9d3b6680540a346",
        "HashType": "Sha256",
        "Name": "SSM-SessionManagerRunShell",
        "Owner": "999999999999",
        "CreatedDate": "2024-08-04T05:39:44.731000+00:00",
        "Status": "Creating",
        "DocumentVersion": "1",
        "PlatformTypes": [
            "Windows",
            "Linux",
            "MacOS"
        ],
        "DocumentType": "Session",
        "SchemaVersion": "1.0",
        "LatestVersion": "1",
        "DefaultVersion": "1",
        "DocumentFormat": "JSON",
        "Tags": []
    }
}
```
### IAMロール権限追加
```bash:コマンド
# 変数
# IAMロール名
IAM_ROLE_NAME="h4b-role" \
&& echo ${IAM_ROLE_NAME}

IAM_ATTACH_POLICY_NAME="CloudWatchLogsFullAccess" \
&& echo ${IAM_ATTACH_POLICY_NAME}

IAM_POLICY_ARN="arn:aws:iam::aws:policy/${IAM_ATTACH_POLICY_NAME}" \
&& echo ${IAM_POLICY_ARN}

# IAMロールにポリシーをアタッチ
aws iam attach-role-policy \
    --role-name ${IAM_ROLE_NAME} \
    --policy-arn ${IAM_POLICY_ARN}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # 変数
[cloudshell-user@ip-10-134-0-112 ~]$ # IAMロール名
[cloudshell-user@ip-10-134-0-112 ~]$ IAM_ROLE_NAME="h4b-role" \
> && echo ${IAM_ROLE_NAME}
h4b-role
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ IAM_ATTACH_POLICY_NAME="CloudWatchLogsFullAccess" \
> && echo ${IAM_ATTACH_POLICY_NAME}
CloudWatchLogsFullAccess
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ IAM_POLICY_ARN="arn:aws:iam::aws:policy/${IAM_ATTACH_POLICY_NAME}" \
> && echo ${IAM_POLICY_ARN}
arn:aws:iam::aws:policy/CloudWatchLogsFullAccess
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # IAMロールにポリシーをアタッチ
[cloudshell-user@ip-10-134-0-112 ~]$ aws iam attach-role-policy \
>     --role-name ${IAM_ROLE_NAME} \
>     --policy-arn ${IAM_POLICY_ARN}
```
### セッションマネージャーを使ったサーバログイン
```bash:コマンド
aws ssm start-session \
    --target ${EC2_INSTANCE_ID} 
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm start-session \
>     --target ${EC2_INSTANCE_ID} 

Starting session with SessionId: admin-aa5ztfvbanlj7pqmyc444zfgmm
sh-4.2$ pwd
/usr/bin
sh-4.2$ whoami
ssm-user
sh-4.2$ exit
exit


Exiting session with sessionId: admin-aa5ztfvbanlj7pqmyc444zfgmm.
```
### 最新のログストリームを取得
```bash:コマンド
LATEST_LOG_STREAM=$(
    aws logs describe-log-streams \
        --log-group-name ${LOG_GROUP_NAME} \
        --order-by LastEventTime \
        --descending \
        --limit 1 \
        --query 'logStreams[0].logStreamName' \
        --output text
) \
&& echo ${LATEST_LOG_STREAM}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ LATEST_LOG_STREAM=$(
>     aws logs describe-log-streams \
>         --log-group-name ${LOG_GROUP_NAME} \
>         --order-by LastEventTime \
>         --descending \
>         --limit 1 \
>         --query 'logStreams[0].logStreamName' \
>         --output text
> ) \
> && echo ${LATEST_LOG_STREAM}
admin-aa5ztfvbanlj7pqmyc444zfgmm
```
### ログの確認
```bash:コマンド
aws logs get-log-events \
    --log-group-name ${LOG_GROUP_NAME} \
    --log-stream-name ${LATEST_LOG_STREAM} \
    --output table
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws logs get-log-events \
>     --log-group-name ${LOG_GROUP_NAME} \
>     --log-stream-name ${LATEST_LOG_STREAM} \
>     --output table
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|                                                                                                                                                                      GetLogEvents                                                                                                                                                                       |
+------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|  nextBackwardToken                                                                 |  b/38418618679008255028435759595580551324241133851684700160/s                                                                                                                                                                                                      |
|  nextForwardToken                                                                  |  f/38418618812812726219619498451963804467526762705000988672/s                                                                                                                                                                                                      |
+------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
||                                                                                                                                                                        events                                                                                                                                                                         ||
|+---------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+|
|| ingestionTime |                                                                                                                                                       message                                                                                                                                                        |   timestamp    ||
|+---------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+|
||  1722750443477|  {"eventVersion":"1.0","eventTime":"2024-08-04T05:47:23Z","awsRegion":"ap-northeast-1","target":{"id":"i-05a444e226ac72648"},"userIdentity":{"arn":"arn:aws:iam::999999999999:user/admin"},"runAsUser":"ssm-user","sessionId":"admin-aa5ztfvbanlj7pqmyc444zfgmm","sessionData":["sh-4.2$ sh-4.2$ pwd","/usr/bin"]}   |  1722750443404 ||
||  1722750445407|  {"eventVersion":"1.0","eventTime":"2024-08-04T05:47:25Z","awsRegion":"ap-northeast-1","target":{"id":"i-05a444e226ac72648"},"userIdentity":{"arn":"arn:aws:iam::999999999999:user/admin"},"runAsUser":"ssm-user","sessionId":"admin-aa5ztfvbanlj7pqmyc444zfgmm","sessionData":["sh-4.2$ whoami","ssm-user"]}        |  1722750445404 ||
||  1722750449407|  {"eventVersion":"1.0","eventTime":"2024-08-04T05:47:29Z","awsRegion":"ap-northeast-1","target":{"id":"i-05a444e226ac72648"},"userIdentity":{"arn":"arn:aws:iam::999999999999:user/admin"},"runAsUser":"ssm-user","sessionId":"admin-aa5ztfvbanlj7pqmyc444zfgmm","sessionData":["sh-4.2$ exit","exit"]}              |  1722750449404 ||
|+---------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+|
```
# 06 Run Commandを使ったコマンド実行
## コマンド実行
```bash:コマンド
COMMAND_ID=$(
    aws ssm send-command \
        --document-name "AWS-RunShellScript" \
        --targets "Key=instanceids,Values=${EC2_INSTANCE_ID} " \
        --parameters 'commands=["pwd","whoami"]' \
        --query Command.CommandId \
        --output text
) \
&& echo ${COMMAND_ID}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ COMMAND_ID=$(
>     aws ssm send-command \
>         --document-name "AWS-RunShellScript" \
>         --targets "Key=instanceids,Values=${EC2_INSTANCE_ID} " \
>         --parameters 'commands=["pwd","whoami"]' \
>         --query Command.CommandId \
>         --output text
> ) \
> && echo ${COMMAND_ID}
5d3954b3-61b0-4f3b-8637-16161067e146
```
## 実行結果確認
```bash:コマンド
aws ssm get-command-invocation \
    --command-id ${COMMAND_ID} \
    --instance-id ${EC2_INSTANCE_ID}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm get-command-invocation \
>     --command-id ${COMMAND_ID} \
>     --instance-id ${EC2_INSTANCE_ID}
{
    "CommandId": "5d3954b3-61b0-4f3b-8637-16161067e146",
    "InstanceId": "i-05a444e226ac72648",
    "Comment": "",
    "DocumentName": "AWS-RunShellScript",
    "DocumentVersion": "$DEFAULT",
    "PluginName": "aws:runShellScript",
    "ResponseCode": 0,
    "ExecutionStartDateTime": "2024-08-04T06:21:33.182Z",
    "ExecutionElapsedTime": "PT0.008S",
    "ExecutionEndDateTime": "2024-08-04T06:21:33.182Z",
    "Status": "Success",
    "StatusDetails": "Success",
    "StandardOutputContent": "/usr/bin\nroot\n",
    "StandardOutputUrl": "",
    "StandardErrorContent": "",
    "StandardErrorUrl": "",
    "CloudWatchOutputConfig": {
        "CloudWatchLogGroupName": "",
        "CloudWatchOutputEnabled": false
    }
}
```
# 07 リソースの削除、本ハンズオンのまとめ
## State Managerの関連付けを削除
```bash:コマンド
# 関連付けの名前
ASSOCIATIONNAME="Inventory-Association" \
&& echo ${ASSOCIATIONNAME}

# アソシエーションID取得
INVENTORY_ASSOCIATION_ID=$(
    aws ssm list-associations \
        --query "Associations[?AssociationName=='${ASSOCIATIONNAME}'].AssociationId" \
        --output text
) \
&& echo ${INVENTORY_ASSOCIATION_ID}

# インベントリの削除
aws ssm delete-association \
    --association-id ${INVENTORY_ASSOCIATION_ID}

# 関連付けの名前
ASSOCIATIONNAME="SystemAssociationForSsmAgentUpdate" \
&& echo ${ASSOCIATIONNAME}

# アソシエーションID取得
INVENTORY_ASSOCIATION_ID=$(
    aws ssm list-associations \
        --query "Associations[?AssociationName=='${ASSOCIATIONNAME}'].AssociationId" \
        --output text
) \
&& echo ${INVENTORY_ASSOCIATION_ID}

# インベントリの削除
aws ssm delete-association \
    --association-id ${INVENTORY_ASSOCIATION_ID}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # 関連付けの名前
[cloudshell-user@ip-10-134-0-112 ~]$ ASSOCIATIONNAME="Inventory-Association" \
> && echo ${ASSOCIATIONNAME}
Inventory-Association
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # アソシエーションID取得
[cloudshell-user@ip-10-134-0-112 ~]$ INVENTORY_ASSOCIATION_ID=$(
>     aws ssm list-associations \
>         --query "Associations[?AssociationName=='${ASSOCIATIONNAME}'].AssociationId" \
>         --output text
> ) \
> && echo ${INVENTORY_ASSOCIATION_ID}
d273a574-d672-494d-9e61-d10eb5c8d2c7
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # インベントリの削除
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm delete-association \
>     --association-id ${INVENTORY_ASSOCIATION_ID}
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # 関連付けの名前
[cloudshell-user@ip-10-134-0-112 ~]$ ASSOCIATIONNAME="SystemAssociationForSsmAgentUpdate" \
> && echo ${ASSOCIATIONNAME}
SystemAssociationForSsmAgentUpdate
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # アソシエーションID取得
[cloudshell-user@ip-10-134-0-112 ~]$ INVENTORY_ASSOCIATION_ID=$(
>     aws ssm list-associations \
>         --query "Associations[?AssociationName=='${ASSOCIATIONNAME}'].AssociationId" \
>         --output text
> ) \
> && echo ${INVENTORY_ASSOCIATION_ID}
56f1b789-41b9-485f-8ecc-e03eb3078bcf
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # インベントリの削除
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm delete-association \
>     --association-id ${INVENTORY_ASSOCIATION_ID}
```
## セッションマネージャーのログ出力設定削除
### ドキュメントJSON更新
```bash:コマンド
# JSONの作成
DOCUMENT_JSON=$(cat << EOF
{
    "schemaVersion": "1.0",
    "description": "Document to hold regional settings for Session Manager",
    "sessionType": "Standard_Stream",
    "inputs": {
        "s3BucketName": "",
        "s3KeyPrefix": "",
        "s3EncryptionEnabled": true,
        "cloudWatchLogGroupName": "",
        "cloudWatchEncryptionEnabled": true,
        "cloudWatchStreamingEnabled": true,
        "idleSessionTimeout": "20",
        "maxSessionDuration": "",
        "kmsKeyId": "",
        "runAsEnabled": false,
        "runAsDefaultUser": "",
        "shellProfile": {
            "windows": "",
            "linux": ""
        }
    }
}
EOF
) \
&& echo ${DOCUMENT_JSON}

# JSONフォーマットの確認
echo ${DOCUMENT_JSON} | python -m json.tool
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # JSONの作成
[cloudshell-user@ip-10-134-0-112 ~]$ DOCUMENT_JSON=$(cat << EOF
> {
>     "schemaVersion": "1.0",
>     "description": "Document to hold regional settings for Session Manager",
>     "sessionType": "Standard_Stream",
>     "inputs": {
>         "s3BucketName": "",
>         "s3KeyPrefix": "",
>         "s3EncryptionEnabled": true,
>         "cloudWatchLogGroupName": "",
>         "cloudWatchEncryptionEnabled": true,
>         "cloudWatchStreamingEnabled": true,
>         "idleSessionTimeout": "20",
>         "maxSessionDuration": "",
>         "kmsKeyId": "",
>         "runAsEnabled": false,
>         "runAsDefaultUser": "",
>         "shellProfile": {
>             "windows": "",
>             "linux": ""
>         }
>     }
> }
> EOF
> ) \
> && echo ${DOCUMENT_JSON}
{ "schemaVersion": "1.0", "description": "Document to hold regional settings for Session Manager", "sessionType": "Standard_Stream", "inputs": { "s3BucketName": "", "s3KeyPrefix": "", "s3EncryptionEnabled": true, "cloudWatchLogGroupName": "", "cloudWatchEncryptionEnabled": true, "cloudWatchStreamingEnabled": true, "idleSessionTimeout": "20", "maxSessionDuration": "", "kmsKeyId": "", "runAsEnabled": false, "runAsDefaultUser": "", "shellProfile": { "windows": "", "linux": "" } } }
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-134-0-112 ~]$ echo ${DOCUMENT_JSON} | python -m json.tool
{
    "schemaVersion": "1.0",
    "description": "Document to hold regional settings for Session Manager",
    "sessionType": "Standard_Stream",
    "inputs": {
        "s3BucketName": "",
        "s3KeyPrefix": "",
        "s3EncryptionEnabled": true,
        "cloudWatchLogGroupName": "",
        "cloudWatchEncryptionEnabled": true,
        "cloudWatchStreamingEnabled": true,
        "idleSessionTimeout": "20",
        "maxSessionDuration": "",
        "kmsKeyId": "",
        "runAsEnabled": false,
        "runAsDefaultUser": "",
        "shellProfile": {
            "windows": "",
            "linux": ""
        }
    }
}
```
### 設定更新
```bash:コマンド
aws ssm update-document \
    --name ${DOCUMENT_NAME} \
    --content "${DOCUMENT_JSON}" \
    --document-version "\$LATEST"
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm update-document \
>     --name ${DOCUMENT_NAME} \
>     --content "${DOCUMENT_JSON}" \
>     --document-version "\$LATEST"
{
    "DocumentDescription": {
        "Hash": "58582884cc09968a45e71acda4efdb93c67657773e582c59fda02acf83c7baec",
        "HashType": "Sha256",
        "Name": "SSM-SessionManagerRunShell",
        "Owner": "999999999999",
        "CreatedDate": "2024-08-04T06:41:27.560000+00:00",
        "Status": "Updating",
        "DocumentVersion": "2",
        "PlatformTypes": [
            "Windows",
            "Linux",
            "MacOS"
        ],
        "DocumentType": "Session",
        "SchemaVersion": "1.0",
        "LatestVersion": "2",
        "DefaultVersion": "1",
        "DocumentFormat": "JSON",
        "Tags": []
    }
}
```
:::note warn
ドキュメント自体を削除する場合、下記でも可
:::
```bash:コマンド
aws ssm delete-document \
    --name ${DOCUMENT_NAME}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws ssm delete-document \
>     --name ${DOCUMENT_NAME}
```
## EC2インスタンスの削除
```bash:コマンド
aws ec2 terminate-instances \
    --instance-ids ${EC2_INSTANCE_ID}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws ec2 terminate-instances \
>     --instance-ids ${EC2_INSTANCE_ID}
{
    "TerminatingInstances": [
        {
            "CurrentState": {
                "Code": 32,
                "Name": "shutting-down"
            },
            "InstanceId": "i-05a444e226ac72648",
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}
```
## CloudWatch Logsグループの削除
```bash:コマンド
aws logs delete-log-group \
    --log-group-name ${LOG_GROUP_NAME}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws logs delete-log-group \
>     --log-group-name ${LOG_GROUP_NAME}
```
## インスタンスプロファイル削除
```bash:コマンド
# IAMプロファイルのデタッチ
aws iam remove-role-from-instance-profile \
    --instance-profile-name ${IAM_INSTANCE_PROFILE_NAME}\
    --role-name ${IAM_ROLE_NAME}

# インスタンスプロファイル削除
aws iam delete-instance-profile \
    --instance-profile-name ${IAM_INSTANCE_PROFILE_NAME}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # IAMプロファイルのデタッチ
[cloudshell-user@ip-10-134-0-112 ~]$ aws iam remove-role-from-instance-profile \
>     --instance-profile-name ${IAM_INSTANCE_PROFILE_NAME}\
>     --role-name ${IAM_ROLE_NAME}
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # インスタンスプロファイル削除
[cloudshell-user@ip-10-134-0-112 ~]$ aws iam delete-instance-profile \
>     --instance-profile-name ${IAM_INSTANCE_PROFILE_NAME}
```
## IAMロールの削除
### ロールにアタッチされているポリシーのデタッチ
```bash:コマンド
# ロールにアタッチされているポリシーをリスト
IAM_POLICIES_LIST=$(
    aws iam list-attached-role-policies \
        --role-name ${IAM_ROLE_NAME} \
        --query 'AttachedPolicies[*].PolicyArn' \
        --output text
) \
&& echo ${IAM_POLICIES_LIST}

# リスト内のポリシーをデタッチする
for POLICY in ${IAM_POLICIES_LIST}; do
    aws iam detach-role-policy \
        --role-name ${IAM_ROLE_NAME} \
        --policy-arn ${POLICY}
done
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # ロールにアタッチされているポリシーをリスト
[cloudshell-user@ip-10-134-0-112 ~]$ IAM_POLICIES_LIST=$(
>     aws iam list-attached-role-policies \
>         --role-name ${IAM_ROLE_NAME} \
>         --query 'AttachedPolicies[*].PolicyArn' \
>         --output text
> ) \
> && echo ${IAM_POLICIES_LIST}
arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore arn:aws:iam::aws:policy/CloudWatchLogsFullAccess
[cloudshell-user@ip-10-134-0-112 ~]$ 
[cloudshell-user@ip-10-134-0-112 ~]$ # リスト内のポリシーをデタッチする
[cloudshell-user@ip-10-134-0-112 ~]$ for POLICY in ${IAM_POLICIES_LIST}; do
>     aws iam detach-role-policy \
>         --role-name ${IAM_ROLE_NAME} \
>         --policy-arn ${POLICY}
> done
```
### IAMロールの削除
```bash:コマンド
# IAMロールの削除
aws iam delete-role \
    --role-name ${IAM_ROLE_NAME}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ # IAMロールの削除
[cloudshell-user@ip-10-134-0-112 ~]$ aws iam delete-role \
>     --role-name ${IAM_ROLE_NAME}
```
## CloudFormationスタックの削除
```bash:コマンド
aws cloudformation delete-stack \
  --stack-name ${STACK_NAME}
```
```bash:出力
[cloudshell-user@ip-10-134-0-112 ~]$ aws cloudformation delete-stack \
>   --stack-name ${STACK_NAME}
```