EC2 [RAM, Disk Metric]How To Set Up Custom Metrics With CloudWatch

Adnan Sabanovic
2 min readMar 3, 2021

If you had your EC2 instance crash once or twice due to memory issues, then you probably tried to find an existing CloudWatch metric to set up alarms. I am guessing you didn’t find any.

That’s because CloudWatch doesn’t offer these from the shelf.

What you need to do is to install an Amazon CloudWatch Agent on your particular instance so it can collect data around your server.

First, you need to have an IAM role with a CloudWatchAgentServerPolicy. If you don’t know how to attach a role with policies to an EC2, go and check another post of mine where I explained that. Check here.

(Here you would edit your existing role that’s already attached to the instance, and just add the new policy to it)

SSH to your instance

And then run the following commands:

wget https://s3.amazonaws.com/amazoncloudwatch-agent/debian/amd64/latest/amazon-cloudwatch-agent.debsudo dpkg -i -E ./amazon-cloudwatch-agent.debsudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard

When following the wizard, you can put anything you want. You can find more explanations on those parameters here. Because later on, we will be able to edit that manually.

After you are done with the wizard (or you could not do that and go straight to create this file /opt/aws/amazon-cloudwatch-agent/bin/config.json

In that file you can open with sudo vim and paste the following:

{
"agent": {
"metrics_collection_interval": 60,
"run_as_user": "cwagent"
},
"metrics": {
"append_dimensions": {
"AutoScalingGroupName": "${aws:AutoScalingGroupName}",
"ImageId": "${aws:ImageId}",
"InstanceId": "${aws:InstanceId}",
"InstanceType": "${aws:InstanceType}"
},
"metrics_collected": {
"disk": {
"measurement": [
"used_percent"
],
"metrics_collection_interval": 60,
"resources": [
"*"
]
},
"mem": {
"measurement": [
"mem_used_percent"
],
"metrics_collection_interval": 60
}
}
}
}

Now save that file and move to start the agent.

You want to start this:

sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json

Later on, if you feel you need to change that config file, go stop the service, change the file and re-start the agent service. You can start and stop like this:

sudo service amazon-cloudwatch-agent stop
sudo service amazon-cloudwatch-agent start

Now that’s it. Go to your CloudWatch and you will see this:

Now you can do as usual, open it up, find your metric, set alarms etc.

Good luck!

--

--

Adnan Sabanovic

Just a tech guy involved in mastering life using mental and physical discipline. Journaling about productivity, personal development and overall growth. #Life