Try using the new boto3
. Reference → http://boto3.readthedocs.org/en/latest/
With pip. Ver is 0.0.6.
$ sudo pip install boto3
$ sudo pip list | grep boto3
boto3 (0.0.6)
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)
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