Boto3
- This is AWS SDK for python
- To install this
pip install boto3 - Documentation of boto3 Refer Here
- Sample python code to list all the s3 buckets
import boto3
def print_s3_buckets():
"""This method will print all the s3 buckets
"""
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
print(bucket.name)
if __name__ == '__main__':
print_s3_buckets()
-
Now lets try to create an lambda function which does the samething.
- Created a lamdba function with code
import json import boto3 def lambda_handler(event, context): s3_buckets = list_s3_buckets() response_dict = dict() response_dict['buckets'] = s3_buckets response_dict['count'] = len(s3_buckets) return { 'statusCode': 200, 'body': json.dumps(response_dict) } def list_s3_buckets(): """This method will print all the s3 buckets """ s3 = boto3.resource('s3') s3_list = [] for bucket in s3.buckets.all(): s3_list.append(bucket.name) return s3_list- When i executed this lambda function using test method i got the following response
-
Exercise: Lets create two ec2 instances
- instance-1: Tag: Name: web1
- instance-2: Tag: Name: web2
-
Code in python
import boto3
def get_ec2_instance_id(key='Name', value='Web1'):
ec2 = boto3.client('ec2')
response = ec2.describe_instances(Filters = [
{
'Name': f'tag:{key}',
'Values': [
value,
]
}])
#print(response)
instance_id = response['Reservations'][0]['Instances'][0]['InstanceId']
return instance_id
def stop_ec2(instance_id):
ec2 = boto3.client('ec2')
try:
ec2.stop_instances(InstanceIds=[instance_id])
except Exception as e:
print(e)
if __name__ == '__main__':
instance_id=get_ec2_instance_id(value='Web1')
stop_ec2(instance_id)
