How to run commands remotely on ec2 instances

Active Directory : How to test if the user is present
March 26, 2018
How to see all the changes before creating/updating the AWS CloudFormation stack
April 3, 2018

How to run commands remotely on ec2 instances


AWS Systems Manager Run Command allows you to remotely and securely run set of commands on EC2 as well on-premise server.

  1. These instances are called as a managed instance.
  2. Run Command enables you to automate the common administrative jobs and perform ad hoc configuration at scale.
  3. You can use Run Command from the AWS console, the AWS CLI, AWS Tools for Windows PowerShell, or the AWS SDKs.
  4. Run Command is offered free, no cost to use it.

 Attach Instance IAM role:

The ec2 instance must have IAM role with policy AmazonSSMFullAccess.  This role enables the instance to communicate with the Systems Manager API.

Verify/install SSM Agent:

The EC2 instance must have SSM agent installed on it. The SSM Agent process the run command requests & configure the instance as per command. The agent is installed by default on Windows AMIs starting in November 2016 and later and Amazon Linux AMIs starting with 2017.09.

To install the agent on Linux, see Installing and Configuring SSM Agent on Linux Instances in the AWS Systems Manager User Guide.

To install the agent on Windows, see Installing and Configuring SSM Agent on Windows Instances in the AWS Systems Manager User Guide.

Sample tasks can be performed via the Run command:

install or bootstrap applications, build a deployment pipeline, capture log files when an instance is terminated from an Auto Scaling group, and join instances to an AD domain, enable log export to CloudWatch from ec2 instance

Example usage via AWS CLI:

Execute the following command to retrieve the services running on the instance. Replace Instance-ID with ec2 instance id.

aws ssm send-command --document-name "AWS-RunShellScript" --comment "listing services" --instance-ids "Instance-ID" --parameters commands="service --status-all" --region us-west-2 --output text

In above command the –document-name “AWS-RunShellScript” is used. This document is used to run the shell script command. Likewise, there are many such documents provided by AWS to use. We can go through SSM documents in next post.

On aws console, if you go to EC2 section and look at the left column, you will see the System Manager menus.

SSM Menus on aws console

AWS System manager menus

Below is a snapshot of Run command AWS console. Here you can see all the run command invocations on managed instances.

RUN command console

AWS Run command console