boto3 (AWS SDK for Python) Note

Try using the new boto3. Reference → http://boto3.readthedocs.org/en/latest/

Installation

With pip. Ver is 0.0.6.

$ sudo pip install boto3
$ sudo pip list | grep boto3
boto3 (0.0.6)

Get EC2 instance information

Reproduce something like $ aws ec2 describe-instances.

>>> import boto3
>>> client = boto3.client('ec2')
>>> response = client.describe_instances()
>>> type(response)
<type 'dict'>

It returns as a dict type. You can leave it as it is, but if you try to convert it to JSON, an error will occur.

>>> import json
>>> res_json = json.dumps(response)

TypeError: datetime.datetime(2014, 4, 4, 11, 34, 13, tzinfo=tzutc()) is not JSON serializable

After a little research, it seems to be not compatible with datetime type, bson ( Binary JSON) and so on.

However, on Mac, it seems to be useless if only bson is included, so insert pymongo and so on.

$ sudo pip install pymongo
>>> from bson import json_util
>>> res_json = json.dumps(response, default=json_util.default)
>>> type(res_json)
<type 'str'>

If it is as it is, it is information of all instances, so narrow it down with Filters. When narrowed down by Instance ID.

>>> response = client.describe_instances(Filters=[{'Name':'instance-id','Values':['i-XXXXXXXX']}])

When Filter is made variable and narrowed down by Tag name.

>>> f = [{'Name':'tag-value', 'Values':['XXXXXXXX']}]
>>> response = client.describe_instances(Filters=f)

EC2 instance operation

Start / stop the instance object. First, try to get the instance object by specifying InstanceID.

>>> import boto3
>>> ec2 = boto3.resource('ec2')
>>> instance = ec2.Instance('i-XXXXXXXX')
>>> instance.private_ip_address
"10.X.X.X"

The other is to get it from the Instances Collection. For example, from the tag name. However, it takes more time as it loops all instances.

>>> import boto3
>>> ec2 = boto3.resource('ec2')
>>> tag_name = "TAG_NAME"
>>> instance = [i for i in ec2.instances.all() for t in i.tags if t["Value"] == tag_name][0]
>>> instance.private_ip_address
"10.X.X.X"

Operate on the instance object acquired by either method. Instance stop. Wait is possible. The self-loop is no longer necessary.

>>> instance.stop()
{u'StoppingInstances': [{u'InstanceId': 'i-XXXXXXXX', u'CurrentState': {u'Code': 64, u'Name': 'stopping'}, u'PreviousState': {u'Code': 16, u'Name': 'running'}}], 'ResponseMetadata': {'HTTPStatusCode': 200, 'RequestId': 'AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA'}}
>>> instance.wait_until_stopped()
>>> instance.state
{u'Code': 80, u'Name': 'stopped'}

Instance launch. This is also possible to wait.

>>> instance.start()
{u'StartingInstances': [{u'InstanceId': 'i-XXXXXXXX', u'CurrentState': {u'Code': 0, u'Name': 'pending'}, u'PreviousState': {u'Code': 80, u'Name': 'stopped'}}], 'ResponseMetadata': {'HTTPStatusCode': 200, 'RequestId': 'AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA'}}
>>> instance.wait_until_running()
>>> instance.state
{u'Code': 16, u'Name': 'running'}

Recommended Posts

boto3 (AWS SDK for Python) Note
Authentication information used by Boto3 (AWS SDK for Python)
AWS SDK for Python (Boto3) development in Visual Studio 2017
Use AWS SDK for Python (boto) under Proxy environment
Get note information using Evernote SDK for Python 3
Call Polly from the AWS SDK for Python
Use Resource API rather than Client API in AWS SDK for Python (Boto3)
[Cloudian # 1] Try to access object storage with AWS SDK for Python (boto3)
3 months note for starting Python
Fleet provisioning with AWS IoT SDK for Python v2
Note: Python
AWS Layer Creation Script for python
Python note
Note for Pyjulia calling Julia from Python
2016-10-30 else for Python3> for:
python [for myself]
Python study note_002
Note: Python Decorator
Python programming note
[Python] Learning Note 1
Python study note_004
Python study note_003
[Note] openCV + python
Python beginner's note
Note for formatting numbers with python format function
Manage AWS nicely with the Python library Boto
About Python for loops
[Note] future sentence ~ Python ~
Python basics ② for statement
[AWS IoT] Register things in AWS IoT using the AWS IoT Python SDK
[Note] The story of setting up the SDK for Python of Azure IoT Hub on Linux
[AWS] Operate SQS from SDK (send / receive) [Python] [Node.js]
[Python] Local → Procedure for uploading files to S3 (boto3)
About Python, for ~ (range)
python textbook for beginners
Refactoring tools for Python
Support for Python 2.7 runtime on AWS Lambda (as of 2020.1)
python for android Toolchain
Note to daemonize python
Note: python Skeleton Nya
Create a Layer for AWS Lambda Python with Docker
Python basic grammar note (4)
Python basic grammar note (3)
AWS CDK with Python
Python Tkinter Primer Note
Notes on writing config files for Python Note: configparser
OpenCV for Python beginners
Install Python (for Windows)
[Python] for statement error
Python environment for projects
Install AWS SDK for PHP on AWS EC2 (PHP7.2 + Apache2.4.41 + OPCashe + Composer)
[Note] List of basic commands for building python / conda environment
Try a similar search for Image Search using the Python SDK [Search]
Create a Twitter BOT with the GoogleAppEngine SDK for Python
Python memo (for myself): Array
About Fabric's support for Python 3
Python list, for statement, dictionary
[Python] Scraping in AWS Lambda
Modern Python for intermediate users
Learning flow for Python beginners
Python 3.6 installation procedure [for Windows]