+86 135 410 16684 如果你在使用中有任何aws上云服务器维护问题,可以随时联系我们!AWSOK你最好的合作伙伴!Mon. - Fri. 10:00-22:00

Amazon Boto3 Library for Python Basics

Amazon Boto3 Library for Python Basics

Amazon Boto3 Library for Python Basics

There is little documentation on using the boto3 library to interact with Amazon’s massive library and the documentation that I found seemed to be outdated as I was getting Key and Attribute errors even with copying and pasting directly from documentation; as such I have compiled two of the most basic functionalities one will start out with when building an application around AWS.

It is my hope that this will assist someone who doesn’t have the time to actually dig through the code, documentation and hack away at a solution.

Create an Instance

Below we will simply make a Amazon Linux AMI micro instance, note that you will need to pass a SubnetId attribute to the create_instances method in order to create a Amazon Linux AMI; however if you skipped just to the code boto3 will throw an Error for you.

  1. #amazon.py
  2. from flask_restful import Resource, Api, request
  3. from flask_jwt import jwt_required
  4. from boto3.session import Session
  5. from botocore.exceptions import ClientError
  6. import boto, boto3
  7.  
  8.  
  9. class AmazonCreateEC2(Resource):
  10. @jwt_required()
  11. def post(self):
  12. data = request.get_json(force=True)
  13. term = data.get(‘term’)
  14. ”’
  15. DEV: HardCode
  16. PROD: DB Pull – 2 Way Encrypt
  17. ”’
  18. session = Session(
  19. aws_access_key_id=,
  20. aws_secret_access_key=,
  21. region_name=‘us-east-1′,
  22. )
  23. ec2 = session.resource(‘ec2′)
  24. ec2_us_east_1 = session.resource(‘ec2′, region_name=‘us-east-1′)
  25. try:
  26. data = ec2.create_instances(
  27. ImageId=‘ami-e3106686′,
  28. MinCount=1,
  29. MaxCount=1,
  30. InstanceType=‘t2.micro’,
  31. )
  32. return {“success”: “Created instance”, “data”: data}
  33. except ClientError as e:
  34. return {“error”: e.message}

Get All Running Instances Data

And here we will get all running instances running in the us-east-1 region. Fortunately, I manually typed all of those wonderful attributes for you so you get a nice hash of hashes / dict of dicts or whatever the cool kids are saying nowadays (looks up rubyism for HoH)…

  1. class AmazonReadEC2(Resource):
  2. @jwt_required()
  3. def get(self):
  4. session = Session(
  5. aws_access_key_id=,
  6. aws_secret_access_key=,
  7. region_name=‘us-east-1′,
  8. )
  9. ec2 = session.resource(‘ec2′)
  10. instances = ec2.instances.filter(
  11. Filters=[{‘Name’: ‘instance-state-name’, ‘Values’: [‘running’]}])
  12. i_json = {}
  13. for instance in instances:
  14. i_json[instance.id] = {
  15. “ami_launch_index”: instance.ami_launch_index,
  16. “architecture”: instance.architecture,
  17. “client_token”: instance.client_token,
  18. “ebs_optimized”: instance.ebs_optimized,
  19. “hypervisor”: instance.hypervisor,
  20. “iam_instance_profile”: instance.iam_instance_profile,
  21. “image_id”: instance.image_id,
  22. “instance_id”: instance.instance_id,
  23. “instance_lifecycle”: instance.instance_lifecycle,
  24. “instance_type”: instance.instance_type,
  25. “kernel_id”: instance.kernel_id,
  26. “key_name”: instance.key_name,
  27. “launch_time”: str(instance.launch_time),
  28. “monitoring”: instance.monitoring,
  29. “placement”: instance.placement,
  30. “platform”: instance.platform,
  31. “private_dns_name”: instance.private_dns_name,
  32. “private_ip_address”: instance.private_ip_address,
  33. “product_codes”: instance.product_codes,
  34. “public_dns_name”: instance.public_dns_name,
  35. “public_ip_address”: instance.public_ip_address,
  36. “ramdisk_id”: instance.ramdisk_id,
  37. “root_device_name”: instance.root_device_name,
  38. “root_device_type”: instance.root_device_type,
  39. “security_groups”: instance.security_groups,
  40. “source_dest_check”: instance.source_dest_check,
  41. “spot_instance_request_id”: instance.spot_instance_request_id,
  42. “sriov_net_support”: instance.sriov_net_support,
  43. “state”: instance.state,
  44. “state_reason”: instance.state_reason,
  45. “state_transition_reason”: instance.state_transition_reason,
  46. “subnet_id”: instance.subnet_id,
  47. “tags”: instance.tags,
  48. “virtualization_type”: instance.virtualization_type,
  49. “vpc_id”: instance.vpc_id,
  50. }
  51. return i_json

Check if a Key exists in S3

A new addition to this page since the last time I’d updated it. You can try an load the object via the s3 resource and it will throw a 404 error to be catched to test if a key exists in AWS S3

  1. #!/usr/bin/env python
  2. import os
  3. from botocore.exceptions import ClientError
  4. from boto3.session import Session
  5.  
  6. # Create AWS Session
  7. session = Session(
  8. aws_access_key_id=‘123’,
  9. aws_secret_access_key=‘123’,
  10. region_name=‘us-east-1′,
  11. )
  12. s3 = session.resource(‘s3′)
  13. obj = s3.Object(‘bucketname’, ‘thing.txt’)
  14. try:
  15. obj.load()
  16. except ClientError:
  17. print “Key doesn’t exist in bucket”

Well, that’s some features and I hope that helps someone on the way to interfacing with AWS via Python and Boto3.