How to Create an EC2 Instance using Python Boto3

How to Create an Amazon EC2 Instance using Python Boto3

How to Create an EC2 Instance using Python Boto3

Dear Reader, I hope you are doing well. In this post, I will help you create an amazon EC2 instance using AWS SDK for Python, also known as Boto3.

I will be creating an amazon Linux 2 instance. However, the concept stays the same and you can create instances with other AMIs by changing the AMI Id as per your need.

EC2 Instance: An EC2 instance is nothing but a virtual server in AWS EC2 or Elastic Compute Cloud. You can use EC2 to host your application in the AWS cloud.

Boto3: Boto3 is AWS SDK for Python that makes it easy for you to create a python application that utilises AWS services like EC2.

In this create instance example post using boto3, you’ll also see how to start and stop an ec2 instance using python boto3.

Don’t want to miss any posts from us? join us on our Facebook group, and follow us on Facebook, Twitter, LinkedIn, and Instagram. You can also subscribe to our newsletter below to not miss any updates from us.

Prerequisite

How to Create an Amazon EC2 Instance using Python Boto3

In this section, we’ll create an EC2 instance using Boto3, check its status and finally will stop/terminate it.

Let’s start

Step 1: Create an EC2 Instance using Python Boto3

Open your IDE. Create a new project or folder and create a new file ec2-instance.py.

Let’s start adding code to it.

1. Import Boto3

Before you use boto3 to create an Ec2 instance, you need to import it.

import boto3

2. Connect with EC2

We are creating an instance or representation of EC2 service that provides us with various action, sub-resources and collection.

We will use create_instances() action of EC2 resource to create an EC2 Instance.

3. Create EC2 Instance using create_instances()

If you see the argument details of this action in the documentation, it supports a huge parameter list for various configurations. But if you look closely, you can find mandatory ones to create an instance.

The bare minimum to create an instance comes down to below-

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

instance = ec2.create_instances(
        ImageId='ami-0cca134ec43cf708f',
        MinCount=1,
        MaxCount=1
)

We will explain about these parameters in a minute.

For now, please note that there is a small issue in using above code. By for the parameters you don’t provide a value, boto3 uses default and it becomes problematic.

For instance, not all instance type is supported in all region. Since above code doesn’t specify Instance type param, by default m1.small is used which is not supported by my region(ap-south-1). And, due to this, you might end up with below error while trying to create the instance using above code.

botocore.exceptions.ClientError: An error occurred (Unsupported) when calling the RunInstances operation: The requested configuration
is currently not supported. Please check the documentation for supported configurations.

Therefore, specify the instance type explicitly and you should be good to go. So a simple working example to create an EC2 using boto3 and python looks like-

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

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

print(instance)

The response of ec2.create_instances() action is a list of EC2 instance resource.

And prints like-

Python Ec2

4. Most Used Parameter & Explanation

As you saw, we have seen the bare minimum parameter that is needed to create an instance. However, from usability perspective most of the times, we use some more parameters.

Here are some of the most used parameters and it’s explanation on when to use it.

  • ImageId(Mandatory): ID of the AMI you want to launch. AMI Id is different for different regions. So always check in the console for your region to find the AMI Id. I wanted to use amazon Linux 2 AMI so I selected it to see the AMI ID.
How to Create an Amazon EC2 Instance using Python Boto3 1
  • MinCount(Mandatory): Is required and specified minimum number of instance that you want to create
  • MaxCount(Mandatory): It is the maximum number of instances that you want to launch. I have specified 1 as I wanted just one instance.
  • InstanceType: By default, it is m1.small so specify your instance type explicitly to meet your need
  • KeyName: It is not mandatory however recommended to provide it if you want to connect to EC2 via SSH. You provide the keypair name to this field that you already have created.
  • SecurityGroupIds: The Id’s of the security group that you want to associate with your EC2.

Step 2: Verify Created EC2 Instance

Navigate to EC2 service in AWS Management Console and see the instance running status.

How to Create an Amazon EC2 Instance using Python Boto3 2

Alternatively, you can use describe_instances() of EC2 client. For that first you will have to create EC2 client.

import boto3
client = boto3.client('ec2');

response = client.describe_instances()
print(response)
      

Step 3: Stop the EC2 Instance using Python Boto 3

If you don’t need the instance anymore or you are doing this just for learning purpose, it’s always good to stop or terminate the instance. That way you won’t get billing shocks.

Related: Use AWS Budget to get Emails and Avoid Billing Shock

1. Stop the Instance using ec2.stop_instances()

Create an EC2 client and call ec2.stop_instances() to stop the instance.

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

response = ec2.stop_instances(
	    InstanceIds=[
                'i-023c7f0245890436e'
            ]
)

Alternatively if you don’t have any plans to use this instance, you can terminate it.

2. Terminate the Instance using ec2.terminate_instances()

Create an EC2 client and call ec2.terminate_instances() to terminate the instance

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

response = ec2.terminate_instances(
	    InstanceIds=[
                'i-023c7f0245890436e'
            ]
)

You can pass in all the instance id that you want to stop or terminate to above method.

Conclusion

In this tutorial, you leanrt to create an EC2 instance using Python Boto3. We learnt a bit about EC2 instance and AWS SDK or Python Boto3.

Then we created an EC2 instance using create_instance(), verified the created instance in console and we stopped the ec2 instance using Boto3.

I also specified how you can terminate your EC2 instance instead of stopping if you don’t need it anymore.

Were you able to create an ec2 instance using python boto3 using this tutorial? Let me know in the comment section.

Enjoyed the content?

Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox.

Don’t forget to motivate me by-

Suggested Read:

Leave a Reply

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