Aug 9, 2018
The objective is to collect data from a MongoDB service and insert it into a CloudWatch as a custom metric. It gives the capability to create alarms based on this information.
The requirements are:
The first step is to create a policy and a role that will permit the instance to put metric into CloudWatch. The following policy is enough to push our metric to CloudWatch.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1523876124974",
"Action": [
"cloudwatch:PutMetricData"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
Then use script bellow to monitor the MongoDB, the script will collect the service status, current connections, and available connections.
#!/bin/bash
EC2_INSTANCE_ID=$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id)
REGION=$(wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone | awk '{print substr($1, 1, length($1)-1)}')
#!/bin/bash
test -n "$EC2_INSTANCE_ID" || die 'cannot obtain instance-id'
test -n "$REGION" || die 'cannot obtain region'
mongo --eval "printjson(db.serverStatus())" > /dev/null 2>&1
SERVER_STATUS=$?
AWSCLI=$(which aws)
if [[ -z $AWSCLI ]]
then
echo "awscli not found"
exit 1
fi
if [[ $SERVER_STATUS -eq 0 ]]
then
aws cloudwatch put-metric-data --region=$REGION --namespace Services --dimensions MongoDB=$EC2_INSTANCE_ID --metric-name 'Status' --unit 'Count' --value='0'
CONN_CUR=$(mongo --eval "printjson(db.serverStatus().connections.current)" | tail -1)
CONN_AVAILABLE=$(mongo --eval "printjson(db.serverStatus().connections.available)" | tail -1)
aws cloudwatch put-metric-data --region=$REGION --namespace Services --dimensions MongoDB=$EC2_INSTANCE_ID --metric-name 'CurrentConn' --unit 'Count' --value=$CONN_CUR
aws cloudwatch put-metric-data --region=$REGION --namespace Services --dimensions MongoDB=$EC2_INSTANCE_ID --metric-name 'AvailableConn' --unit 'Count' --value=$CONN_AVAILABLE
else
aws cloudwatch put-metric-data --region=$REGION --namespace Services --dimensions MongoDB=$EC2_INSTANCE_ID --metric-name 'Status' --unit 'Count' --value='1'
fi
Now is possible to see the metrics on CloudWatch and use it to create alarms.