Skip to content

Instantly share code, notes, and snippets.

@npyoung
Created November 4, 2018 09:39
Show Gist options
  • Save npyoung/ca16bef088ebd0f3d936c09249b1c1fc to your computer and use it in GitHub Desktop.
Save npyoung/ca16bef088ebd0f3d936c09249b1c1fc to your computer and use it in GitHub Desktop.
Some shortcuts to make your life easier when your work machine lives in EC2
#!/usr/bin/env python
# Drop this in your ~/bin folder and chmod u+x it for maximum slickness
import click
import boto3
import subprocess
ec2 = boto3.resource('ec2')
def instances_by_name(name):
response = ec2.instances.filter(
Filters=[
{
'Name': 'tag:Name',
'Values': [name]
}
]
)
return response
@click.group()
def main():
pass
@main.command()
@click.argument('name', type=str)
def start(name):
instances = instances_by_name(name)
for instance in instances:
instance.start()
@main.command()
@click.argument('name', type=str)
def attach(name):
instances = instances_by_name(name)
ips = [instance.private_ip_address for instance in instances]
if len(ips) == 1:
ip = ips[0]
print("Logging into {:s}".format(ip))
subprocess.Popen(["ssh",
"-oStrictHostKeyChecking=no",
ip])
else:
raise ValueError("There were {:d} instances by that name".format(len(ips)))
@main.command()
@click.argument('name', type=str)
def stop(name):
instances = instances_by_name(name)
for instance in instances:
instances.stop()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment