1730696889721aws
1730696889721aws
DevOps Shack
Creating & Managing AWS Resources With
. Python.
What is AWS SDK?
The AWS SDK (Software Development Kit) is a collection of tools that allows developers to
interact programmatically with AWS services. It provides a set of APIs that enable you to
create, configure, and manage AWS services such as EC2, S3, Lambda, and more. The SDK is
available in multiple programming languages, including Python, Java, JavaScript, C#, and
Ruby, making it versatile and accessible for various development environments.
4. Security and Authentication: Integrated with AWS Identity and Access Management
(IAM) for secure API requests.
5. Waiters: Simplifies waiting for resource states (e.g., waiting for an EC2 instance to
reach the 'running' state).
How Boto3 Works
Boto3 provides two levels of APIs:
1. Resource API: Offers an abstraction layer over the raw AWS service APIs, making it
easier to work with AWS services. Resources represent an AWS service's objects and
their attributes.
o Example: ec2.Instance('i-1234567890abcdef0') to represent an EC2 instance.
2. Client API: Provides direct access to the AWS service APIs, allowing for more granular
control and lower-level interactions.
o Example: client.describe_instances(InstanceIds=['i-1234567890abcdef0']) to
describe an EC2 instance.
4. Run the Script: python create_ec2.py Script To Create The Resource import
boto3
# Initialize a session using Amazon EC2 ec2 =
boto3.resource('ec2') client = boto3.client('ec2')
# Create a VPC
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16') vpc.wait_until_available() print(f'Created VPC:
{vpc.id}')
# Enable DNS support
vpc.modify_attribute(EnableDnsSupport={'Value': True})
vpc.modify_attribute(EnableDnsHostnames={'Value': True}) #
Create an Internet Gateway and attach it to the VPC
internet_gateway = ec2.create_internet_gateway()
vpc.attach_internet_gateway(InternetGatewayId=internet_gateway.id) print(f'Created
Internet Gateway: {internet_gateway.id}')
# Create a public subnet
public_subnet = ec2.create_subnet(CidrBlock='10.0.1.0/24', VpcId=vpc.id,
AvailabilityZone='ap-south-1a') print(f'Created Public Subnet: {public_subnet.id}')
# Create a route table and a public route
route_table = vpc.create_route_table() route = route_table.create_route(
DestinationCidrBlock='0.0.0.0/0', GatewayId=internet_gateway.id ) print(f'Created Route
Table: {route_table.id}')
# Associate the route table with the subnet
route_table.associate_with_subnet(SubnetId=public_subnet.id) print(f'Associated Route
Table with Subnet: {public_subnet.id}')
# Create a security group
security_group = ec2.create_security_group( GroupName='my-security-group',
Description='My security group', VpcId=vpc.id ) security_group.authorize_ingress(
IpPermissions=[ {'IpProtocol': 'tcp', 'FromPort': 22, 'ToPort': 22, 'IpRanges': [{'CidrIp':
'0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 80, 'ToPort': 80, 'IpRanges': [{'CidrIp':
'0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 443, 'ToPort': 443, 'IpRanges': [{'CidrIp':
'0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 3000, 'ToPort': 10000, 'IpRanges': [{'CidrIp':
'0.0.0.0/0'}]}, ] ) print(f'Created Security Group: {security_group.id}')
# Function to create instances
def create_instances(instance_count): instances = ec2.create_instances(
ImageId='ami0ad21ae1d0696ad58', # Replace with your desired AMI ID
MinCount=instance_count, MaxCount=instance_count, InstanceType='t2.medium', # Choose
your instance type KeyName='DevOps', # Replace with your key pair name
NetworkInterfaces=[{ 'SubnetId':
public_subnet.id, 'DeviceIndex': 0, 'AssociatePublicIpAddress': True, 'Groups':
[security_group.group_id] }], TagSpecifications=[ { 'ResourceType': 'instance', 'Tags': [{'Key':
'Name', 'Value': f'Server {i+1}'} for i in range(instance_count)] } ], Placement={
'AvailabilityZone': 'ap-south-1a' } ) return instances
# Number of instances to create num_instances = 1 # Create the instances instances =
create_instances(num_instances) print(f'Created {num_instances} EC2 instances')
Explaination
The provided script is a comprehensive example of how to automate the creation of AWS
infrastructure using Boto3, the AWS SDK for Python. Here's a step-by-step explanation of
what each part of the script does:
2. Delete any custom routes in the route table before deleting the route table itself.
Here's the updated script to handle these dependencies:
import boto3
4. Detach and Delete the Internet Gateway: print(f'Detaching and deleting Internet
Gateway: {internet_gateway_id}') vpc = ec2.Vpc(vpc_id)
vpc.detach_internet_gateway(InternetGatewayId=internet_gateway_id)
internet_gateway = ec2.InternetGateway(internet_gateway_id)
internet_gateway.delete() print(f'Deleted Internet
Gateway: {internet_gateway_id}') This detaches the internet
gateway from the VPC and then deletes it.
5. Disassociate the Route Table from the Subnet: print(f'Disassociating Route Table
from Subnet: {subnet_id}') route_table = ec2.RouteTable(route_table_id)
route in route_table.routes:
if route.destination_cidr_block != 'local': # Skip the default local route
client.delete_route(RouteTableId=route_table_id,
DestinationCidrBlock=route.destination_cidr_block)
print(f'Deleted route: {route.destination_cidr_block}')
This deletes any custom routes in the route table, except for the default local route.