Skip to content

Instantly share code, notes, and snippets.

@shyal
Last active November 7, 2018 18:09
Show Gist options
  • Save shyal/b3fa89a49aa2b30d58b9e431fdede558 to your computer and use it in GitHub Desktop.
Save shyal/b3fa89a49aa2b30d58b9e431fdede558 to your computer and use it in GitHub Desktop.
import boto3
from fabric.api import sudo, task, env
import os
env.key_filename = os.path.expanduser('~/.ssh/key.pem')
env.user = 'ubuntu'
env.filter = ['running', 'stopped']
ec2 = boto3.resource('ec2')
"""
This is a very simple example of what can sysadmin tasks can be done with Python. Fabric enables building powerful DSLs for remote admin.
Requirements: python3, pip3, fabric3, boto3
https://www.fabfile.org
https://boto3.amazonaws.com/v1/documentation/api/latest/index.html
Usage:
$ fab create:5 # create 5 micro Ubuntu EC2 instances
$ fab running show # show running instances
$ fab running stop # stop the running instances
$ fab stopped start # start the stopped instances
Note:
certificate is not specified, so currently you cannot ssh into these machines (if you look up the boto3 docs, it's easy to do).
Had we set up the keyfie, we could do:
$ fab running do -- uname -a
or
$ fab running do -- tail /var/log/foobar.log
Example use in production:
https://ioloop.io/blog/ftrack-aws/ftrack-aws.html
"""
@task
def create(n=1):
inst = ec2.create_instances(ImageId='ami-0b0a60c0a2bd40612', MinCount=1, MaxCount=int(n), InstanceType='t2.micro')
print(inst)
@task
def running():
env.filter = ['running']
@task
def stopped():
env.filter = ['stopped']
def get_instances():
return ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': env.filter}, {'Name': 'instance-type', 'Values': ['t2.micro']}])
@task
def do():
env.hosts = []
for i in get_instances():
env.hosts.append(i.public_ip_address)
@task
def show():
for i in get_instances():
print(i.id, i.instance_type, i.state)
@task
def stop():
get_instances().stop()
@task
def start():
get_instances().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment