Let's break down the code step by step to understand how to use boto3
to create an S3 bucket and describe EC2 instances.
Step 1: Import the boto3
Library
import boto3
In this step, we import the boto3
library, which is the AWS SDK for Python. It provides functions and classes to interact with various AWS services.
Step 2: Create an S3 Bucket
def create_s3_bucket(bucket_name):
s3 = boto3.client('s3')
response = s3.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={'LocationConstraint': 'us-east-1'}
)
return response
Here, we define a function called create_s3_bucket
that takes a parameter bucket_name
. Inside the function:
We create an S3 client using
boto3.client('s3')
.We call the
create_bucket
method on the S3 client to create a new S3 bucket. We provide the desired bucket name using theBucket
parameter and specify the region using theCreateBucketConfiguration
parameter. You can change'us-east-1'
to your desired region.The function returns the response from the
create_bucket
operation.
Step 3: Describe EC2 Instances
def describe_ec2_instances():
ec2 = boto3.client('ec2')
response = ec2.describe_instances()
return response
In this step, we define a function called describe_ec2_instances
. Inside the function:
We create an EC2 client using
boto3.client('ec2')
.We call the
describe_instances
method on the EC2 client to retrieve information about EC2 instances.The function returns the response containing information about the instances.
Step 4: Main Execution
bucket_name = 'your_bucket_name'
create_s3_bucket(bucket_name)
print(f"S3 bucket '{bucket_name}' created.")
ec2_instances = describe_ec2_instances()
print("EC2 Instances:")
for reservation in ec2_instances['Reservations']:
for instance in reservation['Instances']:
print(f"Instance ID: {instance['InstanceId']}")
print(f"Instance Type: {instance['InstanceType']}")
print(f"State: {instance['State']['Name']}")
print("------")
In the main part of the script:
We set the
bucket_name
variable to the desired name for the S3 bucket.We call the
create_s3_bucket
function with the specifiedbucket_name
to create the S3 bucket.We print a message indicating that the S3 bucket has been created.
We call the
describe_ec2_instances
function to retrieve information about EC2 instances.We iterate through the response to print details such as instance ID, instance type, and instance state for each EC2 instance.
Overall, this script demonstrates how to create an S3 bucket and describe EC2 instances using the boto3
library in Python. You'll need to replace 'your_bucket_name'
with your desired S3 bucket name and ensure you have the necessary AWS credentials configured.