You can push any metric you wish to Amazon CloudWatch. You can use CLI commands or SDKs available in AWS. In this example I will be using Python to push a metric to CloudWatch. Before we proceed let’s make sure you have your AWS credentials in place. You should have AWS CLI tools installed on your machine. If not please refer to this to see how to install CLI tools on your device. You will also need to create a user in AWS. You can read how to create a user in AWS here.

Once the above two steps are done type aws configure in your terminal. You will be prompted for credentials. You can confirm your user credentials by entering the command aws sts get-caller-identity.

Once your have your terminal set up open a new file in your terminal and insert this code:

import boto3
import requests

r = requests.get('https://tutorials.releaseworksacademy.com/sitemap.xml')
number_of_tutorials = r.text.count('/learn/')
CloudWatch = boto3.client('cloudwatch')

response = CloudWatch.put_metric_data(
    MetricData = [
        {
            'MetricName': 'Number of Releaseworks Tutorials',
            'Unit': 'Count',
            'Value': number_of_tutorials
        },
    ],
    Namespace='Releaseworks_metrics'
)

print(response)

In this example I am using requests library in Python to scrape a webpage for data. I will get the number of tutorials available on our page. I then use boto3 to connect to AWS CloudWatch. I make a call to AWS using boto’s put_metric_data method. I define MetricName as the name of the metric I want to push. It could be something like CPU utilisation, number of logins etc. Next I define Unit, which is the unit you wish to store the metric in, and Value which is the actual value of the metric. Finally I define Namespace, which is the name I will look for when searching for this meteric in CloudWatch. I added print(response) to see whether we were successful in pushing the metric or not. Running python3 your_code_filename.py should return you something like this:

{'ResponseMetadata': {'RequestId': '7324131b-3124-481b-a1a4-fbc1ebde755c', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '7324131b-3124-481b-a1a4-fbc1ebde755c', 'content-type': 'text/xml', 'content-length': '212', 'date': 'Mon, 18 May 2020 09:24:14 GMT'}, 'RetryAttempts': 0}}

'HTTPStatusCode': 200 will mean that the call was successful and the metric has been pushed. Please bear:bear: in mind it takes about 5 minutes for custom metric to show up in AWS CloudWatch console.


Learn more on our Amazon CloudWatch Fundamentals online training course: https://www.releaseworksacademy.com/courses/amazon-CloudWatch-fundamentals