Get information about EC2 instances with arbitrary prefixes in instance names with boto

What is boto ??

It seems to be an SDK for Python that operates AWS. (I want a code name for SDKs other than Python

http://aws.amazon.com/jp/sdkforpython/

Preparation

Installation

It seems easy to enter with the pip command

$ sudo yum install python-pip
$ sudo pip install boto

Setting credentials (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY)

I don't want to write solid code, so I define it in the configuration file. Apparently, it seems to search in the order of "/etc/boto.cfg", "~ / .boto", and this time I want to keep it for each user, so define it in ~ / .boto according to the following format

[Credentials]
aws_access_key_id = <your access key>
aws_secret_access_key = <your secret key>

https://code.google.com/p/boto/wiki/BotoConfig

Extra: I'm addicted to this. .. ..

I couldn't find it in the document, but when I look at the boto implementation, it checks if "AWS_CREDENTIAL_FILE" is defined in the environment variable, and if it is defined, the logic gives priority to that setting.

https://github.com/boto/boto/blob/b9dbaad430fc35160d86fb921c4c1f75d66b6ddf/boto/pyami/config.py#L66-L77

Initially, when importing boto, an error occurred in the ConfigPaser class and it became "Eh ???". The cause was that the header (first line) of the file set in AWS_CREDENTIAL_FILE contained the string "==========". I don't think anyone suffers from the same error, but for reference. (It is a mystery why such a header was used in the first place.

Try to implement

import boto
import boto.ec2
from boto.ec2.connection import EC2Connection
from boto.ec2.regioninfo import RegionInfo
import re

def get_ec2_instances(region_end_point, re_pt):
    region = RegionInfo(endpoint = region_end_point)
    ec2_connection = boto.ec2.connection.EC2Connection(region = region)

    result = []
    instances = [i for r in ec2_connection.get_all_instances() for i in r.instances]
    for i in instances:
        if re_pt.match(i.tags['Name']):
            result.append(i)

    return result

if __name__ == "__main__":
    re_pt = re.compile('production')
    ec2_instance_list = get_ec2_instances('ec2.ap-northeast-1.amazonaws.com', re_pt)

    print(ec2_instance_list)

Now you can get the instance information of EC2 with the prefix "production" as the instance name from the Tokyo region.

Impressions etc.

Recommended Posts

Get information about EC2 instances with arbitrary prefixes in instance names with boto
code-server online environment (3) Launch an EC2 instance with Boto3
Stop an instance with a specific tag in Boto3
Get information with zabbix api
Get Alembic information with Python