AWS EC2 Lifecycle Automation with Python

An EC2-hosted game server can incur costs while idle. This project provides a controlled way to start, stop, and inspect selected instances without granting users direct AWS console access.

A Discord bot manages the selected EC2 instance lifecycle through defined commands and scoped AWS permissions.

EC2 control via boto3

The AWS side is handled entirely through boto3, the AWS Python SDK. The bot uses a restricted IAM role that can only start, stop, and reboot specific tagged instances. It has no other AWS permissions, so even if credentials were somehow compromised, the blast radius is minimal.

def start_instance(instance_id):
    ec2 = boto3.client("ec2", region_name=REGION)
    ec2.start_instances(InstanceIds=[instance_id])
    waiter = ec2.get_waiter("instance_running")
    waiter.wait(InstanceIds=[instance_id])
    return get_public_ip(instance_id)

Instance discovery uses EC2 tags. The bot only manages instances tagged with the Discord Guild ID, which prevents it from accidentally touching other instances in the account.

Discord commands

The bot exposes a small set of commands:

Pterodactyl integration

Pterodactyl is a game server management panel. It handles the actual game server process, player management, and resource limits. The bot optionally integrates with the Pterodactyl API to start or stop the game server process independently of the EC2 instance, which is useful for games where you want the instance running but the server stopped.

Uptime tracking

A local SQLite database records every start and stop event with timestamps. The .totaluptime command queries this to show cumulative hours, useful for splitting costs among players, or just knowing how much you've actually used the server this month.

On-demand operation can reduce idle compute costs; the outcome depends on instance type, region, usage patterns, and other AWS charges.

Deployment

The bot runs in Docker, with the docker-compose.yml handling environment variable injection for AWS credentials, Discord token, and Pterodactyl API key. The README walks through IAM setup, EC2 tagging, and Discord bot creation from scratch.


← Back to all posts  ·  View on GitHub ↗