Launching AWS EC2 Instance using Python


The need for engineers skilled in cloud services like Amazon Web Services (AWS) has increased as more companies around the world move their operations to the cloud. One of the most well-known services offered by AWS, EC2 (Elastic Compute Cloud), offers scalable processing capability. Python is frequently used to manage AWS resources, including launching EC2 instances, due to its vast ecosystem and ease. This post will show you how to use Python to start an AWS EC2 instance. To strengthen our comprehension, we'll also go through a few real-world scenarios.

Understanding AWS EC2 and Python Boto3

Resizable computational capacity is offered by the AWS EC2 service in the cloud. It is intended to simplify web-scale cloud computing by reducing the amount of friction required for customers to acquire and configure capacity.

We use the Boto3 library, the Python Software Development Kit (SDK) for Amazon Web Services (AWS), to communicate with AWS services. It makes it possible for Python programmers to create applications that utilise services like Amazon S3, Amazon EC2, and others.

Setting Up Your AWS and Boto3

You must have an AWS account and have your AWS credentials set up on your computer before you can begin. Installing the AWS CLI (Command Line Interface) and executing aws configure will allow you to set the credentials.

The Boto3 module must be installed in your Python environment. Use pip to accomplish this −

pip install boto3

After installation, you can import Boto3 to communicate with AWS services in your Python programmes.

Launching AWS EC2 Instance: Step by Step Guide

Now, let's guide you through launching an EC2 instance using Python and Boto3.

  • Import Boto3 module

    Script written in Python should import the boto3 package.

import boto3
  • Create a Session

    Make a Boto3 session with your AWS login information.

session = boto3.Session(
   aws_access_key_id='YOUR_ACCESS_KEY',
   aws_secret_access_key='YOUR_SECRET_KEY',
   region_name='us-west-2'
)

'YOUR_ACCESS_KEY' and 'YOUR_SECRET_KEY' should be changed to reflect your AWS access key and secret access key, respectively. You can choose the region according to your preferences.

  • Create EC2 Resource Object

    Make an EC2 resource object utilising the session object.

ec2_resource = session.resource('ec2')
  • Launch EC2 Instance

    Launch the EC2 instance using the create_instances() method.

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

ImageId is the AMI ID, MinCount and MaxCount are the lowest and maximum number of instances to launch, and InstanceType is the type of instance in the create_instances() function.

Examples of Launching AWS EC2 Instances Using Python

Let's look at several EC2 instance launch examples.

  • Launching a Single EC2 Instance

    The Python code below starts one EC2 instance in the 'us-west-2' region.

import boto3

   session = boto3.Session(
      aws_access_key_id='YOUR_ACCESS_KEY',
      aws_secret_access_key='YOUR_SECRET_KEY',
      region_name='us-west-2'
   )

   ec2_resource = session.resource('ec2')

   instance = ec2_resource.create_instances(
      ImageId='ami-0c55b159cbfafe1f0',
      MinCount=1,
      MaxCount=1,
      InstanceType='t2.micro'
   )
   ```

Your AWS login credentials should be substituted for "YOUR_ACCESS_KEY" and "YOUR_SECRET_KEY." When you execute this script, it launches a 't2.micro' instance in the 'us-west-2' region using the supplied AMI ID.

  • Launching Multiple EC2 Instances

    The 'MinCount' and 'MaxCount' parameters can be easily changed if you need to launch more instances. Here is an illustration that starts three instances

import boto3

   session = boto3.Session(
      aws_access_key_id='YOUR_ACCESS_KEY',
      aws_secret_access_key='YOUR_SECRET_KEY',
      region_name='us-west-2'
   )

   ec2_resource = session.resource('ec2')

   instances = ec2_resource.create_instances(
      ImageId='ami-0c55b159cbfafe1f0',
      MinCount=1,
      MaxCount=3,
      InstanceType='t2.micro'
   )

Three 't2.micro' instances are started by this script in the 'us-west-2' region.

  •  Adding Tags to an EC2 Instance

    At launch time, you can also apply tags to your instances. This is how 

import boto3

   session = boto3.Session(
      aws_access_key_id='YOUR_ACCESS_KEY',
      aws_secret_access_key='YOUR_SECRET_KEY',
      region_name='us-west-2'
   )

   ec2_resource = session.resource('ec2')

   instances = ec2_resource.create_instances(
      ImageId='ami-0c55b159cbfafe1f0',
      MinCount=1,
      MaxCount=1,
      InstanceType='t2.micro',
      TagSpecifications=[
         {
            'ResourceType': 'instance',
            'Tags': [
               {
                  'Key': 'Name',
                  'Value': 'MyInstance'
               },
            ]
         },
      ]
   )

The 'MyInstance' name tag is given to the newly launched EC2 instance by this script.

Conclusion

As we've shown in this article, using Python to manage AWS resources is relatively simple thanks to Boto3. To avoid paying unforeseen charges, keep in mind to manage your instances effectively. After you've finished using an instance, always end it.

These are quite simple examples, but they may be developed to cover more intricate setups, such as adding storage, creating security groups, or employing various instance types in accordance with your requirements.

For managing and automating your AWS cloud resources, Python and Boto3 provide a potent toolkit. You can significantly streamline your interactions with AWS services with a little amount of Python knowledge, freeing you more time for application development.

Updated on: 17-Jul-2023

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements