16
votes

The below is the code which i am running from python to execute commands in aws ec2 instance

import boto3
ec2 = boto3.client('ssm',region_name='us-east-1',aws_access_key_id='xxxxxxxxxxxxxxx',aws_secret_access_key='xxxxxxxxx')
a = ec2.send_command(InstanceIds=ids, DocumentName='AWS-RunShellScript', Comment='abcdabcd', Parameters={"commands":["ifconfig"]})

But it is giving the below error

InvalidInstanceId: An error occurred (InvalidInstanceId) when calling the SendCommand operation: 
4
Is ids a valid list of EC2 instance IDs? The error message is saying that it isn't. - Mark B
@MarkB......id is valid....I have checked - Teja
Is ids a list or a single string? It expects it to be a list. - Mark B
@MarkB.... ids = ['i-0ce6exxxx2e3xxxx'].....ids is a list - Teja
And that instance is in the us-east-1 region? - Mark B

4 Answers

25
votes

The following scenarios can result in this error message:

  • Instance id is invalid (in the comments you have verified it isn't)
  • Instance is in a different region (in the comments you have verified it isn't)
  • Instance is not currently in the Running state
  • Instance does not have the AWS SSM agent installed and running.

You need to login to the AWS EC2/SSM console and make sure the instance(s) you are trying manage show up in the SYSTEMS MANAGER SHARED RESOURCES - Managed Instances list, and that they show a Ping status of Online. If not, you need to fix that before trying to send commands to the instance(s) in question.

11
votes

Make sure your instance has SSM setup. For Linux, you need to use Amazon Linux AMI or install manually.

Run:

aws ssm describe-instance-information --output text

to see the SSM agent version from your instances. So make sure your instance is on that list.

See also: SSM send command to EC2 instance Failed.

0
votes

I had the exact same error message and the problem was the version of boto3 in aws.

When I added boto3 as a lambda layer the lambda code ran perfectly.

0
votes

You must make sure you have the SSM Agent installed on your instance, which comes preinstalled on a few AMIs.

Also, what ended up working for me was going through the setup on the AWS Systems Manager service. The Quick Setup is pretty painless, just give it a couple minutes to run. After I ran through the Quick Setup and tested my command directly on Systems Manager, my Lambda function also successfully ran.