Run AWS Systems Manager Run Command from the AWS CLI

Central management node securely coordinating commands across multiple cloud server instances

What You’ll Learn

In this lesson, you will use AWS Systems Manager Run Command from the AWS CLI to execute administrative shell commands on managed EC2 instances without opening SSH connections.

  • Send a command to one or more EC2 instances.
  • Target instances by IDs or by an EC2 tag.
  • Capture the Run Command ID and inspect execution status.
  • Recognize common permission, targeting, and connectivity problems.
Ad

The Concept

AWS Systems Manager Run Command lets you execute commands remotely on managed instances. The SSM Agent running on each instance receives the command, executes it, and reports the result to Systems Manager.

This is useful for administrative tasks such as checking disk usage, restarting a service, collecting diagnostic information, or applying a controlled configuration change across a fleet. Because the communication uses Systems Manager, you do not need to expose SSH port 22 or distribute SSH keys to administrators.

The AWS CLI command for starting an operation is aws ssm send-command. You provide:

  • An SSM document, such as AWS-RunShellScript for Linux instances.
  • The target instances, using instance IDs or tag-based targeting.
  • The commands to execute.
  • Optional controls such as maximum concurrency and maximum allowed errors.

Run Command is asynchronous. The send-command operation normally returns a command ID before the commands have finished. Use that ID with commands such as list-command-invocations or get-command-invocation to inspect progress and results.

Before starting, verify that the AWS CLI is available and configured for the correct account and Region. You can use these Bash techniques to check AWS CLI command availability. You should also understand the usual AWS CLI command patterns, including options, queries, and output formats.

Basic Example

The following example runs hostname and uptime on two Linux EC2 instances. Replace the instance IDs and Region with values from your environment.

REGION="us-east-1"
INSTANCE_IDS=("i-0123456789abcdef0" "i-0fedcba9876543210")

COMMAND_ID=$(aws ssm send-command \
    --region "$REGION" \
    --document-name "AWS-RunShellScript" \
    --instance-ids "${INSTANCE_IDS[@]}" \
    --parameters 'commands=["hostname","uptime"]' \
    --comment "Collect basic host information" \
    --timeout-seconds 600 \
    --query "Command.CommandId" \
    --output text)

printf 'Run Command ID: %s\n' "$COMMAND_ID"

aws ssm list-command-invocations \
    --region "$REGION" \
    --command-id "$COMMAND_ID" \
    --details \
    --query 'CommandInvocations[].{Instance:InstanceId,Status:Status}' \
    --output table

Expected Output

The command ID is generated by AWS, so its exact value will vary. After the invocations finish, the status table should show one row for each targeted instance.

Run Command ID: 7f6c2f5e-1234-4567-89ab-0123456789ab

------------------------------
|      ListCommandInvocations |
+------------------+---------+
|     Instance     | Status  |
+------------------+---------+
|  i-0123456789abcdef0 | Success |
|  i-0fedcba9876543210 | Success |
+------------------+---------+

How the Code Works

The AWS CLI sends an asynchronous Systems Manager Run Command using instance IDs or EC2 tag targets and an SSM document. Systems Manager delivers the command through the SSM Agent on managed EC2 instances without SSH, then returns a command ID used to inspect per-instance status and results.
Run Command targets managed EC2 instances by ID or tag, executes through the SSM Agent without SSH, and uses the returned command ID to track each invocation.

REGION identifies the AWS Region where the managed instances are running. The INSTANCE_IDS Bash array stores multiple EC2 instance IDs, and "${INSTANCE_IDS[@]}" passes each ID to the AWS CLI.

AWS-RunShellScript is an AWS-provided Systems Manager document for running shell commands on Linux instances. The commands parameter is a list, so the example sends two commands to each instance.

The --query "Command.CommandId" option extracts only the ID from the send-command response. Storing this value in COMMAND_ID makes it possible to inspect the same operation afterward.

The --timeout-seconds 600 option sets the execution timeout for the command. It does not make the AWS CLI wait synchronously for completion. The second AWS CLI call uses list-command-invocations with --details to retrieve execution information for every targeted instance.

Run Command can execute on several instances at once. For larger fleets, use --max-concurrency to limit how many instances run the command simultaneously and --max-errors to stop or limit the operation after failures. These controls are important when a command changes system state.

Another Example

You can target instances by an EC2 tag instead of maintaining a list of instance IDs. This example checks disk usage on every managed instance tagged Role=web-server. It limits execution to 25 percent of the matching instances at a time and allows one error before the operation stops progressing.

REGION="us-east-1"

COMMAND_ID=$(aws ssm send-command \
    --region "$REGION" \
    --document-name "AWS-RunShellScript" \
    --targets "Key=tag:Role,Values=web-server" \
    --parameters 'commands=["df -h /","free -m"]' \
    --comment "Check storage and memory on web servers" \
    --max-concurrency "25%" \
    --max-errors "1" \
    --timeout-seconds 300 \
    --query "Command.CommandId" \
    --output text)

printf 'Fleet check started with command ID: %s\n' "$COMMAND_ID"

aws ssm list-command-invocations \
    --region "$REGION" \
    --command-id "$COMMAND_ID" \
    --details \
    --query 'CommandInvocations[].{Instance:InstanceId,Status:Status,Requested:CommandPlugins[0].ResponseCode}' \
    --output table

The tag target is evaluated when the command is sent. Confirm that the tag key and value match the instances you intend to manage. You can also send commands to targets using other supported target keys, but the instances must be managed by Systems Manager and must be in the selected Region.

Common Mistakes

  • The instance is not a managed node: The EC2 instance needs a running SSM Agent, network access to Systems Manager endpoints, and an IAM instance profile that grants the required Systems Manager permissions.
  • The caller lacks permission: The IAM identity running the AWS CLI needs permission to call actions such as ssm:SendCommand and ssm:ListCommandInvocations. The instance role and the caller’s role solve different permission requirements.
  • The Region is wrong: An instance ID is meaningful only in its Region. Use --region explicitly in scripts so they do not depend on the current AWS CLI profile default.
  • Assuming the command finished immediately: send-command returns an operation ID, not necessarily the final result. Inspect the invocation status before treating the operation as successful.
  • Using the wrong document: AWS-RunShellScript is for Linux and compatible systems. Windows instances generally require the AWS-RunPowerShellScript document and PowerShell commands instead.
  • Running a risky command across the whole fleet: Start with a small target set, use a restrictive concurrency value, and test administrative changes before expanding the target.

For commands that change services or files, inspect both the invocation status and the command’s response code. A command can be delivered successfully while the underlying shell command still exits with an error.

Try It Yourself

Choose one managed Linux instance and use Run Command to collect its kernel and operating system information. Send these commands:

  • uname -a
  • cat /etc/os-release

Capture the returned command ID, then use get-command-invocation with that ID and the instance ID to inspect the command output.

Challenge

Write a Bash script that performs a read-only health check on every instance with the tag Environment=staging.

Your script must:

  • Use AWS-RunShellScript.
  • Run systemctl is-system-running and df -h /.
  • Limit concurrency to 10 instances.
  • Allow no more than two errors.
  • Print the Run Command ID.
  • Display each target instance and its final status.

Solution

REGION="us-east-1"

COMMAND_ID=$(aws ssm send-command \
    --region "$REGION" \
    --document-name "AWS-RunShellScript" \
    --targets "Key=tag:Environment,Values=staging" \
    --parameters 'commands=["systemctl is-system-running","df -h /"]' \
    --comment "Run staging instance health checks" \
    --max-concurrency "10" \
    --max-errors "2" \
    --timeout-seconds 300 \
    --query "Command.CommandId" \
    --output text)

printf 'Run Command ID: %s\n' "$COMMAND_ID"

aws ssm list-command-invocations \
    --region "$REGION" \
    --command-id "$COMMAND_ID" \
    --details \
    --query 'CommandInvocations[].{Instance:InstanceId,Status:Status}' \
    --output table

The tag target selects only staging instances. The concurrency value is an absolute maximum of 10 simultaneous executions, while --max-errors "2" limits the number of permitted errors. The final query reports the status for each invocation.

For a single instance, use get-command-invocation to retrieve the command output. For a fleet, list-command-invocations --details is a practical way to review statuses together. This inspection-and-verification workflow is similar to other patterns for monitoring AWS CLI operations.

Key Takeaways

  • aws ssm send-command executes administrative commands without requiring SSH access.
  • AWS-RunShellScript runs shell commands on managed Linux instances.
  • Use instance IDs for precise targeting or tags for repeatable fleet targeting.
  • Run Command is asynchronous, so save the command ID and inspect invocation status.
  • Use concurrency and error limits to reduce risk when operating across multiple instances.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Ad
Ad
Ad