Create EC2 instance, start instance and run Linux command using Boto3

Question:

I am trying to create an AWS EC2 instance, start it, execute a simple Linux command and print the output. However, I keep getting:

botocore.errorfactory.InvalidInstanceId: An error occurred
(InvalidInstanceId) when calling the SendCommand operation: Instances
[[the_instance_id]] not in a valid state for account <some_account>

At the moment I use this boto3 script to create the instance:

import boto3
ec2 = boto3.resource('ec2')

instance = ec2.create_instances(
        ImageId='ami-0b828c1c5ac3f13ee',
        MinCount=1,
        MaxCount=1,
        InstanceType='t2.micro'
)

print(instance)

In the AWS Console the ‘status check’ says ‘2/2 checks passed’. I then copy-paste the instance-id in to the below script to execute a Linux echo command:

import boto3
commands = [' echo "hello world"']
ssm_client = boto3.client('ssm')

output = ssm_client.send_command(
InstanceIds=[<the_instance_id>],
DocumentName='AWS-RunShellScript',
Parameters={
    'commands': commands
    }
)

print(output)

However, I get:

botocore.errorfactory.InvalidInstanceId: An error occurred (InvalidInstanceId) when calling the SendCommand operation: Instances [[<the instance id>]] not in a valid state for account <some account>
Asked By: rare77

||

Answers:

Before you send this command, you need to check few things.

First, the AWS SSM (Systems Manager) agent needs to be running on the instance. Without it, you won’t be able to send commands through SSM. Fortunately, AWS Linux distro has it installed by default, so choose this AMI to keep things easy. But if you want to use Ubuntu or other stuff, you need to start AWS SSM Agent first and make sure it’s always running.

The second thing is instance permission. You need to add to the Instance role policy called AmazonSSMManagedEC2InstanceDefaultPolicy, or other applicable. Here is a full list that describes your potential use cases: https://docs.aws.amazon.com/systems-manager/latest/userguide/security-iam-awsmanpol.html

Then you should be able to easily run SSM commands and connect through AWS Web console terminal 🙂

Answered By: michail_w