Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run shell script on multiple EC2 instances using AWS CLI?

I'm trying to do a simple AWS CLI command that can run a shell command to multiple instances.

I know first I need to get the list of instances ids:

aws ec2 describe-instances --filter "Name=tag:Group,Values=Development" --query 'Reservations[].Instances[].[InstanceId]' --output text

I then will have to assign them to an array. Then loop through each instance id and send the command.

Do we have an option for aws to send a shell command to an instance with a specific id?

Something like this:

aws ssm send-command --instance-ids "i-xxxxxxxxxxxxxxxx" --document-name "shellscript"

I keep getting this error:

An error occurred (InvalidInstanceId) when calling the SendCommand operation:

I've made sure that the SSM agent is running on that specific instance and made sure everything is correct according to these docs pages.

like image 544
Samuel Rodriguez Avatar asked Jan 28 '26 04:01

Samuel Rodriguez


1 Answers

You can use ssm send-command.

A sample command to see ip address of instance:

aws ssm send-command --instance-ids "your id's" --document-name "AWS-RunShellScript" --comment "IP config" --parameters "commands=ifconfig" --output text

Modify command as per your needs.


In case you've got the error, this can happen when you don't have SSM setup on the instance you're trying to access. For a list of instances where you can run SSM commands, run:

aws ssm describe-instance-information --output text

See: InvalidInstanceId: An error occurred (InvalidInstanceId) when calling the SendCommand operation.

like image 198
Kush Vyas Avatar answered Jan 30 '26 11:01

Kush Vyas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!