How do I run a command on an existing EC2 Windows instance when I reboot or start the instance?
Last updated: 2019-10-18
I want to run a custom script on my existing Amazon Elastic Compute Cloud (Amazon EC2) Windows instance when I reboot or start the instance. How can I do this?
You can run a script that executes after the instance reboots or starts by adding it to user data. User data is processed by EC2Config (Windows Server 2012 R2 and earlier) or EC2Launch (Windows Server 2016 and later).
When you add the script to user data, you must enclose it within a special tag. This tag determines whether the commands run in a Command Prompt window or run in Windows PowerShell. For more information, see Running Commands on Your Windows Instance at Launch.
You can’t add or change user data if the instance is running, but you can view it. To add or change user data, the instance must be in the stopped state. User data scripts aren't automatically executed when you reboot or start the instance. You can enable user data execution the next time, or every time, that you reboot or start the instance.
Warning: Before you stop an instance, be aware of the following:
- If you're not using an Elastic IP Address, the public IP address is released when you stop the instance.
- If this instance has an instance store volume, any data on it is lost when the instance is stopped.
- If the instance shutdown behavior is set to Terminate, the instance terminates when it is stopped.
- If the instance is part of an Auto Scaling group, first detach the instance from the Auto Scaling Group. After you stop and start the instance, attach the instance back to the Auto Scaling group.
For more information, see Stop and Start Your Instance.
2. For Windows Server 2016 or later, open a Windows PowerShell command window and then run the following command:
For Windows Server 2012 R2 or earlier, open C:\Program Files\Amazon\Ec2ConfigService\Ec2ConfigServiceSetting.exe.
Then, for User Data, select Enable UserData execution for next service start.
3. From the Amazon EC2 console, stop the instance.
4. Select the instance. For Actions, choose Instance Settings, View/Change User Data.
5. Add or update the user data, and then choose Save.
Note: To execute user data scripts every time you reboot or restart the instance, add the following:
6. Start the instance. The user data scripts executes as part of the instance start process.
For additional troubleshooting, EC2Launch and EC2Config log files contain the output from the standard output and standard error streams. Log files are located as follows:
- EC2Launch: C:\ProgramData\Amazon\EC2-Windows\Launch\Log\UserdataExecution.log
- EC2Config: C:\Program Files\Amazon\Ec2ConfigService\Logs\Ec2Config.log