Skip to content

Commit d3a8c0a

Browse files
Filter instances by project. Also stop and start instances.
1 parent a4fc0db commit d3a8c0a

File tree

2 files changed

+53
-5
lines changed

2 files changed

+53
-5
lines changed

README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,7 @@ In my case "shotty" or anyname you provide with config file, uses the configurat
1010
`aws configure --profile shotty`
1111

1212
## How to run it
13-
`pipenv run python shotty/shotty.py`
13+
`pipenv run python shotty/shotty.py <command> <--project=PROJECT>`
14+
15+
*command* is list, start, or stop
16+
*project* is optional

shotty/shotty.py

Lines changed: 49 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,29 @@
44
session = boto3.Session(profile_name='shotty')
55
ec2 = session.resource('ec2')
66

7-
@click.command()
8-
def list_instances():
7+
def filter_instances(project):
8+
instances = []
9+
10+
if project:
11+
filters = [{'Name':'tag:Project', 'Values':[project]}]
12+
instances = ec2.instances.filter(Filters=filters)
13+
else:
14+
instances = ec2.instances.all()
15+
16+
return instances
17+
18+
@click.group()
19+
def instances():
20+
"""Commands for instances"""
21+
@instances.command('list')
22+
@click.option('--project', default=None,
23+
help="Only instances for project (tag Project:<name>)")
24+
def list_instances(project):
925
"List EC2 instances"
10-
for i in ec2.instances.all():
26+
27+
instances = filter_instances(project)
28+
29+
for i in instances:
1130
print(', '.join((
1231
i.id,
1332
i.instance_type,
@@ -16,5 +35,31 @@ def list_instances():
1635
i.public_dns_name)))
1736
return
1837

38+
@instances.command('stop')
39+
@click.option('--project', default=None,
40+
help='Only instances for project')
41+
def stop_instances(project):
42+
"Stop EC2 instances"
43+
44+
instances = filter_instances(project)
45+
46+
for i in instances:
47+
print("Stopping {0}...".format(i.id))
48+
i.stop()
49+
return
50+
51+
@instances.command('start')
52+
@click.option('--project', default=None,
53+
help='Only instances for project')
54+
def start_instances(project):
55+
"Stop EC2 instances"
56+
57+
instances = filter_instances(project)
58+
59+
for i in instances:
60+
print("Starting {0}...".format(i.id))
61+
i.start()
62+
return
63+
1964
if __name__ == '__main__':
20-
list_instances()
65+
instances()

0 commit comments

Comments
 (0)