0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「AWS Hands-on for Beginners 監視編 サーバーのモニタリングの基本を学ぼう 」をAWS CLIでやってみる

Last updated at Posted at 2024-06-23

上記、「AWS Hands-on for Beginners 監視編 サーバーのモニタリングの基本を学ぼう」 をAWS CLIでやってみる

image.png
ハンズオンから引用

1.CloudFormationでリソースの作成

テンプレートファイルはハンズオンページからダウンロードしたものを使用。

インスタンス作成時にエラーになるため、テンプレートファイル内のRDSのインスタンスはdb.t2.microからdb.t3.microに変更

変数設定

コマンド
# スタック名
STACK_NAME="monitoring-1"
echo ${STACK_NAME}

# テンプレートファイル名
TEMPLATE_BODY="monitoring-1.yaml"
echo ${TEMPLATE_BODY}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ # スタック名
[cloudshell-user@ip-10-132-88-36 ~]$ STACK_NAME="monitoring-1"
[cloudshell-user@ip-10-132-88-36 ~]$ echo ${STACK_NAME}
monitoring-1
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ # テンプレートファイル名
[cloudshell-user@ip-10-132-88-36 ~]$ TEMPLATE_BODY="monitoring-1.yaml"
[cloudshell-user@ip-10-132-88-36 ~]$ echo ${TEMPLATE_BODY}
monitoring-1.yaml

スタック作成

コマンド
aws cloudformation create-stack \
    --stack-name ${STACK_NAME} \
    --template-body file://${TEMPLATE_BODY} \
    --capabilities CAPABILITY_NAMED_IAM
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws cloudformation create-stack \
>     --stack-name ${STACK_NAME} \
>     --template-body file://${TEMPLATE_BODY} \
>     --capabilities CAPABILITY_NAMED_IAM
{
    "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d"
}

スタックの出力確認

コマンド
aws cloudformation describe-stacks --stack-name ${STACK_NAME}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws cloudformation describe-stacks --stack-name ${STACK_NAME}
{
    "Stacks": [
        {
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "StackName": "monitoring-1",
            "Description": "AWS Hands-on for Beginners monitoing-1 template",
            "Parameters": [
                {
                    "ParameterKey": "RDSInstanceType",
                    "ParameterValue": "db.t3.micro"
                },
                {
                    "ParameterKey": "EC2InstanceType",
                    "ParameterValue": "t2.micro"
                },
                {
                    "ParameterKey": "DBUser",
                    "ParameterValue": "dbmaster"
                },
                {
                    "ParameterKey": "DBPassword",
                    "ParameterValue": "****"
                },
                {
                    "ParameterKey": "EC2AMI",
                    "ParameterValue": "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
                    "ResolvedValue": "ami-029dc392355a76964"
                }
            ],
            "CreationTime": "2024-06-22T23:21:52.045000+00:00",
            "RollbackConfiguration": {},
            "StackStatus": "CREATE_COMPLETE",
            "DisableRollback": false,
            "NotificationARNs": [],
            "Capabilities": [
                "CAPABILITY_NAMED_IAM"
            ],
            "Outputs": [
                {
                    "OutputKey": "PrivateSubnet1",
                    "OutputValue": "subnet-04b281a734ba8c075",
                    "Description": "PrivateSubnet 1"
                },
                {
                    "OutputKey": "PrivateSubnet2",
                    "OutputValue": "subnet-06f261f48f7beae0f",
                    "Description": "PrivateSubnet 2"
                },
                {
                    "OutputKey": "EC2WebServer02",
                    "OutputValue": "i-02cee7d18cb05c8e9"
                },
                {
                    "OutputKey": "EC2WebServer01",
                    "OutputValue": "i-0b8d540d2dc6e0497"
                },
                {
                    "OutputKey": "EC2WebServer02DNS",
                    "OutputValue": "ec2-54-238-239-91.ap-northeast-1.compute.amazonaws.com"
                },
                {
                    "OutputKey": "VPCID",
                    "OutputValue": "vpc-09fe2194c2d22f586",
                    "Description": "VPC ID"
                },
                {
                    "OutputKey": "EC2WebServer01DNS",
                    "OutputValue": "ec2-52-192-9-168.ap-northeast-1.compute.amazonaws.com"
                },
                {
                    "OutputKey": "FrontLBEndpoint",
                    "OutputValue": "monitoring-1-elb-182076190.ap-northeast-1.elb.amazonaws.com"
                },
                {
                    "OutputKey": "PublicSubnet2",
                    "OutputValue": "subnet-065d757166972e0c9",
                    "Description": "PublicSubnet 2"
                },
                {
                    "OutputKey": "RDSEndpointAddress",
                    "OutputValue": "monitoring-1-rds.clacqicsiqrt.ap-northeast-1.rds.amazonaws.com"
                },
                {
                    "OutputKey": "PublicSubnet1",
                    "OutputValue": "subnet-08cda4950b87852d6",
                    "Description": "PublicSubnet 1"
                }
            ],
            "Tags": [],
            "EnableTerminationProtection": false,
            "DriftInformation": {
                "StackDriftStatus": "NOT_CHECKED"
            }
        }
    ]
}

リソース物理IDの確認

コマンド
aws cloudformation describe-stack-resources --stack-name ${STACK_NAME}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws cloudformation describe-stack-resources --stack-name ${STACK_NAME}
{
    "StackResources": [
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "CFnVPC",
            "PhysicalResourceId": "vpc-09fe2194c2d22f586",
            "ResourceType": "AWS::EC2::VPC",
            "Timestamp": "2024-06-22T23:22:07.508000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "CFnVPCIGW",
            "PhysicalResourceId": "igw-05d3adcc9cd9d9759",
            "ResourceType": "AWS::EC2::InternetGateway",
            "Timestamp": "2024-06-22T23:22:11.878000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "CFnVPCIGWAttach",
            "PhysicalResourceId": "IGW|vpc-09fe2194c2d22f586",
            "ResourceType": "AWS::EC2::VPCGatewayAttachment",
            "Timestamp": "2024-06-22T23:22:10.755000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "DBInstance",
            "PhysicalResourceId": "monitoring-1-rds",
            "ResourceType": "AWS::RDS::DBInstance",
            "Timestamp": "2024-06-22T23:34:59.512000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "DBSubnetGroup",
            "PhysicalResourceId": "monitoring-1-dbsubnetgroup-f2xnw5qizmae",
            "ResourceType": "AWS::RDS::DBSubnetGroup",
            "Timestamp": "2024-06-22T23:22:13.573000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "EC2WebServer01",
            "PhysicalResourceId": "i-0b8d540d2dc6e0497",
            "ResourceType": "AWS::EC2::Instance",
            "Timestamp": "2024-06-22T23:25:00.719000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "EC2WebServer02",
            "PhysicalResourceId": "i-02cee7d18cb05c8e9",
            "ResourceType": "AWS::EC2::Instance",
            "Timestamp": "2024-06-22T23:24:50.409000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "FrontLB",
            "PhysicalResourceId": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/monitoring-1-elb/c147aef4db266283",
            "ResourceType": "AWS::ElasticLoadBalancingV2::LoadBalancer",
            "Timestamp": "2024-06-22T23:24:49.195000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "FrontLBListener",
            "PhysicalResourceId": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:listener/app/monitoring-1-elb/c147aef4db266283/f8e0379a181bee32",
            "ResourceType": "AWS::ElasticLoadBalancingV2::Listener",
            "Timestamp": "2024-06-22T23:25:10.177000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "FrontLBTargetGroup",
            "PhysicalResourceId": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/monitoring-1-tg/0726cfe1b71c5746",
            "ResourceType": "AWS::ElasticLoadBalancingV2::TargetGroup",
            "Timestamp": "2024-06-22T23:25:08.271000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "IAMInstanceProfile",
            "PhysicalResourceId": "monitoring-1-IAMInstanceProfile-gTiXgLxPzjHq",
            "ResourceType": "AWS::IAM::InstanceProfile",
            "Timestamp": "2024-06-22T23:24:26.474000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "Monitoring1EC2RoleforSSM",
            "PhysicalResourceId": "Monitoring1EC2RoleforSSM",
            "ResourceType": "AWS::IAM::Role",
            "Timestamp": "2024-06-22T23:22:14.238000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "PrivateSubnet1",
            "PhysicalResourceId": "subnet-04b281a734ba8c075",
            "ResourceType": "AWS::EC2::Subnet",
            "Timestamp": "2024-06-22T23:22:12.421000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "PrivateSubnet2",
            "PhysicalResourceId": "subnet-06f261f48f7beae0f",
            "ResourceType": "AWS::EC2::Subnet",
            "Timestamp": "2024-06-22T23:22:12.823000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "PublicRoute",
            "PhysicalResourceId": "rtb-005ca0ece222251e1|0.0.0.0/0",
            "ResourceType": "AWS::EC2::Route",
            "Timestamp": "2024-06-22T23:22:21.821000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "PublicRouteTable",
            "PhysicalResourceId": "rtb-005ca0ece222251e1",
            "ResourceType": "AWS::EC2::RouteTable",
            "Timestamp": "2024-06-22T23:22:19.653000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "PublicSubnet1",
            "PhysicalResourceId": "subnet-08cda4950b87852d6",
            "ResourceType": "AWS::EC2::Subnet",
            "Timestamp": "2024-06-22T23:22:12.842000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "PublicSubnet1Assoc",
            "PhysicalResourceId": "rtbassoc-0945997393dccb837",
            "ResourceType": "AWS::EC2::SubnetRouteTableAssociation",
            "Timestamp": "2024-06-22T23:22:15.092000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "PublicSubnet2",
            "PhysicalResourceId": "subnet-065d757166972e0c9",
            "ResourceType": "AWS::EC2::Subnet",
            "Timestamp": "2024-06-22T23:22:12.850000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "PublicSubnet2Assoc",
            "PhysicalResourceId": "rtbassoc-08ca3a7c0f8be03aa",
            "ResourceType": "AWS::EC2::SubnetRouteTableAssociation",
            "Timestamp": "2024-06-22T23:22:14.832000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "SecurityGroupDB",
            "PhysicalResourceId": "sg-0b56c8512f3c29157",
            "ResourceType": "AWS::EC2::SecurityGroup",
            "Timestamp": "2024-06-22T23:22:11.752000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "SecurityGroupLB",
            "PhysicalResourceId": "sg-0c7c991af0197422f",
            "ResourceType": "AWS::EC2::SecurityGroup",
            "Timestamp": "2024-06-22T23:22:11.626000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        },
        {
            "StackName": "monitoring-1",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:999999999999:stack/monitoring-1/34db9450-30ee-11ef-92cd-0a227c45dc8d",
            "LogicalResourceId": "SecurityGroupWebServer",
            "PhysicalResourceId": "sg-0f97e53a072e77388",
            "ResourceType": "AWS::EC2::SecurityGroup",
            "Timestamp": "2024-06-22T23:22:12.372000+00:00",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "NOT_CHECKED"
            }
        }
    ]
}

2. WordPressの初期設定

WebUIからの設定のため省略

3. CloudWatchメトリクスの確認

インスタンスIDの取得

コマンド
# Ec2インスタンス1
OUTPUTKEY='EC2WebServer01'
echo ${OUTPUTKEY}

EC2_INSTANCE_ID_1=$(
    aws cloudformation describe-stacks \
        --stack-name ${STACK_NAME} \
        --query "Stacks[*].Outputs[?OutputKey=='${OUTPUTKEY}'].OutputValue" \
        --output text
) \
&& echo ${EC2_INSTANCE_ID_1}

# Ec2インスタンス2
OUTPUTKEY='EC2WebServer02'
echo ${OUTPUTKEY}

EC2_INSTANCE_ID_2=$(
    aws cloudformation describe-stacks \
        --stack-name ${STACK_NAME} \
        --query "Stacks[*].Outputs[?OutputKey=='${OUTPUTKEY}'].OutputValue" \
        --output text
) \
&& echo ${EC2_INSTANCE_ID_2}

# EC2 AMI
PARAMETERKEY='EC2AMI'
echo ${PARAMETERKEY}

EC2_AMI=$(
    aws cloudformation describe-stacks \
        --stack-name ${STACK_NAME} \
        --query "Stacks[*].Parameters[?ParameterKey=='${PARAMETERKEY}'].ResolvedValue" \
        --output text
) \
&& echo ${EC2_AMI}

# ALB ARN
LOGICALRESOURCEID='FrontLB'
echo ${LOGICALRESOURCEID}

ALB_ARN=$(
    aws cloudformation describe-stack-resources \
        --stack-name ${STACK_NAME} \
        --query "StackResources[?LogicalResourceId=='${LOGICALRESOURCEID}'].PhysicalResourceId" \
        --output text
) \
&& echo ${ALB_ARN}

last_part=$(echo "${ALB_ARN}" | awk -F':' '{print $NF}') \
&& DIMENSIONS_ALB=$(echo ${last_part} | rev | cut -d'/' -f1-3 | rev) \
&& echo ${DIMENSIONS_ALB}

# TARGETGROUP ARN
LOGICALRESOURCEID='FrontLBTargetGroup'
echo ${LOGICALRESOURCEID}

TARGET_GROUP_ARN=$(
    aws cloudformation describe-stack-resources \
        --stack-name ${STACK_NAME} \
        --query "StackResources[?LogicalResourceId=='${LOGICALRESOURCEID}'].PhysicalResourceId" \
        --output text
) \
&& echo ${TARGET_GROUP_ARN}

last_part=$(echo "${TARGET_GROUP_ARN}" | awk -F':' '{print $NF}') \
&& DIMENSIONS_TG=$(echo ${last_part} | rev | cut -d'/' -f1-3 | rev) \
&& echo ${DIMENSIONS_TG}

# RDS
RDS_INSTANCE_ID=$(
    aws cloudformation describe-stack-resources \
        --stack-name ${STACK_NAME} \
        --query "StackResources[?LogicalResourceId=='DBInstance'].PhysicalResourceId" \
        --output text
) \
&& echo ${RDS_INSTANCE_ID}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ # Ec2インスタンス1
[cloudshell-user@ip-10-132-88-36 ~]$ OUTPUTKEY='EC2WebServer01'
[cloudshell-user@ip-10-132-88-36 ~]$ echo ${OUTPUTKEY}
EC2WebServer01
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ EC2_INSTANCE_ID_1=$(
>     aws cloudformation describe-stacks \
>         --stack-name ${STACK_NAME} \
>         --query "Stacks[*].Outputs[?OutputKey=='${OUTPUTKEY}'].OutputValue" \
>         --output text
> ) \
> && echo ${EC2_INSTANCE_ID_1}
i-0b8d540d2dc6e0497
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ # Ec2インスタンス2
[cloudshell-user@ip-10-132-88-36 ~]$ OUTPUTKEY='EC2WebServer02'
[cloudshell-user@ip-10-132-88-36 ~]$ echo ${OUTPUTKEY}
EC2WebServer02
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ EC2_INSTANCE_ID_2=$(
>     aws cloudformation describe-stacks \
>         --stack-name ${STACK_NAME} \
>         --query "Stacks[*].Outputs[?OutputKey=='${OUTPUTKEY}'].OutputValue" \
>         --output text
> ) \
> && echo ${EC2_INSTANCE_ID_2}
i-02cee7d18cb05c8e9
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ # EC2 AMI
[cloudshell-user@ip-10-132-88-36 ~]$ PARAMETERKEY='EC2AMI'
[cloudshell-user@ip-10-132-88-36 ~]$ echo ${PARAMETERKEY}
EC2AMI
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ EC2_AMI=$(
>     aws cloudformation describe-stacks \
>         --stack-name ${STACK_NAME} \
>         --query "Stacks[*].Parameters[?ParameterKey=='${PARAMETERKEY}'].ResolvedValue" \
>         --output text
> ) \
> && echo ${EC2_AMI}
ami-029dc392355a76964
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ # ALB ARN
[cloudshell-user@ip-10-132-88-36 ~]$ LOGICALRESOURCEID='FrontLB'
[cloudshell-user@ip-10-132-88-36 ~]$ echo ${LOGICALRESOURCEID}
FrontLB
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ ALB_ARN=$(
>     aws cloudformation describe-stack-resources \
>         --stack-name ${STACK_NAME} \
>         --query "StackResources[?LogicalResourceId=='${LOGICALRESOURCEID}'].PhysicalResourceId" \
>         --output text
> ) \
> && echo ${ALB_ARN}
arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/monitoring-1-elb/c147aef4db266283
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ last_part=$(echo "${ALB_ARN}" | awk -F':' '{print $NF}') \
> && DIMENSIONS_ALB=$(echo ${last_part} | rev | cut -d'/' -f1-3 | rev) \
> && echo ${DIMENSIONS_ALB}
app/monitoring-1-elb/c147aef4db266283
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ # TARGETGROUP ARN
[cloudshell-user@ip-10-132-88-36 ~]$ LOGICALRESOURCEID='FrontLBTargetGroup'
[cloudshell-user@ip-10-132-88-36 ~]$ echo ${LOGICALRESOURCEID}
FrontLBTargetGroup
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ TARGET_GROUP_ARN=$(
>     aws cloudformation describe-stack-resources \
>         --stack-name ${STACK_NAME} \
>         --query "StackResources[?LogicalResourceId=='${LOGICALRESOURCEID}'].PhysicalResourceId" \
>         --output text
> ) \
> && echo ${TARGET_GROUP_ARN}
arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/monitoring-1-tg/0726cfe1b71c5746
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ last_part=$(echo "${TARGET_GROUP_ARN}" | awk -F':' '{print $NF}') \
> && DIMENSIONS_TG=$(echo ${last_part} | rev | cut -d'/' -f1-3 | rev) \
> && echo ${DIMENSIONS_TG}
targetgroup/monitoring-1-tg/0726cfe1b71c5746
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ # RDS
[cloudshell-user@ip-10-132-88-36 ~]$ RDS_INSTANCE_ID=$(
>     aws cloudformation describe-stack-resources \
>         --stack-name ${STACK_NAME} \
>         --query "StackResources[?LogicalResourceId=='DBInstance'].PhysicalResourceId" \
>         --output text
> ) \
> && echo ${RDS_INSTANCE_ID}
monitoring-1-rds

取得期間の指定

コマンド
# 現在時間のUnixタイムスタンプ
END_TIME=$(date +%s)
echo ${END_TIME}

# 1時間前のUnixタイムスタンプ
START_TIME=$(date -d '-2 hours' +%s)
echo ${START_TIME}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ # 現在時間のUnixタイムスタンプ
[cloudshell-user@ip-10-132-88-36 ~]$ END_TIME=$(date +%s)
[cloudshell-user@ip-10-132-88-36 ~]$ echo ${END_TIME}
1719100110
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ # 1時間前のUnixタイムスタンプ
[cloudshell-user@ip-10-132-88-36 ~]$ START_TIME=$(date -d '-2 hours' +%s)
[cloudshell-user@ip-10-132-88-36 ~]$ echo ${START_TIME}
1719092910

メトリクスの取得

EC2 CPU使用率(CPUUtilization)

コマンド
aws cloudwatch get-metric-statistics \
    --metric-name CPUUtilization \
    --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --period 300 \
    --namespace AWS/EC2 \
    --statistics Average \
    --dimensions Name=InstanceId,Value=${EC2_INSTANCE_ID_1}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws cloudwatch get-metric-statistics \
>     --metric-name CPUUtilization \
>     --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --period 300 \
>     --namespace AWS/EC2 \
>     --statistics Average \
>     --dimensions Name=InstanceId,Value=${EC2_INSTANCE_ID_1}
{
    "Label": "CPUUtilization",
    "Datapoints": [
        {
            "Timestamp": "2024-06-22T23:23:00+00:00",
            "Average": 19.2,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2024-06-22T23:28:00+00:00",
            "Average": 0.8721499905784793,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2024-06-22T23:33:00+00:00",
            "Average": 0.8632299397630666,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2024-06-22T23:38:00+00:00",
            "Average": 2.629706579187167,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2024-06-22T23:43:00+00:00",
            "Average": 1.4480156859787752,
            "Unit": "Percent"
        }
    ]
}

EC2 ネットワーク入力(NetworkIn)

コマンド
aws cloudwatch get-metric-statistics \
    --metric-name NetworkIn \
    --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --period 300 \
    --namespace AWS/EC2 \
    --statistics Average \
    --dimensions Name=InstanceId,Value=${EC2_INSTANCE_ID_1}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws cloudwatch get-metric-statistics \
>     --metric-name NetworkIn \
>     --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --period 300 \
>     --namespace AWS/EC2 \
>     --statistics Average \
>     --dimensions Name=InstanceId,Value=${EC2_INSTANCE_ID_1}
{
    "Label": "NetworkIn",
    "Datapoints": [
        {
            "Timestamp": "2024-06-22T23:28:00+00:00",
            "Average": 33506.0,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2024-06-22T23:23:00+00:00",
            "Average": 56110839.4,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2024-06-22T23:38:00+00:00",
            "Average": 302097.2,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2024-06-22T23:33:00+00:00",
            "Average": 37111.6,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2024-06-22T23:43:00+00:00",
            "Average": 116185.0,
            "Unit": "Bytes"
        }
    ]
}

EC2 ネットワーク出力(NetworkOut)

コマンド
aws cloudwatch get-metric-statistics \
    --metric-name NetworkOut \
    --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --period 300 \
    --namespace AWS/EC2 \
    --statistics Average \
    --dimensions Name=InstanceId,Value=${EC2_INSTANCE_ID_1}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws cloudwatch get-metric-statistics \
>     --metric-name NetworkOut \
>     --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --period 300 \
>     --namespace AWS/EC2 \
>     --statistics Average \
>     --dimensions Name=InstanceId,Value=${EC2_INSTANCE_ID_1}
{
    "Label": "NetworkOut",
    "Datapoints": [
        {
            "Timestamp": "2024-06-22T23:28:00+00:00",
            "Average": 22059.0,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2024-06-22T23:23:00+00:00",
            "Average": 252882.0,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2024-06-22T23:38:00+00:00",
            "Average": 873908.8,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2024-06-22T23:33:00+00:00",
            "Average": 22911.4,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2024-06-22T23:43:00+00:00",
            "Average": 261257.6,
            "Unit": "Bytes"
        }
    ]
}

AppELB 別、TG 別メトリクス (HealthyHostCount)

コマンド
aws cloudwatch get-metric-statistics \
    --namespace AWS/ApplicationELB \
    --metric-name HealthyHostCount \
    --dimensions Name=TargetGroup,Value=${DIMENSIONS_TG} Name=LoadBalancer,Value=${DIMENSIONS_ALB} \
    --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --period 300 \
    --statistics Average
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws cloudwatch get-metric-statistics \
>     --namespace AWS/ApplicationELB \
>     --metric-name HealthyHostCount \
>     --dimensions Name=TargetGroup,Value=${DIMENSIONS_TG} Name=LoadBalancer,Value=${DIMENSIONS_ALB} \
>     --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --period 300 \
>     --statistics Average
{
    "Label": "HealthyHostCount",
    "Datapoints": [
        {
            "Timestamp": "2024-06-22T23:33:00+00:00",
            "Average": 2.0,
            "Unit": "Count"
        },
        {
            "Timestamp": "2024-06-22T23:28:00+00:00",
            "Average": 2.0,
            "Unit": "Count"
        },
        {
            "Timestamp": "2024-06-22T23:23:00+00:00",
            "Average": 2.0,
            "Unit": "Count"
        },
        {
            "Timestamp": "2024-06-22T23:43:00+00:00",
            "Average": 2.0,
            "Unit": "Count"
        },
        {
            "Timestamp": "2024-06-22T23:38:00+00:00",
            "Average": 2.0,
            "Unit": "Count"
        }
    ]
}

RDS(WriteIOPS)

コマンド
aws cloudwatch get-metric-statistics \
    --metric-name WriteIOPS \
    --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --period 300 \
    --namespace AWS/RDS \
    --statistics Average \
    --dimensions Name=DBInstanceIdentifier,Value=${RDS_INSTANCE_ID}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws cloudwatch get-metric-statistics \
>     --metric-name WriteIOPS \
>     --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --period 300 \
>     --namespace AWS/RDS \
>     --statistics Average \
>     --dimensions Name=DBInstanceIdentifier,Value=${RDS_INSTANCE_ID}
{
    "Label": "WriteIOPS",
    "Datapoints": [
        {
            "Timestamp": "2024-06-22T23:33:00+00:00",
            "Average": 0.3333804284775603,
            "Unit": "Count/Second"
        },
        {
            "Timestamp": "2024-06-22T23:28:00+00:00",
            "Average": 0.8397166918240048,
            "Unit": "Count/Second"
        },
        {
            "Timestamp": "2024-06-22T23:43:00+00:00",
            "Average": 7.784855338298053,
            "Unit": "Count/Second"
        },
        {
            "Timestamp": "2024-06-22T23:38:00+00:00",
            "Average": 0.126673406820922,
            "Unit": "Count/Second"
        },
        {
            "Timestamp": "2024-06-22T23:23:00+00:00",
            "Average": 129.89268581547697,
            "Unit": "Count/Second"
        }
    ]
}

RDS(ReadIOPS)

コマンド
aws cloudwatch get-metric-statistics \
    --metric-name ReadIOPS \
    --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --period 300 \
    --namespace AWS/RDS \
    --statistics Average \
    --dimensions Name=DBInstanceIdentifier,Value=${RDS_INSTANCE_ID}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws cloudwatch get-metric-statistics \
>     --metric-name ReadIOPS \
>     --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --period 300 \
>     --namespace AWS/RDS \
>     --statistics Average \
>     --dimensions Name=DBInstanceIdentifier,Value=${RDS_INSTANCE_ID}
{
    "Label": "ReadIOPS",
    "Datapoints": [
        {
            "Timestamp": "2024-06-22T23:33:00+00:00",
            "Average": 0.3301217130739428,
            "Unit": "Count/Second"
        },
        {
            "Timestamp": "2024-06-22T23:28:00+00:00",
            "Average": 0.2632421608157417,
            "Unit": "Count/Second"
        },
        {
            "Timestamp": "2024-06-22T23:43:00+00:00",
            "Average": 0.2799391798832384,
            "Unit": "Count/Second"
        },
        {
            "Timestamp": "2024-06-22T23:38:00+00:00",
            "Average": 0.2667908389089163,
            "Unit": "Count/Second"
        },
        {
            "Timestamp": "2024-06-22T23:23:00+00:00",
            "Average": 11.988669499291843,
            "Unit": "Count/Second"
        }
    ]
}

EC2 カスタムメトリクス(disk_used_percent)

コマンド
aws cloudwatch get-metric-statistics \
    --namespace CWAgent \
    --metric-name disk_used_percent \
    --dimensions Name=InstanceId,Value=${EC2_INSTANCE_ID_1} Name=path,Value="/" Name=ImageId,Value=${EC2_AMI} Name=InstanceType,Value="t2.micro" Name=device,Value="xvda1" Name=fstype,Value="xfs" \
    --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --period 300 \
    --statistics Average
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws cloudwatch get-metric-statistics \
>     --namespace CWAgent \
>     --metric-name disk_used_percent \
>     --dimensions Name=InstanceId,Value=${EC2_INSTANCE_ID_1} Name=path,Value="/" Name=ImageId,Value=${EC2_AMI} Name=InstanceType,Value="t2.micro" Name=device,Value="xvda1" Name=fstype,Value="xfs" \
>     --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --period 300 \
>     --statistics Average
{
    "Label": "disk_used_percent",
    "Datapoints": [
        {
            "Timestamp": "2024-06-22T23:23:00+00:00",
            "Average": 29.81738953953416,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2024-06-22T23:28:00+00:00",
            "Average": 29.81684992180318,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2024-06-22T23:33:00+00:00",
            "Average": 29.814806059954872,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2024-06-22T23:38:00+00:00",
            "Average": 29.81401334718193,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2024-06-22T23:43:00+00:00",
            "Average": 29.8171173429796,
            "Unit": "Percent"
        }
    ]
}

EC2 カスタムメトリクス(disk_used_percent)

コマンド
aws cloudwatch get-metric-statistics \
    --namespace CWAgent \
    --metric-name mem_used_percent \
    --dimensions Name=InstanceId,Value=${EC2_INSTANCE_ID_1} Name=ImageId,Value=${EC2_AMI} Name=InstanceType,Value="t2.micro" \
    --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
    --period 300 \
    --statistics Average
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws cloudwatch get-metric-statistics \
>     --namespace CWAgent \
>     --metric-name mem_used_percent \
>     --dimensions Name=InstanceId,Value=${EC2_INSTANCE_ID_1} Name=ImageId,Value=${EC2_AMI} Name=InstanceType,Value="t2.micro" \
>     --start-time $(date -d @$START_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --end-time $(date -d @$END_TIME -u +%Y-%m-%dT%H:%M:%SZ) \
>     --period 300 \
>     --statistics Average
{
    "Label": "mem_used_percent",
    "Datapoints": [
        {
            "Timestamp": "2024-06-22T23:23:00+00:00",
            "Average": 13.611785500034223,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2024-06-22T23:28:00+00:00",
            "Average": 12.778200529043012,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2024-06-22T23:33:00+00:00",
            "Average": 12.724249415194084,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2024-06-22T23:38:00+00:00",
            "Average": 12.720303736718565,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2024-06-22T23:43:00+00:00",
            "Average": 25.773735470441636,
            "Unit": "Percent"
        }
    ]
}

4. CloudWatch Alarms

変数設定

コマンド
# アラーム名
ALARM_NAME="monitoring-1-alarm" \
&& echo ${ALARM_NAME}

# トピック名
TOPIC_NAME="monitoring-1-topic" \
&& echo ${TOPIC_NAME}

# メールアドレス
EMAIL="username@example.com" \
&& echo ${EMAIL}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ # アラーム名
[cloudshell-user@ip-10-132-88-36 ~]$ ALARM_NAME="monitoring-1-alarm" \
> && echo ${ALARM_NAME}
monitoring-1-alarm
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ # トピック名
[cloudshell-user@ip-10-132-88-36 ~]$ TOPIC_NAME="monitoring-1-topic" \
> && echo ${TOPIC_NAME}
monitoring-1-topic
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ # メールアドレス
[cloudshell-user@ip-10-132-88-36 ~]$ EMAIL="username@example.com" \
> && echo ${EMAIL}
username@example.com

トピック作成

コマンド
aws sns create-topic --name ${TOPIC_NAME}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws sns create-topic --name ${TOPIC_NAME}
{
    "TopicArn": "arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic"
}

ARN取得

コマンド
# トピックのARNを取得
TOPIC_ARN=$(
    aws sns list-topics \
        --query "Topics[?contains(TopicArn, '${TOPIC_NAME}')].TopicArn" \
        --output text
) \
&& echo ${TOPIC_ARN}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ TOPIC_ARN=$(
>     aws sns list-topics \
>         --query "Topics[?contains(TopicArn, '${TOPIC_NAME}')].TopicArn" \
>         --output text
> ) \
> && echo ${TOPIC_ARN}
arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic

サブスクリプションの作成

コマンド
aws sns subscribe \
    --topic-arn $TOPIC_ARN \
    --protocol email \
    --notification-endpoint ${EMAIL}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws sns subscribe \
>     --topic-arn $TOPIC_ARN \
>     --protocol email \
>     --notification-endpoint ${EMAIL}
{
    "SubscriptionArn": "pending confirmation"
}

CloudWatchアラームの作成

コマンド
aws cloudwatch put-metric-alarm --alarm-name ${ALARM_NAME} \
    --metric-name "disk_used_percent" \
    --namespace "CWAgent" \
    --statistic "Average" \
    --period 900 \
    --threshold 90 \
    --comparison-operator "GreaterThanOrEqualToThreshold" \
    --dimensions Name=InstanceId,Value=${EC2_INSTANCE_ID_1} Name=path,Value="/" Name=ImageId,Value=${EC2_AMI} Name=InstanceType,Value="t2.micro" Name=device,Value="xvda1" Name=fstype,Value="xfs" \
    --evaluation-periods 1 \
    --alarm-actions ${TOPIC_ARN}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws cloudwatch put-metric-alarm --alarm-name ${ALARM_NAME} \
>     --metric-name "disk_used_percent" \
>     --namespace "CWAgent" \
>     --statistic "Average" \
>     --period 900 \
>     --threshold 90 \
>     --comparison-operator "GreaterThanOrEqualToThreshold" \
>     --dimensions Name=InstanceId,Value=${EC2_INSTANCE_ID_1} Name=path,Value="/" Name=ImageId,Value=${EC2_AMI} Name=InstanceType,Value="t2.micro" Name=device,Value="xvda1" Name=fstype,Value="xfs" \
>     --evaluation-periods 1 \
>     --alarm-actions ${TOPIC_ARN}

CloudWatchログの確認

変数設定

コマンド
LOG_GROUP_NAME='wordpress_access_log' \
&& echo ${LOG_GROUP_NAME}

LOG_ACCESS_NAME='wordpress_access_log' \
&& echo ${LOG_ACCESS_NAME}

LOG_ERROR_NAME='wordpress_error_log' \
&& echo ${LOG_ERROR_NAME}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ LOG_GROUP_NAME='wordpress_access_log' \
> && echo ${LOG_GROUP_NAME}
wordpress_access_log
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ LOG_ACCESS_NAME='wordpress_access_log' \
> && echo ${LOG_ACCESS_NAME}
wordpress_access_log
[cloudshell-user@ip-10-132-88-36 ~]$ 
[cloudshell-user@ip-10-132-88-36 ~]$ LOG_ERROR_NAME='wordpress_error_log' \
> && echo ${LOG_ERROR_NAME}
wordpress_error_log

最新のログストリーム名を取得

コマンド
LATEST_LOG_STREAM_NAME=$(
    aws logs describe-log-streams \
        --log-group-name "$LOG_GROUP_NAME" \
        --order-by LastEventTime \
        --descending \
        --limit 1 | jq -r '.logStreams[0].logStreamName'
) \
&& echo ${LATEST_LOG_STREAM_NAME}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ LATEST_LOG_STREAM_NAME=$(
>     aws logs describe-log-streams \
>     --log-group-name "$LOG_GROUP_NAME" \
>     --order-by LastEventTime \
>     --descending \
>     --limit 1 | jq -r '.logStreams[0].logStreamName'
> ) \
> && echo ${LATEST_LOG_STREAM_NAME}
i-02cee7d18cb05c8e9

ログの確認

コマンド
aws logs get-log-events \
    --log-group-name ${LOG_GROUP_NAME} \
    --log-stream-name ${LATEST_LOG_STREAM_NAME} \
    --output table
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws logs get-log-events \
>     --log-group-name ${LOG_GROUP_NAME} \
>     --log-stream-name ${LATEST_LOG_STREAM_NAME} \
>     --output table
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|                                                                                                                                                                                                                                                                                                        GetLogEvents                                                                                                                                                                                                                                                                                                        |
+----------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|  nextBackwardToken                                                                                                                                 |  b/38337570254780535266769393403704440839829444184946114560/s                                                                                                                                                                                                                                                                                                                                                                                                         |
|  nextForwardToken                                                                                                                                  |  f/38337682176645500392334291047353364048084678697053388801/s                                                                                                                                                                                                                                                                                                                                                                                                         |
+----------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
||                                                                                                                                                                                                                                                                                                          events                                                                                                                                                                                                                                                                                                          ||
|+---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+|
|| ingestionTime |                                                                                                                                                                                                                                                                                         message                                                                                                                                                                                                                                                                                         |   timestamp    ||
|+---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+|
||  1719117011969|  10.0.0.222 - - [23/Jun/2024:04:30:06 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |  1719117006937 ||
||  1719117011969|  10.0.1.176 - - [23/Jun/2024:04:30:06 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |  1719117011117 ||
||  1719117042021|  10.0.0.222 - - [23/Jun/2024:04:30:36 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |  1719117036999 ||
||  1719117042021|  10.0.1.176 - - [23/Jun/2024:04:30:36 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |  1719117041117 ||
||  1719117072099|  10.0.0.222 - - [23/Jun/2024:04:31:06 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |  1719117067071 ||
||  1719117072099|  10.0.1.176 - - [23/Jun/2024:04:31:06 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |  1719117071117 ||
|+---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+|

フィルター

コマンド
aws logs filter-log-events \
    --log-group-name ${LOG_GROUP_NAME} \
    --filter-pattern "GET" \
    --output table
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws logs filter-log-events \
>     --log-group-name ${LOG_GROUP_NAME} \
>     --filter-pattern "GET" \
>     --output table
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|                                                                                                                                                                                                                                                                                                                                                FilterLogEvents                                                                                                                                                                                                                                                                                                                                                |
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
||                                                                                                                                                                                                                                                                                                                                                   events                                                                                                                                                                                                                                                                                                                                                    ||
|+----------------------------------------------------------+----------------+----------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+|
||                          eventId                         | ingestionTime  |    logStreamName     |                                                                                                                                                                                                                                                                                         message                                                                                                                                                                                                                                                                                         |   timestamp    ||
|+----------------------------------------------------------+----------------+----------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+|
||  38336162989001542094297206108908958612843111801005670400|  1719053007714 |  i-07ebafd72024ae1a4 |  15.177.2.30 - - [22/Jun/2024:10:42:44 +0000] "GET / HTTP/1.1" 302 - "-" "Amazon-Route53-Health-Check-Service (ref d5fdcdf0-bc0e-4b97-8653-9d8cb3286735; report http://amzn.to/1vsZADi)"                                                                                                                                                                                                                                                                                                                                                                                                |  1719053002387 ||
||  38336162989001542094297206108908958612843111801005670401|  1719053007714 |  i-07ebafd72024ae1a4 |  15.177.14.137 - - [22/Jun/2024:10:42:48 +0000] "GET / HTTP/1.1" 302 - "-" "Amazon-Route53-Health-Check-Service (ref d5fdcdf0-bc0e-4b97-8653-9d8cb3286735; report http://amzn.to/1vsZADi)"                                                                                                                                                                                                                                                                                                                                                                                              |  1719053002387 ||
||  38336162989001542094297206108908958612843111801005670402|  1719053007714 |  i-07ebafd72024ae1a4 |  15.177.18.108 - - [22/Jun/2024:10:42:48 +0000] "GET / HTTP/1.1" 302 - "-" "Amazon-Route53-Health-Check-Service (ref d5fdcdf0-bc0e-4b97-8653-9d8cb3286735; report http://amzn.to/1vsZADi)"                                                                                                                                                                                                                                                                                                                                                                                              |  1719053002387 ||
||  38336162989001542094297206108908958612843111801005670403|  1719053007714 |  i-07ebafd72024ae1a4 |  15.177.30.159 - - [22/Jun/2024:10:42:49 +0000] "GET / HTTP/1.1" 302 - "-" "Amazon-Route53-Health-Check-Service (ref d5fdcdf0-bc0e-4b97-8653-9d8cb3286735; report http://amzn.to/1vsZADi)"                                                                                                                                                                                                                                                                                                                                                                                              |  1719053002387 ||  
|+----------------------------------------------------------+----------------+----------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+|

5. CloudWatch Logs Insights

クエリ実行

コマンド
# クエリIDを変数に保存
QUERY_ID=$(aws logs start-query \
    --log-group-name $LOG_GROUP_NAME \
    --start-time $(date -d @$START_TIME -u +%s) \
    --end-time $(date -d @$END_TIME -u +%s) \
    --query-string "fields @timestamp, @message | sort @timestamp desc | limit 20" \
    --query "queryId" \
    --output text
) \
&& echo ${QUERY_ID}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ # クエリIDを変数に保存
[cloudshell-user@ip-10-132-88-36 ~]$ QUERY_ID=$(aws logs start-query \
>     --log-group-name $LOG_GROUP_NAME \
>     --start-time $(date -d @$START_TIME -u +%s) \
>     --end-time $(date -d @$END_TIME -u +%s) \
>     --query-string "fields @timestamp, @message | sort @timestamp desc | limit 20" \
>     --query "queryId" \
>     --output text
> ) \
> && echo ${QUERY_ID}
17e92a1b-5d49-4417-a571-96c7f67ab71a

クエリ結果の確認

コマンド
# クエリ結果を取得
aws logs get-query-results \
    --query-id ${QUERY_ID} \
    --output table
出力
[cloudshell-user@ip-10-132-88-36 ~]$ # クエリ結果を取得
[cloudshell-user@ip-10-132-88-36 ~]$ aws logs get-query-results \
>     --query-id ${QUERY_ID} \
>     --output table
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|                                                                                   GetQueryResults                                                                                  |
+---------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+
|  status                                                                         |  Complete                                                                                        |
+---------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+
||                                                                                      results                                                                                     ||
|+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+|
||    field   |                                                                                value                                                                                ||
|+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+|
||  @timestamp|  2024-06-22 23:48:29.117                                                                                                                                            ||
||  @message  |  10.0.1.176 - - [22/Jun/2024:23:48:24 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAQiDgiwr7CPhDIQl/HnkoQyEjUaGAIGYhoZ3wAAAAFLOVB2AAZndiggAAAE8iABKJ++55KEMjC94ueShDI4AkCSAkiaB1DJAxgAIAEQARgB   ||
||  @timestamp|  2024-06-22 23:48:29.056                                                                                                                                            ||
||  @message  |  10.0.1.176 - - [22/Jun/2024:23:48:24 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAciDgiwr7CPhDIQl/HnkoQyEjUaGAIGTNfXYwAAAAU1BW6hAAZndiuAAAAFMiABKIy/55KEMjDtzOmShDI4BkC2BkjTCFCABRgAIAEQARgB   ||
||  @timestamp|  2024-06-22 23:48:24.588                                                                                                                                            ||
||  @message  |  10.0.0.222 - - [22/Jun/2024:23:48:23 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAciDgiwr7CPhDIQl/HnkoQyEjUaGAIGTNfXYwAAAAU1BW6hAAZndiuAAAAFMiABKIy/55KEMjDtzOmShDI4BkC2BkjTCFCABRgAIAEQABgB   ||
||  @timestamp|  2024-06-22 23:48:24.479                                                                                                                                            ||
||  @message  |  10.0.0.222 - - [22/Jun/2024:23:48:23 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAQiDgiwr7CPhDIQl/HnkoQyEjUaGAIGYhoZ3wAAAAFLOVB2AAZndiggAAAE8iABKJ++55KEMjC94ueShDI4AkCSAkiaB1DJAxgAIAEQABgB   ||
||  @timestamp|  2024-06-22 23:47:59.116                                                                                                                                            ||
||  @message  |  10.0.1.176 - - [22/Jun/2024:23:47:54 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAciDgiwr7CPhDIQl/HnkoQyEjUaGAIGTNfXYwAAAAU1BJwMAAZndiMgAAAFMiABKKCf3pKEMjCM+OWShDI4EECiH0iqDlDXChgAIAEQDxgB   ||
||  @timestamp|  2024-06-22 23:47:59.057                                                                                                                                            ||
||  @message  |  10.0.1.176 - - [22/Jun/2024:23:47:54 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAMiDgiwr7CPhDIQl/HnkoQyEjUaGAIGVMKtUQAAAANuJbAMAAZndiewAAACEiABKI3U5ZKEMjDR9+WShDI4AkCSAkidB1DMAxgAIAEQARgB   ||
||  @timestamp|  2024-06-22 23:47:54.509                                                                                                                                            ||
||  @message  |  10.0.0.222 - - [22/Jun/2024:23:47:53 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAMiDgiwr7CPhDIQl/HnkoQyEjUaGAIGVMKtUQAAAANuJbAMAAZndiewAAACEiABKI3U5ZKEMjDR9+WShDI4AkCSAkidB1DMAxgAIAEQABgB   ||
||  @timestamp|  2024-06-22 23:47:54.412                                                                                                                                            ||
||  @message  |  10.0.0.222 - - [22/Jun/2024:23:47:53 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAciDgiwr7CPhDIQl/HnkoQyEjUaGAIGTNfXYwAAAAU1BJwMAAZndiMgAAAFMiABKKCf3pKEMjCM+OWShDI4EECiH0iqDlDXChgAIAEQDhgB   ||
||  @timestamp|  2024-06-22 23:47:29.117                                                                                                                                            ||
||  @message  |  10.0.1.176 - - [22/Jun/2024:23:47:24 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAYiDgiwr7CPhDIQl/HnkoQyEjUaGAIGZvZEWwAAAAOKtKPgAAZndiCwAAADsiABKJGV4JKEMjDdjeSShDI4BECkBEiaCFDHBBgAIAEQAxgB   ||
||  @timestamp|  2024-06-22 23:47:29.056                                                                                                                                            ||
||  @message  |  10.0.1.176 - - [22/Jun/2024:23:47:24 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAEiDgiwr7CPhDIQl/HnkoQyEjUaGAIGUyFXogAAAAR3l+31AAZndiNwAAAGIiABKISA4pKEMjCgjeSShDI4BECkBEjeB1CMBBgAIAEQAxgB   ||
||  @timestamp|  2024-06-22 23:47:24.422                                                                                                                                            ||
||  @message  |  10.0.0.222 - - [22/Jun/2024:23:47:23 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAEiDgiwr7CPhDIQl/HnkoQyEjUaGAIGUyFXogAAAAR3l+31AAZndiNwAAAGIiABKISA4pKEMjCgjeSShDI4BECkBEjeB1CMBBgAIAEQAhgB   ||
||  @timestamp|  2024-06-22 23:47:24.335                                                                                                                                            ||
||  @message  |  10.0.0.222 - - [22/Jun/2024:23:47:23 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAYiDgiwr7CPhDIQl/HnkoQyEjUaGAIGZvZEWwAAAAOKtKPgAAZndiCwAAADsiABKJGV4JKEMjDdjeSShDI4BECkBEiaCFDHBBgAIAEQAhgB   ||
||  @timestamp|  2024-06-22 23:46:59.117                                                                                                                                            ||
||  @message  |  10.0.1.176 - - [22/Jun/2024:23:46:54 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAciDgiwr7CPhDIQl/HnkoQyEjUaGAIGTNfXYwAAAAU1BJwMAAZndiMgAAAFMiABKKCf3pKEMjCM+OWShDI4EECiH0iqDlDXChgAIAEQDRgB   ||
||  @timestamp|  2024-06-22 23:46:59.057                                                                                                                                            ||
||  @message  |  10.0.1.176 - - [22/Jun/2024:23:46:54 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAEiDgiwr7CPhDIQl/HnkoQyEjUaGAIGUyFXogAAAAR3l+31AAZndiNwAAAGIiABKISA4pKEMjCgjeSShDI4BECkBEjeB1CMBBgAIAEQARgB   ||
||  @timestamp|  2024-06-22 23:46:54.596                                                                                                                                            ||
||  @message  |  10.0.0.222 - - [22/Jun/2024:23:46:53 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAEiDgiwr7CPhDIQl/HnkoQyEjUaGAIGUyFXogAAAAR3l+31AAZndiNwAAAGIiABKISA4pKEMjCgjeSShDI4BECkBEjeB1CMBBgAIAEQABgB   ||
||  @timestamp|  2024-06-22 23:46:54.509                                                                                                                                            ||
||  @message  |  10.0.0.222 - - [22/Jun/2024:23:46:53 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAciDgiwr7CPhDIQl/HnkoQyEjUaGAIGTNfXYwAAAAU1BJwMAAZndiMgAAAFMiABKKCf3pKEMjCM+OWShDI4EECiH0iqDlDXChgAIAEQDBgB   ||
||  @timestamp|  2024-06-22 23:46:29.117                                                                                                                                            ||
||  @message  |  10.0.1.176 - - [22/Jun/2024:23:46:24 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAQiDgiwr7CPhDIQl/HnkoQyEjUaGAIGYhoZ3wAAAAFLN1c5AAZndh+wAAAE8iABKPje25KEMjD9uOCShDI4C0CfEUi6DFDnCBgAIAEQChgB   ||
||  @timestamp|  2024-06-22 23:46:29.056                                                                                                                                            ||
||  @message  |  10.0.1.176 - - [22/Jun/2024:23:46:24 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAYiDgiwr7CPhDIQl/HnkoQyEjUaGAIGZvZEWwAAAAOKtKPgAAZndiCwAAADsiABKJGV4JKEMjDdjeSShDI4BECkBEiaCFDHBBgAIAEQARgB   ||
||  @timestamp|  2024-06-22 23:46:24.529                                                                                                                                            ||
||  @message  |  10.0.0.222 - - [22/Jun/2024:23:46:23 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAYiDgiwr7CPhDIQl/HnkoQyEjUaGAIGZvZEWwAAAAOKtKPgAAZndiCwAAADsiABKJGV4JKEMjDdjeSShDI4BECkBEiaCFDHBBgAIAEQABgB   ||
||  @timestamp|  2024-06-22 23:46:24.430                                                                                                                                            ||
||  @message  |  10.0.0.222 - - [22/Jun/2024:23:46:23 +0000] "GET /.check_alive HTTP/1.1" 200 - "-" "ELB-HealthChecker/2.0"                                                         ||
||  @ptr      |  CnIKNQohNDIzNzYxMTc1MTk3OndvcmRwcmVzc19hY2Nlc3NfbG9nEAQiDgiwr7CPhDIQl/HnkoQyEjUaGAIGYhoZ3wAAAAFLN1c5AAZndh+wAAAE8iABKPje25KEMjD9uOCShDI4C0CfEUi6DFDnCBgAIAEQCRgB   ||
|+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+|
||                                                                                    statistics                                                                                    ||
|+--------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+|
||  bytesScanned                                                                                                |  72658.0                                                          ||
||  recordsMatched                                                                                              |  325.0                                                            ||
||  recordsScanned                                                                                              |  329.0                                                            ||
|+--------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+|

ハンズオン内で指定しているクエリは管理コンソールからだとうまくいくが、CLIからだとうまくいかなかった

6. CloudWatch Dashboards

変数設定

コマンド
# ダッシュボード名
DASHBOARD="WordPress_dashboard"
echo ${DASHBOARD}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ # ダッシュボード名
[cloudshell-user@ip-10-132-88-36 ~]$ DASHBOARD="WordPress_dashboard"
[cloudshell-user@ip-10-132-88-36 ~]$ echo ${DASHBOARD}
WordPress_dashboard

ダッシュボード用JSONファイル作成

コマンド
cat << EOF > dashboard.json
{
    "widgets": [
        {
            "height": 6,
            "width": 6,
            "y": 0,
            "x": 0,
            "type": "metric",
            "properties": {
                "view": "timeSeries",
                "stacked": false,
                "metrics": [
                    [ "AWS/EC2", "CPUUtilization", "InstanceId", "${EC2_INSTANCE_ID_1}" ],
                    [ "...", "${EC2_INSTANCE_ID_2}" ]
                ],
                "region": "ap-northeast-1"
            }
        },
        {
            "height": 6,
            "width": 6,
            "y": 0,
            "x": 6,
            "type": "text",
            "properties": {
                "markdown": "# WordPress障害時メモ\n非常時は以下のボタンをクリックしてください \n\n [button:primary:非常時ボタン](https://amazon.com) \n "
            }
        },
        {
            "height": 6,
            "width": 24,
            "y": 6,
            "x": 0,
            "type": "log",
            "properties": {
                "query": "SOURCE 'wordpress_access_log' | fields @timestamp, @message, @logStream, @log\n| sort @timestamp desc\n| limit 1000",
                "region": "ap-northeast-1",
                "stacked": false,
                "view": "table"
            }
        }
    ]
}
EOF
出力
[cloudshell-user@ip-10-132-88-36 ~]$ cat << EOF > dashboard.json
> {
>     "widgets": [
>         {
>             "height": 6,
>             "width": 6,
>             "y": 0,
>             "x": 0,
>             "type": "metric",
>             "properties": {
>                 "view": "timeSeries",
>                 "stacked": false,
>                 "metrics": [
>                     [ "AWS/EC2", "CPUUtilization", "InstanceId", "${EC2_INSTANCE_ID_1}" ],
>                     [ "...", "${EC2_INSTANCE_ID_2}" ]
>                 ],
>                 "region": "ap-northeast-1"
>             }
>         },
>         {
>             "height": 6,
>             "width": 6,
>             "y": 0,
>             "x": 6,
>             "type": "text",
>             "properties": {
>                 "markdown": "# WordPress障害時メモ\n非常時は以下のボタンをクリックしてください \n\n [button:primary:非常時ボタン](https://amazon.com) \n "
>             }
>         },
>         {
>             "height": 6,
>             "width": 24,
>             "y": 6,
>             "x": 0,
>             "type": "log",
>             "properties": {
>                 "query": "SOURCE 'wordpress_access_log' | fields @timestamp, @message, @logStream, @log\n| sort @timestamp desc\n| limit 1000",
>                 "region": "ap-northeast-1",
>                 "stacked": false,
>                 "view": "table"
>             }
>         }
>     ]
> }
> EOF

ダッシュボード作成

コマンド
aws cloudwatch put-dashboard \
    --dashboard-name ${DASHBOARD} \
    --dashboard-body file://dashboard.json
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws cloudwatch put-dashboard \
>     --dashboard-name ${DASHBOARD} \
>     --dashboard-body file://dashboard.json
{
    "DashboardValidationMessages": []
}

7. CloudWatch Events (Amazon EventBridge)

変数設定

コマンド
# ルール名
EVENT_RULE_NAME="monitoring-1-event-rule" \
&& echo ${EVENT_RULE_NAME}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ # ルール名
[cloudshell-user@ip-10-132-88-36 ~]$ EVENT_RULE_NAME="monitoring-1-event-rule" \
> && echo ${EVENT_RULE_NAME}
monitoring-1-event-rule

EventBridgeルールの作成

ルールの作成

コマンド
aws events put-rule \
    --name ${EVENT_RULE_NAME} \
    --event-pattern \
    '{  "source": ["aws.ec2"], 
      "detail-type": ["EC2 Instance State-change Notification"],
      "detail": {
          "state": ["stopped"]
          }
      }'
出力
[cloudshell-user@ip-10-132-88-36 ~]$ aws events put-rule \
>     --name ${EVENT_RULE_NAME} \
>     --event-pattern \
>     '{  "source": ["aws.ec2"], 
>       "detail-type": ["EC2 Instance State-change Notification"],
>       "detail": {
>           "state": ["stopped"]
>           }
>       }'
{
    "RuleArn": "arn:aws:events:ap-northeast-1:999999999999:rule/monitoring-1-event-rule"
}

ARNの取得

コマンド
EVENT_RULE_ARN=$(
    aws events describe-rule \
        --name ${EVENT_RULE_NAME} \
        --query "Arn" \
        --output text
) \
&& echo ${EVENT_RULE_ARN}
出力
[cloudshell-user@ip-10-132-88-36 ~]$ EVENT_RULE_ARN=$(
>     aws events describe-rule \
>         --name ${EVENT_RULE_NAME} \
>         --query "Arn" \
>         --output text
> ) \
> && echo ${EVENT_RULE_ARN}
arn:aws:events:ap-northeast-1:999999999999:rule/monitoring-1-event-rule

EventBridgeターゲットの作成

JSONファイルの作成

コマンド
cat << EOF > ${HOME}/${EVENT_RULE_NAME}.json
[
    {
        "Id": "1",
        "Arn": "${TOPIC_ARN}"
    }
]
EOF
出力
[cloudshell-user@ip-10-134-29-105 ~]$ cat << EOF > ${HOME}/${EVENT_RULE_NAME}.json
> [
>     {
>         "Id": "1",
>         "Arn": "${TOPIC_ARN}"
>     }
> ]
> EOF

ターゲットの作成

コマンド
aws events put-targets \
    --rule ${EVENT_RULE_NAME} \
    --targets file://${HOME}/${EVENT_RULE_NAME}.json
出力
[cloudshell-user@ip-10-134-29-105 ~]$ aws events put-targets \
>     --rule ${EVENT_RULE_NAME} \
>     --targets file://${HOME}/${EVENT_RULE_NAME}.json
{
    "FailedEntryCount": 0,
    "FailedEntries": []
}

SNSトピックにEventBridgeルールからの許可権限追加

コマンド
# 現在のSNSトピックのポリシーを取得
CURRENT_POLICY=$(
    aws sns get-topic-attributes \
        --topic-arn ${TOPIC_ARN} \
        --query "Attributes.Policy" \
        --output text
) \
&& echo ${CURRENT_POLICY}

# 現在のポリシーをJSON形式に変換
CURRENT_POLICY_JSON=$(echo ${CURRENT_POLICY} | jq .) \
&& echo ${CURRENT_POLICY_JSON}

# 新しいポリシーステートメント
NEW_POLICY_STATEMENT=$(cat <<EOF
{
  "Sid": "${EVENT_RULE_NAME}",
  "Effect": "Allow",
  "Principal": {
    "Service": "events.amazonaws.com"
  },
  "Action": "sns:Publish",
  "Resource": "${TOPIC_ARN}"
}
EOF
) \
&& echo ${NEW_POLICY_STATEMENT}

# ポリシーに新しいステートメントを追加
UPDATED_POLICY=$(echo ${CURRENT_POLICY_JSON} | jq --argjson stmt "${NEW_POLICY_STATEMENT}" '.Statement += [$stmt]') \
&& echo ${UPDATED_POLICY}

# 更新されたポリシーを文字列に変換
UPDATED_POLICY_STR=$(echo ${UPDATED_POLICY} | jq -c .) \
&& echo ${UPDATED_POLICY_STR}

aws sns set-topic-attributes \
    --topic-arn ${TOPIC_ARN} \
    --attribute-name Policy \
    --attribute-value "${UPDATED_POLICY_STR}"
出力
[cloudshell-user@ip-10-130-49-7 ~]$ # 現在のSNSトピックのポリシーを取得
[cloudshell-user@ip-10-130-49-7 ~]$ CURRENT_POLICY=$(
>     aws sns get-topic-attributes \
>         --topic-arn ${TOPIC_ARN} \
>         --query "Attributes.Policy" \
>         --output text
> ) \
> && echo ${CURRENT_POLICY}
{"Version":"2008-10-17","Id":"__default_policy_ID","Statement":[{"Sid":"__default_statement_ID","Effect":"Allow","Principal":{"AWS":"*"},"Action":["SNS:GetTopicAttributes","SNS:SetTopicAttributes","SNS:AddPermission","SNS:RemovePermission","SNS:DeleteTopic","SNS:Subscribe","SNS:ListSubscriptionsByTopic","SNS:Publish"],"Resource":"arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic","Condition":{"StringEquals":{"AWS:SourceOwner":"999999999999"}}}]}
[cloudshell-user@ip-10-130-49-7 ~]$ 
[cloudshell-user@ip-10-130-49-7 ~]$ # 現在のポリシーをJSON形式に変換
[cloudshell-user@ip-10-130-49-7 ~]$ CURRENT_POLICY_JSON=$(echo ${CURRENT_POLICY} | jq .) \
> && echo ${CURRENT_POLICY_JSON}
{ "Version": "2008-10-17", "Id": "__default_policy_ID", "Statement": [ { "Sid": "__default_statement_ID", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": [ "SNS:GetTopicAttributes", "SNS:SetTopicAttributes", "SNS:AddPermission", "SNS:RemovePermission", "SNS:DeleteTopic", "SNS:Subscribe", "SNS:ListSubscriptionsByTopic", "SNS:Publish" ], "Resource": "arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic", "Condition": { "StringEquals": { "AWS:SourceOwner": "999999999999" } } } ] }
[cloudshell-user@ip-10-130-49-7 ~]$ 
[cloudshell-user@ip-10-130-49-7 ~]$ # 新しいポリシーステートメント
[cloudshell-user@ip-10-130-49-7 ~]$ NEW_POLICY_STATEMENT=$(cat <<EOF
> {
>   "Sid": "${EVENT_RULE_NAME}",
>   "Effect": "Allow",
>   "Principal": {
>     "Service": "events.amazonaws.com"
>   },
>   "Action": "sns:Publish",
>   "Resource": "${TOPIC_ARN}"
> }
> EOF
> ) \
> && echo ${NEW_POLICY_STATEMENT}
{ "Sid": "monitoring-1-event-rule", "Effect": "Allow", "Principal": { "Service": "events.amazonaws.com" }, "Action": "sns:Publish", "Resource": "arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic" }
[cloudshell-user@ip-10-130-49-7 ~]$ 
[cloudshell-user@ip-10-130-49-7 ~]$ # ポリシーに新しいステートメントを追加
[cloudshell-user@ip-10-130-49-7 ~]$ UPDATED_POLICY=$(echo ${CURRENT_POLICY_JSON} | jq --argjson stmt "${NEW_POLICY_STATEMENT}" '.Statement += [$stmt]') \
> && echo ${UPDATED_POLICY}
{ "Version": "2008-10-17", "Id": "__default_policy_ID", "Statement": [ { "Sid": "__default_statement_ID", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": [ "SNS:GetTopicAttributes", "SNS:SetTopicAttributes", "SNS:AddPermission", "SNS:RemovePermission", "SNS:DeleteTopic", "SNS:Subscribe", "SNS:ListSubscriptionsByTopic", "SNS:Publish" ], "Resource": "arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic", "Condition": { "StringEquals": { "AWS:SourceOwner": "999999999999" } } }, { "Sid": "monitoring-1-event-rule", "Effect": "Allow", "Principal": { "Service": "events.amazonaws.com" }, "Action": "sns:Publish", "Resource": "arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic" } ] }
[cloudshell-user@ip-10-130-49-7 ~]$ 
[cloudshell-user@ip-10-130-49-7 ~]$ # 更新されたポリシーを文字列に変換
[cloudshell-user@ip-10-130-49-7 ~]$ UPDATED_POLICY_STR=$(echo ${UPDATED_POLICY} | jq -c .) \
> && echo ${UPDATED_POLICY_STR}
{"Version":"2008-10-17","Id":"__default_policy_ID","Statement":[{"Sid":"__default_statement_ID","Effect":"Allow","Principal":{"AWS":"*"},"Action":["SNS:GetTopicAttributes","SNS:SetTopicAttributes","SNS:AddPermission","SNS:RemovePermission","SNS:DeleteTopic","SNS:Subscribe","SNS:ListSubscriptionsByTopic","SNS:Publish"],"Resource":"arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic","Condition":{"StringEquals":{"AWS:SourceOwner":"999999999999"}}},{"Sid":"monitoring-1-event-rule","Effect":"Allow","Principal":{"Service":"events.amazonaws.com"},"Action":"sns:Publish","Resource":"arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic"}]}
[cloudshell-user@ip-10-130-49-7 ~]$ 
[cloudshell-user@ip-10-130-49-7 ~]$ aws sns set-topic-attributes \
>     --topic-arn ${TOPIC_ARN} \
>     --attribute-name Policy \
>     --attribute-value "${UPDATED_POLICY_STR}"

8. 削除

CloudFormation

コマンド
aws cloudformation delete-stack --stack-name ${STACK_NAME}
出力
[cloudshell-user@ip-10-130-49-7 ~]$ aws cloudformation delete-stack --stack-name ${STACK_NAME}

CloudWatch

ダッシュボード

コマンド
aws cloudwatch delete-dashboards --dashboard-names ${DASHBOARD}
出力
[cloudshell-user@ip-10-130-49-7 ~]$ aws cloudwatch delete-dashboards --dashboard-names ${DASHBOARD}

アラーム

コマンド
aws cloudwatch delete-alarms --alarm-names ${ALARM_NAME}
出力
[cloudshell-user@ip-10-130-49-7 ~]$ aws cloudwatch delete-alarms --alarm-names ${ALARM_NAME}

ログ

コマンド
aws logs delete-log-group \
    --log-group-name ${LOG_ACCESS_NAME}

aws logs delete-log-group \
    --log-group-name ${LOG_ERROR_NAME}
出力
[cloudshell-user@ip-10-130-49-7 ~]$ aws logs delete-log-group \
>     --log-group-name ${LOG_ACCESS_NAME}
[cloudshell-user@ip-10-130-49-7 ~]$ 
[cloudshell-user@ip-10-130-49-7 ~]$ aws logs delete-log-group \
>     --log-group-name ${LOG_ERROR_NAME}

イベント

コマンド
aws events remove-targets \
  --rule ${EVENT_RULE_NAME}  --ids 1

aws events delete-rule \
  --name ${EVENT_RULE_NAME}
出力
[cloudshell-user@ip-10-130-49-7 ~]$ aws events remove-targets \
>   --rule ${EVENT_RULE_NAME}  --ids 1
{
    "FailedEntryCount": 0,
    "FailedEntries": []
}
[cloudshell-user@ip-10-130-49-7 ~]$ 
[cloudshell-user@ip-10-130-49-7 ~]$ aws events delete-rule \
>   --name ${EVENT_RULE_NAME}

SNS

指定のSidが含まれるステートメントを削除

コマンド
# 現在のSNSトピックのポリシーを取得
CURRENT_POLICY=$(
    aws sns get-topic-attributes \
        --topic-arn ${TOPIC_ARN} \
        --query "Attributes.Policy" \
        --output text
) \
&& echo ${CURRENT_POLICY}

# 削除したいSidを指定
SID_TO_DELETE=${EVENT_RULE_NAME} \
&& echo ${SID_TO_DELETE}

# 現在のポリシーをJSON形式に変換
CURRENT_POLICY_JSON=$(echo ${CURRENT_POLICY} | jq .) \
&& echo ${CURRENT_POLICY_JSON}

# 指定のSidが含まれるステートメントを削除
UPDATED_POLICY=$(
    echo ${CURRENT_POLICY_JSON} | jq 'del(.Statement[] | select(.Sid == "'${SID_TO_DELETE}'"))'
) \
&& echo ${UPDATED_POLICY}

# 更新されたポリシーを文字列に変換
UPDATED_POLICY_STR=$(echo ${UPDATED_POLICY} | jq -c .) \
&& echo ${UPDATED_POLICY_STR}

# 更新されたポリシーを設定
aws sns set-topic-attributes \
    --topic-arn ${TOPIC_ARN} \
    --attribute-name Policy \
    --attribute-value "${UPDATED_POLICY_STR}"
出力
[cloudshell-user@ip-10-130-49-7 ~]$ # 現在のSNSトピックのポリシーを取得
[cloudshell-user@ip-10-130-49-7 ~]$ CURRENT_POLICY=$(
>     aws sns get-topic-attributes \
>         --topic-arn ${TOPIC_ARN} \
>         --query "Attributes.Policy" \
>         --output text
> ) \
> && echo ${CURRENT_POLICY}
{"Version":"2008-10-17","Id":"__default_policy_ID","Statement":[{"Sid":"__default_statement_ID","Effect":"Allow","Principal":{"AWS":"*"},"Action":["SNS:GetTopicAttributes","SNS:SetTopicAttributes","SNS:AddPermission","SNS:RemovePermission","SNS:DeleteTopic","SNS:Subscribe","SNS:ListSubscriptionsByTopic","SNS:Publish"],"Resource":"arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic","Condition":{"StringEquals":{"AWS:SourceOwner":"999999999999"}}},{"Sid":"monitoring-1-event-rule","Effect":"Allow","Principal":{"Service":"events.amazonaws.com"},"Action":"sns:Publish","Resource":"arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic"}]}
[cloudshell-user@ip-10-130-49-7 ~]$ 
[cloudshell-user@ip-10-130-49-7 ~]$ # 削除したいSidを指定
[cloudshell-user@ip-10-130-49-7 ~]$ SID_TO_DELETE=${EVENT_RULE_NAME} \
> && echo ${SID_TO_DELETE}
monitoring-1-event-rule
[cloudshell-user@ip-10-130-49-7 ~]$ 
[cloudshell-user@ip-10-130-49-7 ~]$ # 現在のポリシーをJSON形式に変換
[cloudshell-user@ip-10-130-49-7 ~]$ CURRENT_POLICY_JSON=$(echo ${CURRENT_POLICY} | jq .) \
> && echo ${CURRENT_POLICY_JSON}
{ "Version": "2008-10-17", "Id": "__default_policy_ID", "Statement": [ { "Sid": "__default_statement_ID", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": [ "SNS:GetTopicAttributes", "SNS:SetTopicAttributes", "SNS:AddPermission", "SNS:RemovePermission", "SNS:DeleteTopic", "SNS:Subscribe", "SNS:ListSubscriptionsByTopic", "SNS:Publish" ], "Resource": "arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic", "Condition": { "StringEquals": { "AWS:SourceOwner": "999999999999" } } }, { "Sid": "monitoring-1-event-rule", "Effect": "Allow", "Principal": { "Service": "events.amazonaws.com" }, "Action": "sns:Publish", "Resource": "arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic" } ] }
[cloudshell-user@ip-10-130-49-7 ~]$ 
[cloudshell-user@ip-10-130-49-7 ~]$ # 指定のSidが含まれるステートメントを削除
[cloudshell-user@ip-10-130-49-7 ~]$ UPDATED_POLICY=$(
>     echo ${CURRENT_POLICY_JSON} | jq 'del(.Statement[] | select(.Sid == "'${SID_TO_DELETE}'"))'
> ) \
> && echo ${UPDATED_POLICY}
{ "Version": "2008-10-17", "Id": "__default_policy_ID", "Statement": [ { "Sid": "__default_statement_ID", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": [ "SNS:GetTopicAttributes", "SNS:SetTopicAttributes", "SNS:AddPermission", "SNS:RemovePermission", "SNS:DeleteTopic", "SNS:Subscribe", "SNS:ListSubscriptionsByTopic", "SNS:Publish" ], "Resource": "arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic", "Condition": { "StringEquals": { "AWS:SourceOwner": "999999999999" } } } ] }
[cloudshell-user@ip-10-130-49-7 ~]$ 
[cloudshell-user@ip-10-130-49-7 ~]$ # 更新されたポリシーを文字列に変換
[cloudshell-user@ip-10-130-49-7 ~]$ UPDATED_POLICY_STR=$(echo ${UPDATED_POLICY} | jq -c .) \
> && echo ${UPDATED_POLICY_STR}
{"Version":"2008-10-17","Id":"__default_policy_ID","Statement":[{"Sid":"__default_statement_ID","Effect":"Allow","Principal":{"AWS":"*"},"Action":["SNS:GetTopicAttributes","SNS:SetTopicAttributes","SNS:AddPermission","SNS:RemovePermission","SNS:DeleteTopic","SNS:Subscribe","SNS:ListSubscriptionsByTopic","SNS:Publish"],"Resource":"arn:aws:sns:ap-northeast-1:999999999999:monitoring-1-topic","Condition":{"StringEquals":{"AWS:SourceOwner":"999999999999"}}}]}
[cloudshell-user@ip-10-130-49-7 ~]$ 
[cloudshell-user@ip-10-130-49-7 ~]$ # 更新されたポリシーを設定
[cloudshell-user@ip-10-130-49-7 ~]$ aws sns set-topic-attributes \
>     --topic-arn ${TOPIC_ARN} \
>     --attribute-name Policy \
>     --attribute-value "${UPDATED_POLICY_STR}"

トピック削除

コマンド
aws sns delete-topic --topic-arn ${TOPIC_ARN} 
出力
[cloudshell-user@ip-10-130-49-7 ~]$ aws sns delete-topic --topic-arn ${TOPIC_ARN} 
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?