cloud

Automate (Un)Installation of AWS CloudWatch Agent in Systems Manager

- Updated November 16, 2020

AWS CloudWatch Agent comes installed on Amazon Linux 2 AMI and other AMIs. However, you may run into older AMIs or custom AMIs that don’t include the CloudWatch Agent.  If you need to install, uninstall, or reinstall CloudWatch Agent on a Linux EC2 instance follow these steps. I’m going to assume you have an EC2 instance running.  

Create an IAM Role

  1. Navigate to IAM and click Create Role.
  2. Select AWS Service for your trusted entity. 
  3. Choose EC2 for your use case.
  4. Search for and select CloudWatchAgentServerPolicy and AmazonSSMManagedInstanceCore for your policies. 
  5. Tag your role if you’d like.
  6. Give the role a name. DefaultEC2role would be descriptive. 
  7. Click Create Role.
  8. Navigate to EC2 and attach DefaultEC2role to your instance. 

Create an Association

  1. Navigate to the AWS Systems Manager service.
  2. Click on State Manager.
  3. Select the Create Association button. 
  4. Give your association a name like CloudWatchAgentInstaller
  5. Select AWS-ConfigureAWSPackage for your Document
  6. For your Parameters to
    • Install: 
      •  Action: Install; Installation Type: Uninstall and Reinstall; Name: AmazonCloudWatchAgent; Version: Default.
    • Uninstall:
      • Action: Uninstall; Installation Type: Uninstall and Reinstall; Name: AmazonCloudWatchAgent; Version: Default.
  7. You can choose all EC2 targets or manually, by tag, or by resource group.

  8. You can specify a CRON job to run the association to ensure the CloudWatch Agent is installed on newly created EC2 instances with targeted tags or resource groups. Or you can opt to run the association once.

Connect to EC2 with Session Manager

Now that we have AWS CloudWatch Agent installed, let’s check it out on our EC2 instance by using Session Manager. 

  1. Navigate to the AWS EC2 service.
  2. Select your EC2 instance.
  3. Select Connect
  4. Select Session Manager.
  5. Click the Connect button   
  6. In bash, run systemctl status amazon-cloudwatch-agent
  7. “amazon-cloudwatch-agent.service – Amazon CloudWatch Agent” should be active. 
  8. Click the Terminate button to close your session

In conclusion, you should now have a way to automatically (un)install AWS CloudWatch Agent on supported EC2 instances!