AWS Classroom Series – 25/Jun/2020

Boto3

  • Boto3 is the name of the Python SDK for AWS
  • Refer Here for documentaion
  • Refer Here for API Reference

Boto3 Setup on Local dev Instance

  1. Install Python3
  2. Install Boto3
pip install boto3

Preview 3. Create an IAM User with Programmatic access and configure the IAM user using AWS CLI

Boto3 Client and Resource

  • Boto3 calls AWS API’s from python code
  • Client: low-level service access. Used when the work is more programmatic.
import boto3
s3_my_client = boto3.client('s3')
  • Resource: Higher-level object oriented access
import boto3
s3_my_resource = boto3.resource('s3')

Sample Code to list s3 buckets

import boto3

s3_my_client = boto3.client('s3')
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#client

buckets_list = s3_my_client.list_buckets()
#print(buckets_list)

for bucket  in buckets_list['Buckets']:
    print(bucket['Name'])
import boto3
s3_my_resource = boto3.resource('s3')

for bucket in s3_my_resource.buckets.all():
    print(bucket.name)

Sample Code around EC2 instances

import boto3

ec2_resource = boto3.resource('ec2')
ec2_instances = ec2_resource.instances.all()
for instance in ec2_instances:
    print(instance.instance_id + "==> "+ instance.state['Name'])
    # Stop the machines if they are running
    if(instance.state['Name'] == 'running'):
        instance.stop()
    # Terminate the machines if they are stopped
    if(instance.state['Name'] == 'stopped'):
        instance.terminate()
    # Refer Here for creating Instance https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin