Python Boto3 Task - Vaibhav Ingle
First Installation of the Pycharm
Just Go to : https://www.jetbrains.com/pycharm/download/?section=windows
And Download Pycharm Community Edition
You Will See Below Page After Download Started
After Download Just Install the Downloaded PyCharm file
Now Installation Get Completed so just Open the Pycharm .
Go to File Tab → Create New Project
Create New Project With Name PythonBoto3
Now Go to Setting
Now Go to Your Project → Click on Python Interpreter
Now Click on + Search on Boto3 and Click Install Package
Now Go to AWS Boto3 Documentation :
https://boto3.amazonaws.com/v1/documentation/api/latest/index.html
Using Python Boto3 Documentation We Can Learn AWS Boto3
So Lets Start With Python Boto3.
Now Open the Terminal
Give Command aws configure
And Give Your Credentials
Again To check Given Credentials Give Command – aws configure list
EC2 Creation , Deletion using The Python Boto3.
Just Go through Documentation
Step-1 Import Python Boto3 in Our Code File
import boto3
Explanation:
import boto3: This imports the Boto3 library, which is used to interact with various AWS
services, including EC2 (Elastic Compute Cloud).
Step-2 Create client
client = boto3.client('ec2')
Explanation:
client = boto3.client('ec2'): This line creates a client object that allows you to interact with
the EC2 service in AWS. A client in Boto3 is a low-level interface to AWS services, meaning
you can make API calls directly to EC2.
Step-3 Write response = client.run_instances() method
response = client.run_instances() method in the boto3 library is used to launch one or more
new Amazon EC2 instances. When you call this function, AWS will start the requested
instances, and it will return a response object that contains details about the launched
instances.
Step-4 Give Correct Parameters for
Parameters inside run_instances():
• ImageId='ami-050cd642fd83388e4': This specifies the Amazon Machine Image (AMI)
to use for the instance.
• InstanceType='t2.micro': This defines the size and capacity of the instance
• KeyName='ProjectV': This is the name of the SSH key pair used to securely connect to
the instance.
• MaxCount=1 and MinCount=1: These define the number of instances to launch. Here,
it's set to 1 instance.
import boto3 #used to Import Boto3 in code
client = boto3.client('ec2') # Create the EC2 client
response = client.run_instances(
ImageId='ami-050cd642fd83388e4',
InstanceType='t2.micro',
KeyName='ProjectV',
MaxCount=1,
MinCount=1,
)
Write the Python Boto3 code for Ec2 Creation
Now Lets Run it & see Code Runned Successfully .
Now Go to AWS EC2 console & check The Instances you have Given while
Configuration
Instance Using Python Boto3 is Created Successfully.
Now Lets Practice Again for Stop the Same Instance .
Step-1 Import the Boto3 using – import boto3
Step-2 Create EC2 Client: client = boto3.client('ec2')
Step-3 Specify Instance ID: instance_id=” Our Instance Id ” (just Creating Variable and
Assigning it Our Instance Id
Step-4 Stop the Instance: Use response = client.stop_instances() method with the
InstanceIds=[instance_id] as parameter
Write the Code And Run it
Code Runs Successfully so , Now Go to Same Instance and check the State It is
Stopped or Not.
Now Again Lets Practice Terminate Process on Same Instance
Same Code For Terminate Process just change Method and Replace it with
client.terminate_instances()
Step-1 Import the Boto3 using – import boto3
Step-2 Create EC2 Client: client = boto3.client('ec2')
Step-3 Specify Instance ID: instance_id=” Our Instance Id ” (just Creating Variable and
Assigning it Our Instance Id
Step-4 Stop the Instance: Use response = client.stop_instances() method with the
InstanceIds=[instance_id] as parameter
Code Runs Successfully so , Now Go to Same Instance and check the State It Is Terminated
or Not
Now Lets Do the Same Things Created , Stop and Delete Instance Using Boto3 on EC2
So First Create One Server For Our Use So We Already Written have a Script to Create EC2
in Pycharm so just Run it
Instance is Created After the code Runned Successfully. I give the name to Instance for
Identity - Pycharm
Now Connect to this Instance using EC2 connect
Connected to Instance Successfully.
To Create EC2 Instance :
1) Create File Name Create.py using vi command and Paste the Code & Save
import boto3 #used to Import Boto3 in code
client = boto3.client('ec2') # Create the EC2 client
response = client.run_instances(
ImageId='ami-050cd642fd83388e4',
InstanceType='t2.micro',
KeyName='ProjectV',
MaxCount=1,
MinCount=1,
)
Copy the Code And Paste in Create.py File but Check Key Pair is Present or not.
Now We Need Python to run this File so Install Python Using Command :
sudo yum install python-pip -y
Now Run the Create.py file using command : python3 Create.py
Now It will show Error Because we had not installed boto3 Dependencies
So Download Python Boto3 using command: sudo pip3 install boto3
Now Again Run the Create.py file
Again it is showing Error : Region not Specifyed and more
So open Create.py file using vi and give Region , save file and run file
But Again It Will Give Error : raise NoCredentialsError()
botocore.exceptions.NoCredentialsError: Unable to locate credentials which means
that the AWS SDK for Python (Boto3) is unable to find the AWS credentials needed to
authenticate your requests. So Just Ensure that your IAM user has the necessary
permissions for the actions you want to perform with Boto3.
So Now Lets , Create the IAM Role
Give Name to Role
Role Created Successfully .
Now just Go to Instance → go to Actions → now Security → and Just Modify the Role
Now just Select Created Role & Update the role
Now Again Try to Run Create.py file
See Now file Run Successfully so Check the Instance Page
Instance is Created (initializing)
Now Again to stop this Instance using boto3 , use same code as we wrote in Pycharm just
change instance id
Create File using vi stop.py → Copy & Paste Code From Pycharm → Update Instance_id
and Also Add Region where instance is Present → Save the file → run the stop.py file
Now Run the Stop.py file
Now Check the Instance , See it is Stopped
Now Again Same Process For the Termination of Instance
Create File using vi delete.py → Copy & Paste Code From Pycharm → Update Instance_id
and Also Add Region where instance is Present → Save the file → run the delete.py file
Now Run the delete.py file
Now check the EC2 Instance console , see the instance Is Terminated
S3 Bucket Creation using Boto3
Now Lets Create the S3 Bucket using Python Boto3
Now Lets Write Code for the Creation of S3 Bucket in us-east-2 Region
1. import boto3
Explanation: This imports the Boto3 library, which allows you to interact with AWS services like S3,
EC2, and others using Python.
2. s3_client = boto3.client('s3')
Explanation: This creates an S3 client object, allowing you to interact with Amazon S3 (Simple
Storage Service). The 's3' argument tells Boto3 that you're specifically working with the S3 service.
3. bucket_name = "your-unique-bucket-name"
Explanation: This creates a variable bucket_name and assigns it a string value that represents the
name of your S3 bucket. This name must be unique across all AWS accounts.
4. response = s3_client.create_bucket( Bucket='bucket_name',
CreateBucketConfiguration={'LocationConstraint': 'us-west-2'} )
Explanation: This creates an S3 bucket with the name specified in the bucket_name variable. The
CreateBucketConfiguration parameter defines the region where the bucket will be created, in this
case, 'us-west-2'.
import boto3 #importing Boto3
s3_client = boto3.client('s3') # Created Client for S3
bucket_name = "aws-s3-v" #Creating Variable to store Bucket Name
response = s3_client.create_bucket(
Bucket='bucket_name',
CreateBucketConfiguration={'LocationConstraint': 'us-west-2'} # Specifying our
region
)
Now Code Has been Written for S3 Bucket Creation , Now run it and check the S3 console
Code Successfully Runned
Now check the Amazon S3 bucket console , Bucket is Created Succcessfully.
Lets Create IAM Role For S3 Bucket
Creation of Lambda Function
Now Lets Create Lambda Function by simply Giving Name and Selecting
Platform (Language-Platform) & Using Existing IAM Role for Lambda
Now Select IAM role & Create
Lambda Function Created Succesfully
Write Code to Create Instance Inside Lambda Function
Now First Lets Simply Try to run the function its Working or not
Simply first Deploy code
Now run the code but it will ask for event so Create One Test Event
Now Run the Code But It will show some time Error so
Go to Configuration → Go to General Configuration → edit Time Min 1 & Max
15 Minutes (give in this Range only ) → Save
Now Again Run the Code
Code Successfully Run, so check console Ec2 instance is Created or not
Our Ec2 Instance is Successfully Created
Now Lets Add Trigger and Destination
Click on Add Trigger and Select S3 and Choose the Bucket which we have Already Created
See Now Trigger is Added
Now Lets Add the Destination
We Use SNS ( simple Notification Service ) So Lets Create SNS Topic First
Go to SNS → Create Topic
Now SNS Created So Create Subscription
Subscription Created Successfully.
Now Go to Gmail And Confirm the Subscription
When we will Click on Link Subscription it will be done
Now Go to Lambda Function Again and Click on Add Destination
Choose SNS and select Our SNS Topic We Created
See Done , Destination Added Successfully
Now Run the Lambda Function Again And See the Result for Destination Working or Not
Code Run Successfully
Instance Created Successfully
Now Lets Go To Our S3 Bucket Which is Working as Trigger and Add Something to Bucket to Create Trigger
Adding File
File Added Successfully
Now Go to AWS Console and Check Instance is Creating or not
See the New Instance is Initializing
Now Check the Mail box Destination is Working or not
Now Lets Create One More Lambda Function To Delete the Instance or Terminate the Existing Instance
Write the Code for Terminating the Instance and add Existing Instance Id Also & Deploy The Code
Now Again Go to S3-Lamda Function and Add One More Destination
Select Destination type – Lambda Function & Choose lambda-terminateEC2 which we have Created just
Now See Lambda function is Added as Destination
Now Again Delete or Add file in S3 to generate Trigger and check the Working
See I am Adding the Object or file into S3 bucket
Our Tigger and Destination Worked Successfully
One Instance Is Creating and One Is Deleting