Python AWS EC2

EC2 instances - describing, starting, stopping and tagging them from Python services.

Zato lets you manage Amazon EC2 instances directly from your Python services. You create an AWS connection in the Dashboard, and the EC2 client is available under conn.ec2 - the same client that boto3.client('ec2') returns, with credentials and configuration managed for you.

Describing instances

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class ListRunningInstances(Service):

    def handle(self):

        # Get the connection by its Dashboard name
        conn = self.aws['My AWS']

        # Only instances that are currently running
        response = conn.ec2.describe_instances(
            Filters=[{'Name': 'instance-state-name', 'Values': ['running']}],
        )

        # Collect their IDs and types
        instances = []
        for reservation in response['Reservations']:
            for instance in reservation['Instances']:
                instances.append({
                    'instance_id': instance['InstanceId'],
                    'instance_type': instance['InstanceType'],
                })

        self.response.payload = {'instances': instances}

Starting and stopping instances

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class StopInstance(Service):

    input = 'instance_id'

    def handle(self):

        conn = self.aws['My AWS']

        # Stop the instance and report the state transition
        response = conn.ec2.stop_instances(InstanceIds=[self.request.input.instance_id])

        state_change = response['StoppingInstances'][0]
        self.response.payload = {
            'previous': state_change['PreviousState']['Name'],
            'current': state_change['CurrentState']['Name'],
        }

Starting an instance back up is symmetrical - call conn.ec2.start_instances(InstanceIds=[...]).

Working with tags

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class TagInstance(Service):

    input = 'instance_id', 'environment'

    def handle(self):

        conn = self.aws['My AWS']

        conn.ec2.create_tags(
            Resources=[self.request.input.instance_id],
            Tags=[{'Key': 'Environment', 'Value': self.request.input.environment}],
        )

More resources

Learn more