HiveBrain v1.2.0
Get Started
← Back to all entries
snippetModerate

How to run a script or a command on EC2 instance via AWS CLI?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
scriptec2instanceviacliawshowcommandrun

Problem

According to New EC2 Run Command news article, AWS CLI should support a new sub-command to execute scripts on remote EC2 instances.

However I've checked in aws ec2 help, but I can't find the relevant command.

I've installed aws via apt-get:

$ aws --version
aws-cli/1.14.32 Python/3.5.4 Linux/4.12.7-64 botocore/1.8.36


Which sub-command I should look for and what's the syntax to run, let say ipconfig in PowerShell on the remote EC2 instance?

Solution

To run ipconfig from the AWS Systems Manager Run Command:

$ aws ssm send-command --document-name "AWS-RunPowerShellScript" --instance-ids "" --parameters commands=ipconfig


Note: If you've got the error, consider specifying the right --region.

This assumes you have your AWS credentials and CLI configured properly. See Systems Manager Run Command Walkthrough Using the AWS CLI for more information.

Here is the practical shell command example of sending and getting the command output:

cmdid=$(aws ssm send-command --instance-ids "i-ch3ng3th1s" --document-name "AWS-RunPowerShellScript" --parameters commands=ipconfig --query "Command.CommandId" --output text)
aws ssm list-command-invocations --command-id "$cmdid" --details --query "CommandInvocations[*].CommandPlugins[*].Output[]" --output text

Code Snippets

$ aws ssm send-command --document-name "AWS-RunPowerShellScript" --instance-ids "<your instance id>" --parameters commands=ipconfig
cmdid=$(aws ssm send-command --instance-ids "i-ch3ng3th1s" --document-name "AWS-RunPowerShellScript" --parameters commands=ipconfig --query "Command.CommandId" --output text)
aws ssm list-command-invocations --command-id "$cmdid" --details --query "CommandInvocations[*].CommandPlugins[*].Output[]" --output text

Context

StackExchange DevOps Q#3264, answer score: 15

Revisions (0)

No revisions yet.