How do I configure a script to automatically run when I start a hibernated Amazon Linux 2023 EC2 instance?

2 minute read

I want a script to automatically run when I start my hibernated Amazon Linux 2023 (AL2023) Amazon Elastic Compute Cloud (Amazon EC2) instance.


To run a script when you start a hibernated AL2023 instance, create a systemd script that runs a custom shell script after

Complete the following steps:

1.    Launch an instance with the hibernation option turned on.

Note: You can't turn hibernation on or off after you launch the instance.

2.    Use SSH to log in to the instance, and then create a unit file in /etc/systemd/system:

sudo touch /etc/systemd/system/myscripttest.service

Note: The preceding example names the unit file myscripttest.service. However, you can change this name.

3.    Place the script under the /etc/pm/sleep.d/ directory.

4.    Run the following command to give the script run permissions. Replace file_path with the path to your unit file and script_name with the name of your script:

sudo chmod +x /file_path/

5.    Use a text editor to add the following content to the unit file. Replace unit_name with the name of your unit file and script_path with the path to your script:

Description=Run unit_name

Example file:

Description=Run myscripttest

6.    Run the following command to turn on the unit. Replace myscripttest-service with the name of your unit file:

sudo systemctl enable myscripttest.service

7.    Start the hibernated instance. Wait for the instance status to change to running.

8.    Check the service logs to verify that the script ran. Replace myscripttest.service with your unit file:

journalctl -u myscripttest.service
AWS OFFICIALUpdated 4 months ago