Launching and Terminating EC2 Instances using Boto3
Introduction
Amazon EC2 (Elastic Compute Cloud) is one of the core AWS services that allows users to rent virtual servers in the cloud. Boto3 is the AWS SDK for Python that allows you to automate the management of AWS resources. In this document, we will cover how to launch and terminate an EC2 instance using Boto3.
Prerequisites
Before you begin, ensure that you have the following:
An AWS Account with necessary permissions to manage EC2 resources.
AWS Access Key and Secret Key to authenticate Boto3 requests.
Python installed on your machine.
Boto3 installed in your Python environment.
Step-by-Step Guide
Step 1: Install Boto3
First, you need to install Boto3. You can easily install it using pip:
pip install boto3
Step 2: Configure AWS Credentials
You will need to configure your AWS credentials to use Boto3. You can either:
Set up your AWS credentials using the AWS CLI:
aws configure
This will prompt you for your Access Key, Secret Key, region, and output format.
Alternatively, you can directly store credentials in your
~/.aws/credentials
file:aws_access_key_id = YOUR_ACCESS_KEY aws_secret_access_key = YOUR_SECRET_KEY
Step 3: Launch an EC2 Instance
To launch an EC2 instance using Boto3, follow these steps:
Import Boto3 and Create an EC2 Client: You need to import Boto3 and create an EC2 client object that will interact with AWS services.
Define Instance Parameters: Specify details such as AMI ID, instance type, and key pair name.
Launch the EC2 Instance: Use the
run_instances
method to launch the EC2 instance.
Step 4: Terminate the EC2 Instance
To stop incurring costs or clean up resources, you can terminate the EC2 instance using the terminate_instances
method. You will need the Instance ID
to terminate it.
Sample Code
Launching an Instance
Here’s a Python script that demonstrates how to launch an EC2 instance using Boto3.
import boto3
# Create an EC2 client
ec2 = boto3.client('ec2', region_name='us-east-1') # Specify your AWS region
# Launch an EC2 instance
def launch_instance():
try:
response = ec2.run_instances(
ImageId='ami-0c55b159cbfafe1f0', # Example Amazon Linux 2 AMI
InstanceType='t2.micro', # Free tier eligible instance type
KeyName='your-key-pair', # Replace with your key pair
MinCount=1,
MaxCount=1,
TagSpecifications=[
{
'ResourceType': 'instance',
'Tags': [
{'Key': 'Name', 'Value': 'MyBoto3Instance'} # Optional tag for your instance
]
}
]
)
instance_id = response['Instances'][0]['InstanceId']
print(f'Instance launched, ID: {instance_id}')
return instance_id
except Exception as e:
print(f'Error launching instance: {e}')
if __name__ == "__main__":
instance_id = launch_instance()
Explanation:
ImageId
: The Amazon Machine Image (AMI) to use for the instance.InstanceType
: Specifies the type of instance (e.g.,t2.micro
).KeyName
: Specifies the key pair for SSH access.TagSpecifications
: Optional, used to apply tags to the instance.
Terminating an Instance
Here’s a Python script to terminate the EC2 instance:
import boto3
# Create an EC2 client
ec2 = boto3.client('ec2', region_name='us-east-1') # Specify your AWS region
# Terminate an EC2 instance
def terminate_instance(instance_id):
try:
response = ec2.terminate_instances(InstanceIds=[instance_id])
print(f'Terminating instance {instance_id}. Current state: {response["TerminatingInstances"][0]["CurrentState"]["Name"]}')
except Exception as e:
print(f'Error terminating instance: {e}')
if __name__ == "__main__":
instance_id = 'i-1234567890abcdef0' # Replace with your instance ID
terminate_instance(instance_id)
Explanation:
terminate_instances()
: This method terminates the instance based on the provided instance ID.
Conclusion
With this documentation, you’ve learned how to automate the launching and termination of EC2 instances using Boto3. This can help you easily manage your AWS infrastructure programmatically.
Key Takeaways:
Boto3 simplifies interaction with AWS services, including EC2.
You can automate the process of launching and terminating EC2 instances by integrating Boto3 into your workflows.
Always ensure proper cleanup of resources to avoid unnecessary charges on AWS.
For more advanced configurations, you can extend these scripts to include security groups, IAM roles, or specify more instance parameters.