Tech Chorus

Installing AWS CloudWatchAgent On EC2 Instance Via Ansible

written by Sudheer Satyanarayana on 2019-03-26

Install the Ansible role gavika.aws_cloudwatchagent via Galaxy.

ansible-galaxy install gavika.aws_cloudwatchagent

Create The Playbook File - cw-play.yml :

---
- hosts: all
  become: true
  vars:
  roles:
    - role: gavika.aws_cloudwatchagent

Prepare the AWS CloudWatch Agent configuration - aws-cw-config.json:

{
    "metrics": {
        "namespace": "gavika",
        "metrics_collected": {
            "cpu": {
                "measurement": [
                    "cpu_usage_idle",
                    "cpu_usage_iowait",
                    "cpu_usage_user",
                    "cpu_usage_system"
                ],
                "metrics_collection_interval": 360,
                "resources": [
                    "*"
                ],
                "totalcpu": false
            },
            "disk": {
                "measurement": [
                    "used_percent",
                    "inodes_free"
                ],
                "metrics_collection_interval": 360,
                "resources": [
                    "*"
                ]
            },
            "diskio": {
                "measurement": [
                    "io_time"
                ],
                "metrics_collection_interval": 360,
                "resources": [
                    "*"
                ]
            },
            "mem": {
                "measurement": [
                    "mem_used_percent"
                ],
                "metrics_collection_interval": 360
            },
            "swap": {
                "measurement": [
                    "swap_used_percent"
                ],
                "metrics_collection_interval": 360
            }
        }
    }
}

In this example, I am using the namespace, gavika. Feel free to change it. We collect the cpu, disk, diskio, mem and swap metrics. The agent will send these metrics once in 360 seconds.

Run The Playbook (CentOS):

ansible-playbook -i centos@myserver.example.com, cw-play.yml

The target machine is a CentOS server. Hence you see centos username. I am passing the server name inline. In a production system, you might have a well-defined inventory file. Change the command to suit your needs.

Run The Playbook (Ubuntu)

ansible-playbook -i ubuntu@myserver.example.com, cw-play.yml -e ansible_python_interpreter=/usr/bin/python3 -vvv

The Ubuntu server has Python3 by default and Ansible expects Python2 by default. Therefore, I pass the ansible_python_interpreter extra variable from the command line.

After the playbook executes successfully, you should see the metrics in AWS CloudWatch under the namespace specified.