-
Notifications
You must be signed in to change notification settings - Fork 1
/
awsboto.py
89 lines (67 loc) · 2.25 KB
/
awsboto.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#one line comment
import boto.ec2
import yaml
def save_config(query):
config = dict(([x.split('=') for x in query.split(',')]))
stream = file('./aws.conf', 'w')
# config['region'] = query
yaml.dump(config, stream)
def load_config():
stream = file('./aws.conf', 'r')
return yaml.load(stream)
def get_instances():
config = load_config()
if 'region' in config:
region = config['region']
else:
region = 'us-west-2'
boto_ec2 = boto.ec2.connect_to_region(region)
rsv = boto_ec2.get_all_instances()
idata = {}
for r in rsv:
for i in r.instances:
tag_value = i.tags.get('Name', '')
idata[instance_to_string(i)] = i
return idata
def start_instance(id):
config = load_config()
if 'region' in config:
region = config['region']
else:
region = 'us-west-2'
boto_ec2 = boto.ec2.connect_to_region(region)
instance = boto_ec2.get_all_instances(instance_ids=[id])
return instance[0].instances[0].start()
def stop_instance(id):
config = load_config()
if 'region' in config:
region = config['region']
else:
region = 'us-west-2'
boto_ec2 = boto.ec2.connect_to_region(region)
instance = boto_ec2.get_all_instances(instance_ids=[id])
return instance[0].instances[0].stop()
def instance_to_string(i):
#if 'Name' in i.tags.keys():
config = load_config()
tag_value = i.tags.get('Name', '')
ip = i.private_ip_address if config.get('ip_type') == 'private' else i.ip_address
return i.id + ", " + tag_value + ", " + str(ip) + ", " + i.state
def search_instances(query):
# CACHE['expires'] = 30 # Seconds to expire cache
idata = get_instances()
search_results = []
for k in idata.keys():
stringify_instance = ("".join(str(idata[k].__dict__.values()))).lower()
queries = query.split(" ")
match = 0
for q in queries:
if q in stringify_instance:
match = match + 1
if match == len(queries): # all user queries matched, we got a winner.
search_results.append(idata[k])
return search_results
if __name__ == "__main__":
import sys
for i in search_instances(sys.argv[1]):
print instance_to_string(i)