automate-start-stop-server / stop-server.py
stop-server.py
Raw
import boto3

def lambda_handler(event, context):
    try:
        client = boto3.client('ec2')
        response = client.describe_instances(
            Filters=[
                {
                    'Name': 'instance-state-name',
                    'Values': [
                        'running',
                    ]
                },
            ],
        )
        if (len(response['Reservations']) != 0):
            instance_id = response['Reservations'][0]['Instances'][0]['InstanceId']

            stop_response = client.stop_instances(
                InstanceIds=[
                    instance_id,
                ]
            )
            print(stop_response)
            #print(instance_id)
        else:
            print('No running instance')
    except:
        print('Unable to stop instance with id {}'.format(instance_id))

'''if __name__ == "__main__":
    lambda_handler()'''