Self stopping EC2 once task complete?

I have a lambda starting an EC2 hourly. The (windows) operating system on the EC2 runs a script on startup. The task can take anything from 1 minute to 45 minutes. I would like the EC2 to stop once the script has run.

I can think of one way to achieve this. I could install the aws cli on the EC2 itself and run something like aws ec2 stop-instances --instance-ids i-07c1849fe7abcdef. Doing so feels weird. Is there a better way?


For complete clarity, I don't want to simply set a timer on the instance. Say I set a 45 minute timer, I would pay for 45 mniutes even when the task only takes 3 minutes. I would like the instance to stop immediately after the script has run, no matter how long the script took to run.

1 answer

  • answered 2019-06-12 03:34 John Rotenstein

    Your instance can use the operating system command to Power Off.

    On Linux, it would be:

    sudo shutdown now -h

    (The -h means Halt, which will trigger the power-off. If not included, the operating system will stop but the instance will keep running.)

    This can be used in conjunction with the Instance Initiated Shutdown Behavior, which can either:

    • Stop the instance (sounds like what you seek)
    • Terminate the instance (good if a new instance is launched each time)

    Shutdown Behavior

    No IAM permissions are required for this method.