Skip to content

Instantly share code, notes, and snippets.

@chrismckinnel
Created July 14, 2015 13:51
Show Gist options
  • Save chrismckinnel/d23a82b620c4b4d0d93b to your computer and use it in GitHub Desktop.
Save chrismckinnel/d23a82b620c4b4d0d93b to your computer and use it in GitHub Desktop.
Better connections in boto2

So this thing:

class BotoConnection(object):

    def __new__(cls, profile_name, services):
        if not hasattr(cls, '__instance__'):
            cls.__instance__ = super(BotoConnection, cls)\
                .__new__(cls, profile_name, services)

        return cls.__instance__

    def __init__(self, profile_name, services):
        self.__connect_to_boto_services(profile_name, services)

    def __connect_to_boto_services(self, profile_name, services):
        for service_name in services:
            attribute_name = service_name.split('.')[-1]

            if hasattr(self, attribute_name):
                raise Exception("'%s' service connection already exists. Did "
                                "you define the same service twice, or have "
                                "two services with the same module "
                                "name?" % attribute_name)

            service = import_module(service_name)
            connection = service.connect_to_region(
                env.region, profile_name=env.profile_name)
            setattr(self, attribute_name, connection)

Allows me to go:

# Boto connections
services = [
    'boto.ec2',
    'boto.ec2.elb',
    'boto.ec2.autoscale',
    'boto.ec2.cloudwatch',
    'boto.route53',
    'boto.s3']
env.connections = utils.BotoConnection(
    profile_name=env.profile_name, services=services)

In my fabconfig.py and then:

    reservations = env.connections.ec2.get_all_instances(
        instance_ids=[instance_id])

In my build modules.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment