Skip to content

Instantly share code, notes, and snippets.



Last active Nov 7, 2018
What would you like to do?
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
$ 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
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
$ fab running do -- tail /var/log/foobar.log
Example use in production:
def create(n=1):
inst = ec2.create_instances(ImageId='ami-0b0a60c0a2bd40612', MinCount=1, MaxCount=int(n), InstanceType='t2.micro')
def running():
env.filter = ['running']
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']}])
def do():
env.hosts = []
for i in get_instances():
def show():
for i in get_instances():
print(, i.instance_type, i.state)
def stop():
def start():
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment