# 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](https://zato.io/docs/dev/examples/cloud/aws/index.html) 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 {#describing-instances}

```python
# -*- 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 {#starting-and-stopping-instances}

```python
# -*- 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 {#working-with-tags}

```python
# -*- 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 {#more-resources}

- [AWS integrations overview](https://zato.io/docs/dev/examples/cloud/aws/index.html)
- [AWS tutorial](https://zato.io/docs/dev/examples/cloud/aws/tutorial.html)
- [boto3 EC2 reference](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html)

## Learn more {#learn-more}

- [Development documentation](https://zato.io/docs/dev/) - The complete reference for writing services
- [Requests and responses](https://zato.io/docs/dev/request-response/) - What a service receives, what it returns and how both are structured
- [Integration examples](https://zato.io/docs/dev/examples/) - Ready-made code for the systems you are likely to connect to
- [IDE and debugging](https://zato.io/docs/dev/ide/) - Write services in the Dashboard or in your own editor
- [Data models](https://zato.io/docs/dev/model/) - Declare inputs and outputs and have them validated for you
- [In-depth API tutorial](https://zato.io/tutorials/main/01.html) - The full platform tutorial, from installation to production patterns
